Fix Technical Debt, basic JUnit tests for Rest 59/28459/2
authorvdmeer <sven.van.der.meer@ericsson.com>
Wed, 17 Jan 2018 23:13:14 +0000 (23:13 +0000)
committervdmeer <sven.van.der.meer@ericsson.com>
Wed, 17 Jan 2018 23:23:50 +0000 (23:23 +0000)
Basic tests for get and post
(not testing full user/pw/body)

Issue-ID: POLICY-455
Change-Id: I186ebf969abc239e5056199c2fd8da9f3253d2fc
Signed-off-by: vdmeer.sven <sven.van.der.meer@ericsson.com>
controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java
controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestGet.java [new file with mode: 0755]
controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestPair.java [new file with mode: 0755]
controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestPost.java [new file with mode: 0755]

index c74a75c..2540cb2 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.rest;
 
 import java.io.IOException;
 import java.util.Map;
+import java.util.Map.Entry;
 
 import org.apache.http.HttpResponse;
 import org.apache.http.auth.AuthScope;
@@ -39,89 +40,100 @@ import org.slf4j.LoggerFactory;
 
 public class RESTManager {
 
-       private static final Logger logger = LoggerFactory.getLogger(RESTManager.class);
-       
-       public class Pair<A, B> {
-               public final A a;
-               public final B b;
-               
-               public Pair(A a, B b) {
-                       this.a = a;
-                       this.b = b;
-               }
-       }
-
-       public Pair<Integer, String> post(String url, String username, String password, Map<String, String> headers, String contentType, String body) {
-               CredentialsProvider credentials = new BasicCredentialsProvider();
-               credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
-               
-               logger.debug("HTTP REQUEST: {} -> {} {} -> {}", url, username, ((password!=null)?password.length():"-"), contentType);
-               if (headers != null) {
-                       logger.debug("Headers: ");
-                       headers.forEach((name, value) -> {
-                           logger.debug("{} -> {}", name, value);
-                       });
-               }
-               logger.debug(body);
-               
-               try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
-
-                       HttpPost post = new HttpPost(url);
-                       if (headers != null)  {
-                               for (String key : headers.keySet()) {
-                                       post.addHeader(key, headers.get(key));
-                               }
-                       }
-                       post.addHeader("Content-Type", contentType);
-                       
-                       StringEntity input = new StringEntity(body);
-                       input.setContentType(contentType);
-                       post.setEntity(input);
-                       
-                       HttpResponse response = client.execute(post);
-                       if (response != null) {
-                               String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
-                               logger.debug("HTTP POST Response Status Code: {}", response.getStatusLine().getStatusCode());
-                               logger.debug("HTTP POST Response Body:");
-                               logger.debug(returnBody);
-                               
-                               return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody);
-                       } else {
-                               logger.error("Response from {} is null", url);
-                               return null;
-                       }
-               } catch (Exception e) {
-                       logger.error("Failed to POST to {}",url,e);
-                       return null;
-               } 
-       }
-
-       public Pair<Integer, String> get(String url, String username, String password, Map<String, String> headers) {
-               
-               CredentialsProvider credentials = new BasicCredentialsProvider();
-               credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
-               
-               try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
-
-                       HttpGet get = new HttpGet(url);
-                       if (headers != null) {
-                               for (String key : headers.keySet()) {
-                                       get.addHeader(key, headers.get(key));
-                               }
-                       }
-                       
-                       HttpResponse response = client.execute(get);
-                       
-                       String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
-
-                       logger.debug("HTTP GET Response Status Code: {}", response.getStatusLine().getStatusCode());
-                       logger.debug("HTTP GET Response Body:");
-                       logger.debug(returnBody);
-
-                       return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody);
-               } catch (IOException e) {
-                       logger.error("Failed to GET to {}",url,e);
-                       return null;
-               }
-       }
+    private static final Logger logger = LoggerFactory.getLogger(RESTManager.class);
+
+    public class Pair<A, B> {
+        public final A a;
+        public final B b;
+
+        public Pair(A a, B b) {
+            this.a = a;
+            this.b = b;
+        }
+    }
+
+    public Pair<Integer, String> post(String url, String username, String password,
+            Map<String, String> headers, String contentType, String body) {
+        CredentialsProvider credentials = new BasicCredentialsProvider();
+        credentials.setCredentials(AuthScope.ANY,
+                new UsernamePasswordCredentials(username, password));
+
+        logger.debug("HTTP REQUEST: {} -> {} {} -> {}", url, username,
+                ((password != null) ? password.length() : "-"), contentType);
+        if (headers != null) {
+            logger.debug("Headers: ");
+            headers.forEach((name, value) -> logger.debug("{} -> {}", name, value));
+        }
+        logger.debug(body);
+
+        try (CloseableHttpClient client =
+                HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
+
+            HttpPost post = new HttpPost(url);
+            if (headers != null) {
+                for (Entry<String, String> entry : headers.entrySet()) {
+                    post.addHeader(entry.getKey(), headers.get(entry.getKey()));
+                }
+            }
+            post.addHeader("Content-Type", contentType);
+
+            StringEntity input = new StringEntity(body);
+            input.setContentType(contentType);
+            post.setEntity(input);
+
+            HttpResponse response = client.execute(post);
+            if (response != null) {
+                String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
+                logger.debug("HTTP POST Response Status Code: {}",
+                        response.getStatusLine().getStatusCode());
+                logger.debug("HTTP POST Response Body:");
+                logger.debug(returnBody);
+
+                return new Pair<>(response.getStatusLine().getStatusCode(),
+                        returnBody);
+            }
+            else {
+                logger.error("Response from {} is null", url);
+                return null;
+            }
+        }
+        catch (Exception e) {
+            logger.error("Failed to POST to {}", url, e);
+            return null;
+        }
+    }
+
+    public Pair<Integer, String> get(String url, String username, String password,
+            Map<String, String> headers) {
+
+        CredentialsProvider credentials = new BasicCredentialsProvider();
+        credentials.setCredentials(AuthScope.ANY,
+                new UsernamePasswordCredentials(username, password));
+
+        try (CloseableHttpClient client =
+                HttpClientBuilder.create().setDefaultCredentialsProvider(credentials).build()) {
+
+            HttpGet get = new HttpGet(url);
+            if (headers != null) {
+                for (Entry<String, String> entry : headers.entrySet()) {
+                    get.addHeader(entry.getKey(), headers.get(entry.getKey()));
+                }
+            }
+
+            HttpResponse response = client.execute(get);
+
+            String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8");
+
+            logger.debug("HTTP GET Response Status Code: {}",
+                    response.getStatusLine().getStatusCode());
+            logger.debug("HTTP GET Response Body:");
+            logger.debug(returnBody);
+
+            return new Pair<>(response.getStatusLine().getStatusCode(), returnBody);
+        }
+        catch (IOException e) {
+            logger.error("Failed to GET to {}", url, e);
+            return null;
+        }
+    }
 }
diff --git a/controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestGet.java b/controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestGet.java
new file mode 100755 (executable)
index 0000000..96dec30
--- /dev/null
@@ -0,0 +1,52 @@
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * rest\r
+ * ================================================================================\r
+ * \r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.onap.policy.rest;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertTrue;\r
+\r
+import org.junit.Test;\r
+import org.onap.policy.rest.RESTManager.Pair;\r
+\r
+public class TestGet {\r
+\r
+    @Test(expected = NullPointerException.class)\r
+    public void testUrlNull() {\r
+        RESTManager mgr = new RESTManager();\r
+        mgr.get(null, "user", null, null);\r
+    }\r
+\r
+    @Test(expected = IllegalArgumentException.class)\r
+    public void testUsernameNull() {\r
+        RESTManager mgr = new RESTManager();\r
+        mgr.get("nothing", null, null, null);\r
+    }\r
+\r
+    @Test\r
+    public void testUrlExampleOrg() {\r
+        RESTManager mgr = new RESTManager();\r
+\r
+        Pair<Integer, String> result = mgr.get("http://www.example.org", "user", null, null);\r
+        assertEquals((Integer)200, result.a);\r
+        assertTrue(result.b != null);\r
+        assertTrue(result.b.length() > 0);\r
+    }\r
+}
\ No newline at end of file
diff --git a/controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestPair.java b/controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestPair.java
new file mode 100755 (executable)
index 0000000..3ada0a7
--- /dev/null
@@ -0,0 +1,42 @@
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * rest\r
+ * ================================================================================\r
+ * \r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.onap.policy.rest;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import org.junit.Test;\r
+import org.onap.policy.rest.RESTManager.Pair;\r
+\r
+public class TestPair {\r
+\r
+    @Test\r
+    public void testPair() {\r
+        RESTManager mgr = new RESTManager();\r
+\r
+        Pair<Integer, Integer> pii = mgr.new Pair<>(1, 2);\r
+        assertEquals((Integer) 1, (Integer) pii.a);\r
+        assertEquals((Integer) 2, (Integer) pii.b);\r
+\r
+        Pair<Integer, String> pis = mgr.new Pair<>(1, "test");\r
+        assertEquals((Integer) 1, (Integer) pis.a);\r
+        assertEquals("test", pis.b);\r
+    }\r
+}\r
diff --git a/controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestPost.java b/controlloop/common/model-impl/rest/src/test/java/org/onap/policy/rest/TestPost.java
new file mode 100755 (executable)
index 0000000..40f1b30
--- /dev/null
@@ -0,0 +1,42 @@
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * rest\r
+ * ================================================================================\r
+ * \r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ *      http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.onap.policy.rest;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import org.junit.Test;\r
+import org.onap.policy.rest.RESTManager.Pair;\r
+\r
+public class TestPost {\r
+\r
+    @Test(expected = IllegalArgumentException.class)\r
+    public void testUsernameNull() {\r
+        RESTManager mgr = new RESTManager();\r
+        mgr.post("nothing", null, null, null, null, null);\r
+    }\r
+\r
+    @Test\r
+    public void testBodyNull() {\r
+        RESTManager mgr = new RESTManager();\r
+        Pair<Integer, String> result = mgr.post("http://www.example.org", "user", null, null, null, null);\r
+        assertEquals(null, result);\r
+    }\r
+}\r