You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by ge...@apache.org on 2017/06/06 13:41:43 UTC

[3/5] brooklyn-server git commit: more unit tests

more unit tests


Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/f843ac87
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/f843ac87
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/f843ac87

Branch: refs/heads/master
Commit: f843ac87eab4353a3d9a51e68b0fe8b699c0d8da
Parents: a0ae7b3
Author: Andrea Turli <an...@gmail.com>
Authored: Tue Jun 6 10:38:42 2017 +0200
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Jun 6 10:38:42 2017 +0200

----------------------------------------------------------------------
 .../core/effector/http/HttpCommandEffector.java | 29 ++++++++++++----
 .../http/HttpCommandEffectorHttpBinTest.java    | 36 +++++++++++++++++---
 .../effector/http/HttpCommandEffectorTest.java  | 21 ++++++++++++
 .../effector/http/url-encoded-response.json     | 16 +++++++++
 4 files changed, 90 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f843ac87/core/src/main/java/org/apache/brooklyn/core/effector/http/HttpCommandEffector.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/effector/http/HttpCommandEffector.java b/core/src/main/java/org/apache/brooklyn/core/effector/http/HttpCommandEffector.java
index e49577c..8bef573 100644
--- a/core/src/main/java/org/apache/brooklyn/core/effector/http/HttpCommandEffector.java
+++ b/core/src/main/java/org/apache/brooklyn/core/effector/http/HttpCommandEffector.java
@@ -53,6 +53,7 @@ import org.apache.brooklyn.util.http.executor.HttpRequest;
 import org.apache.brooklyn.util.http.executor.HttpResponse;
 import org.apache.brooklyn.util.http.executor.UsernamePassword;
 import org.apache.brooklyn.util.http.executor.apacheclient.HttpExecutorImpl;
+import org.apache.brooklyn.util.text.Strings;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -60,6 +61,7 @@ import com.google.common.annotations.Beta;
 import com.google.common.base.Enums;
 import com.google.common.base.Joiner;
 import com.google.common.base.Optional;
+import com.google.common.base.Throwables;
 import com.google.common.io.ByteStreams;
 import com.google.common.net.HttpHeaders;
 import com.jayway.jsonpath.JsonPath;
@@ -72,7 +74,8 @@ import com.jayway.jsonpath.JsonPath;
  * It deals with some {@link HttpHeaders.CONTENT_TYPE} namely 'application/json' (as default) and 'application/x-www-form-urlencoded'. 
  * In the latter case, a map payload will be URLEncoded in a single string
  * 
- * With optional JSON_PATH config key, the effector will extract a section of the json response.
+ * With optional JSON_PATH config key, the effector will extract a section of the json response. 
+ * Notice if both JSON_PATH and JSON_PATHS_AND_SENSORS are both defined, JSON_PATH will take precedence. 
  * 
  * Using JSON_PATHS_AND_SENSORS, it is possible to extract one or more values from a json response, and publish them in sensors
  */
@@ -88,7 +91,9 @@ public final class HttpCommandEffector extends AddEffector {
     public static final ConfigKey<Map<String, String>> EFFECTOR_HTTP_HEADERS = new MapConfigKey(String.class, "headers");
     public static final ConfigKey<Object> EFFECTOR_HTTP_PAYLOAD = ConfigKeys.newConfigKey(Object.class, "httpPayload");
     public static final ConfigKey<String> JSON_PATH = ConfigKeys.newStringConfigKey("jsonPath", "JSON path to select in HTTP response");
-    public static final ConfigKey<Map<String, String>> JSON_PATHS_AND_SENSORS = new MapConfigKey(String.class, "jsonPathAndSensors", "json path selector and correspondant sensor name tha will publish the json path extracted value");
+    @Deprecated 
+    public static final ConfigKey<String> PUBLISH_SENSOR = ConfigKeys.newStringConfigKey("publishSensor", "Sensor name where to store json path extracted value");
+    public static final ConfigKey<Map<String, String>> JSON_PATHS_AND_SENSORS = new MapConfigKey(String.class, "jsonPathAndSensors", "json path selector and correspondant sensor name that will publish the json path extracted value");
 
     public static final String APPLICATION_JSON = "application/json";
     public static final String APPLICATION_X_WWW_FORM_URLENCODE = "application/x-www-form-urlencoded";
@@ -128,7 +133,12 @@ public final class HttpCommandEffector extends AddEffector {
             final Map<String, String> headers = EntityInitializers.resolve(allConfig, EFFECTOR_HTTP_HEADERS);
             final Object payload = EntityInitializers.resolve(allConfig, EFFECTOR_HTTP_PAYLOAD);
             final String jsonPath = EntityInitializers.resolve(allConfig, JSON_PATH);
+            final String publishSensor = EntityInitializers.resolve(allConfig, PUBLISH_SENSOR);
             final Map<String, String> pathsAndSensors = EntityInitializers.resolve(allConfig, JSON_PATHS_AND_SENSORS);
+            
+            if(!Strings.isEmpty(jsonPath) && !pathsAndSensors.isEmpty()) {
+                throw new IllegalArgumentException("Both jsonPath and pathsAndSensors are defined, please pick just one to resolve the ambiguity");
+            }
             final HttpExecutor httpExecutor = HttpExecutorImpl.newInstance();
 
             final HttpRequest request = buildHttpRequest(httpVerb, uri, headers, httpUsername, httpPassword, payload);
@@ -148,12 +158,17 @@ public final class HttpCommandEffector extends AddEffector {
             }).build();
 
             String responseBody = (String) queue(t).getUnchecked();
-            
-            if (jsonPath == null && pathsAndSensors.isEmpty()) return responseBody;
 
             if (jsonPath != null) {
-                return JsonPath.parse(responseBody).read(jsonPath, String.class);
-            } else if (!pathsAndSensors.isEmpty()) {
+                String extractedValue = JsonPath.parse(responseBody).read(jsonPath, String.class);
+                if (publishSensor != null) {
+                    LOG.warn("`publishSensor` configuration key is deprecated. PLease prefer `pathsAndSensors`, instead");
+                    entity().sensors().set(Sensors.newStringSensor(publishSensor), extractedValue);
+                }
+                return extractedValue;
+            }
+            
+            if (!pathsAndSensors.isEmpty()) {
                 for (String path : pathsAndSensors.keySet()) {
                     String jsonPathValue = JsonPath.parse(responseBody).read(path, String.class);
                     entity().sensors().set(Sensors.newStringSensor(pathsAndSensors.get(path)), jsonPathValue);
@@ -211,7 +226,7 @@ public final class HttpCommandEffector extends AddEffector {
                                 if (!body.equals("")) body += "&";
                                 body += URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()) + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                             } catch (UnsupportedEncodingException e) {
-                                e.printStackTrace();
+                                throw Throwables.propagate(e);
                             }
 
                         }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f843ac87/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorHttpBinTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorHttpBinTest.java b/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorHttpBinTest.java
index 9a39c07..2f4ceca 100644
--- a/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorHttpBinTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorHttpBinTest.java
@@ -21,6 +21,7 @@ package org.apache.brooklyn.core.effector.http;
 import java.io.IOException;
 import java.net.URI;
 import java.util.List;
+import java.util.concurrent.ExecutionException;
 
 import org.apache.brooklyn.api.effector.Effector;
 import org.apache.brooklyn.api.entity.EntityLocal;
@@ -147,8 +148,6 @@ public class HttpCommandEffectorHttpBinTest {
                         "public", "false",
                         "files", ImmutableMap.of("demo.txt", ImmutableMap.of("content","Demo"))))
                 .configure(HttpCommandEffector.EFFECTOR_HTTP_HEADERS, ImmutableMap.of("Content-Type", "application/json"))
-//                .configure(HttpCommandEffector.JSON_PATH, "$.url")
-//                .configure(HttpCommandEffector.PUBLISH_SENSOR, "result")
                 .configure(HttpCommandEffector.JSON_PATHS_AND_SENSORS, ImmutableMap.of("$.url", "result"))
 
         ).apply(entity);
@@ -163,8 +162,35 @@ public class HttpCommandEffectorHttpBinTest {
                 .configure(HttpCommandEffector.EFFECTOR_NAME, "Httpbin")
                 .configure(HttpCommandEffector.EFFECTOR_URI, serverUrl + "/get?id=myId")
                 .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
-//                .configure(HttpCommandEffector.JSON_PATH, "$.args.id")
-//                .configure(HttpCommandEffector.PUBLISH_SENSOR, "result")
+                .configure(HttpCommandEffector.JSON_PATH, "$.args.id")
+        ).apply(entity);
+
+        String val = entity.invoke(EFFECTOR_HTTPBIN, MutableMap.<String,String>of()).get();
+        Assert.assertEquals(val, "myId");
+    }
+
+    @Test
+    public void testHttpEffectorWithJsonPathWithPublishSensor() throws Exception {
+        new HttpCommandEffector(ConfigBag.newInstance()
+                .configure(HttpCommandEffector.EFFECTOR_NAME, "Httpbin")
+                .configure(HttpCommandEffector.EFFECTOR_URI, serverUrl + "/get?id=myId")
+                .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
+                .configure(HttpCommandEffector.JSON_PATH, "$.args.id")
+                .configure(HttpCommandEffector.PUBLISH_SENSOR, "result")
+        ).apply(entity);
+
+        String val = entity.invoke(EFFECTOR_HTTPBIN, MutableMap.<String,String>of()).get();
+        Assert.assertEquals(val, "myId");
+        Assert.assertEquals(entity.sensors().get(Sensors.newStringSensor("result")), "myId");
+    }
+
+    @Test(expectedExceptions = ExecutionException.class)
+    public void testHttpEffectorWithJsonPathWithPathsAndSensors() throws Exception {
+        new HttpCommandEffector(ConfigBag.newInstance()
+                .configure(HttpCommandEffector.EFFECTOR_NAME, "Httpbin")
+                .configure(HttpCommandEffector.EFFECTOR_URI, serverUrl + "/get?id=myId")
+                .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
+                .configure(HttpCommandEffector.JSON_PATH, "$.args.id")
                 .configure(HttpCommandEffector.JSON_PATHS_AND_SENSORS, ImmutableMap.of("$.args.id", "result"))
         ).apply(entity);
 
@@ -172,7 +198,7 @@ public class HttpCommandEffectorHttpBinTest {
         Assert.assertEquals(val, "myId");
         Assert.assertEquals(entity.sensors().get(Sensors.newStringSensor("result")), "myId");
     }
-    
+
     @Test
     public void testHttpEffectorWithParameters() throws Exception {
         new HttpCommandEffector(ConfigBag.newInstance()

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f843ac87/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorTest.java b/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorTest.java
index d3d5b7f..75d1e03 100644
--- a/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/effector/http/HttpCommandEffectorTest.java
@@ -248,6 +248,27 @@ public class HttpCommandEffectorTest extends BrooklynAppUnitTestSupport {
    }
 
    @Test
+   public void testPayloadWithContentTypeFormUrlEncoded() throws InterruptedException {
+      server.enqueue(jsonResponse("url-encoded-response.json"));
+
+      httpCommandEffector = new HttpCommandEffector(ConfigBag.newInstance()
+              .configure(HttpCommandEffector.EFFECTOR_NAME, EFFECTOR_HTTP_COMMAND.getName())
+              .configure(HttpCommandEffector.EFFECTOR_URI, url("/post"))
+              .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "POST")
+              .configure(HttpCommandEffector.EFFECTOR_HTTP_PAYLOAD, ImmutableMap.of("key", "<img>"))
+              .configure(HttpCommandEffector.EFFECTOR_HTTP_HEADERS, ImmutableMap.of(HttpHeaders.CONTENT_TYPE, HttpCommandEffector.APPLICATION_X_WWW_FORM_URLENCODE))
+              .configure(HttpCommandEffector.JSON_PATH, "$.data")
+      );
+      assertNotNull(httpCommandEffector);
+      TestEntity testEntity = app.createAndManageChild(buildEntitySpec(httpCommandEffector));
+      Object output = testEntity.invoke(EFFECTOR_HTTP_COMMAND, ImmutableMap.of()).getUnchecked(Duration.seconds(1));
+      assertEquals(output, "{\"key\", \"%3Cimg%3E\"}");
+      
+      assertEquals(server.getRequestCount(), 1);
+      assertSent(server, "POST", "/post");
+   }
+   
+   @Test
    public void testHappyPath() throws InterruptedException {
       server.enqueue(jsonResponse("login.json"));
 

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/f843ac87/core/src/test/resources/org/apache/brooklyn/core/effector/http/url-encoded-response.json
----------------------------------------------------------------------
diff --git a/core/src/test/resources/org/apache/brooklyn/core/effector/http/url-encoded-response.json b/core/src/test/resources/org/apache/brooklyn/core/effector/http/url-encoded-response.json
new file mode 100644
index 0000000..30bfc3c
--- /dev/null
+++ b/core/src/test/resources/org/apache/brooklyn/core/effector/http/url-encoded-response.json
@@ -0,0 +1,16 @@
+{
+  "args": {},
+  "data": "{\"key\", \"%3Cimg%3E\"}",
+  "files": {},
+  "form": {},
+  "headers": {
+    "Accept": "*/*",
+    "Content-Length": "16",
+    "Content-Type": "application/json",
+    "Host": "httpbin.org",
+    "User-Agent": "curl/7.49.1"
+  },
+  "json": null,
+  "origin": "93.61.99.89",
+  "url": "http://httpbin.org/post"
+}