Improve mod/runtimeapi code coverage 71/100771/1
authorAndrew Gauld <agauld@att.com>
Fri, 24 Jan 2020 19:14:27 +0000 (19:14 +0000)
committerAndrew Gauld <agauld@att.com>
Fri, 24 Jan 2020 19:22:15 +0000 (19:22 +0000)
Change-Id: Ic8b23955deed9411ac2c216571ec2548a9fc5e42
Issue-ID: DCAEGEN2-1860
Signed-off-by: Andrew Gauld <agauld@att.com>
12 files changed:
mod/runtimeapi/pom.xml
mod/runtimeapi/runtime-core/pom.xml
mod/runtimeapi/runtime-core/src/test/java/org/onap/dcae/runtime/core/TestBeans.java [new file with mode: 0644]
mod/runtimeapi/runtime-core/src/test/java/org/onap/dcae/runtime/core/TestFlowGraphParser.java
mod/runtimeapi/runtime-web/pom.xml
mod/runtimeapi/runtime-web/src/main/java/org/onap/dcae/runtime/web/service/BlueprintInventory.java
mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/ClientMocking.java [new file with mode: 0644]
mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestBeans.java [new file with mode: 0644]
mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestIntegration.java [deleted file]
mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestDistributeEndpoint.java [deleted file]
mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestFlowGraphController.java
mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/service/GraphServiceImplTest.java [deleted file]

index 0f79be4..045f28e 100644 (file)
@@ -1,4 +1,21 @@
 <?xml version="1.0" encoding="UTF-8"?>
+<!--
+============LICENSE_START=======================================================
+Copyright (c) 2019-2020 AT&T Intellectual Property. All rights reserved.
+================================================================================
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+============LICENSE_END=========================================================
+-->
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
index fcfe314..dd5d10b 100644 (file)
@@ -1,4 +1,21 @@
 <?xml version="1.0" encoding="UTF-8"?>
+<!--
+============LICENSE_START=======================================================
+Copyright (c) 2019-2020 AT&T Intellectual Property. All rights reserved.
+================================================================================
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+============LICENSE_END=========================================================
+-->
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
             <artifactId>blueprint-generator</artifactId>
             <version>1.0.0</version> 
         </dependency>
+       <dependency>
+               <groupId>org.json</groupId>
+               <artifactId>json</artifactId>
+               <version>20190722</version>
+       </dependency>
         <dependency>
             <groupId>org.yaml</groupId>
             <artifactId>snakeyaml</artifactId>
-            <version>1.21</version>
+            <version>1.23</version>
         </dependency>
     </dependencies>
 </project>
diff --git a/mod/runtimeapi/runtime-core/src/test/java/org/onap/dcae/runtime/core/TestBeans.java b/mod/runtimeapi/runtime-core/src/test/java/org/onap/dcae/runtime/core/TestBeans.java
new file mode 100644 (file)
index 0000000..1d2e8fb
--- /dev/null
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dcae.runtime.core;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class TestBeans {
+    @Test
+    public void testBeans() {
+       BlueprintData bpd = new BlueprintData("version", "content");
+       bpd.setVersion(bpd.getVersion());
+       bpd.setBlueprint_content(bpd.getBlueprint_content());
+       Edge edg = new Edge(null, null, null);
+       edg.setSrc(edg.getSrc());
+       edg.setTgt(edg.getTgt());
+       edg.setMetadata(edg.getMetadata());
+       EdgeLocation el = new EdgeLocation("node", "port");
+       el.setNode(el.getNode());
+       el.setPort(el.getPort());
+       EdgeMetadata em = new EdgeMetadata("name", "data_type", "dmaap_type");
+       em.setName(em.getName());
+       em.setDataType(em.getDataType());
+       em.setDmaapType(em.getDmaapType());
+       Node nod = new Node("componentId", "componentName", "componentSpec");
+       nod.setComponentId(nod.getComponentId());
+       nod.setComponentName(nod.getComponentName());
+       nod.setComponentSpec(nod.getComponentSpec());
+       nod.setBlueprintData(nod.getBlueprintData());
+       assertTrue(nod.equals(nod));
+       assertEquals(nod.toString(), "componentId");
+    }
+}
index bacfcb1..8412133 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  */
 package org.onap.dcae.runtime.core;
 
-import org.junit.Before;
-import org.junit.Ignore;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Map;
+import org.junit.Rule;
+import org.junit.rules.TemporaryFolder;
 import org.junit.Test;
+import static org.junit.Assert.assertEquals;
 import org.onap.dcae.runtime.core.blueprint_creator.BlueprintCreatorOnapDublin;
 
 public class TestFlowGraphParser {
 
-    private FlowGraph<Node, Edge> flowGraph;
-    private FlowGraphParser flowGraphParser;
-
-    @Before
-    public void setUp() throws Exception{
-        flowGraph = Helper.prepareFlowGraph();
-        flowGraphParser = new FlowGraphParser(new BlueprintCreatorOnapDublin());
-        flowGraphParser.parse(flowGraph);
-    }
+    @Rule
+    public TemporaryFolder folder = new TemporaryFolder();
 
     @Test
-    @Ignore
-    public void testBlueprintsCreate() throws Exception{
-        /*
-        TODO: FIX
-        Map<String,String> expectedBlueprints = Helper.loadTestBlueprints();
-        Map<String,String> resultBlueprints = flowGraphParser.createAndProcessBlueprints();
-
-        assertEquals(expectedBlueprints,resultBlueprints);
-        */
+    public void testFlowGraphParser() throws IOException {
+        try {
+        File importsfile = folder.newFile("imports.yaml");
+        try (Writer w = new FileWriter(importsfile)) {
+            w.write(
+                "imports:\n" +
+               " - 'http://www.getcloudify.org/spec/cloudify/3.4/types.yaml'\n" +
+               " - 'https://nexus.onap.org/service/local/repositories/raw/content/org.onap.dcaegen2.platform.plugins/R4/k8splugin/1.4.5/k8splugin_types.yaml'\n" +
+                " - 'https://nexus.onap.org/service/local/repositories/raw/content/org.onap.dcaegen2.platform.plugins/R4/dcaepolicyplugin/2.3.0/dcaepolicyplugin_types.yaml'\n"
+           );
+        }
+        FlowGraph<Node, Edge> mainFlowGraph = new FlowGraph<>("1234", "nifi-main", true, "mock graph");
+        mainFlowGraph.addNode(new Node("dummy_id", "dummy_name", "dummy_compspec"));
+        BlueprintCreatorOnapDublin bcod = new BlueprintCreatorOnapDublin();
+        bcod.setTopicUrl("u.r.l");
+        bcod.setImportFilePath(importsfile.getAbsolutePath());
+        FlowGraphParser flowGraphParser = new FlowGraphParser(bcod);
+        flowGraphParser.parse(mainFlowGraph);
+        String compspec = Helper.loadFileContent("src/test/data/compspecs/componentSpec_hello_world.json");
+        mainFlowGraph.addNode(new Node("comp5678", "hello-world-2", compspec));
+        mainFlowGraph.addNode(new Node("comp1234", "hello-world-1", compspec));
+        mainFlowGraph.addEdge(
+          flowGraphParser.getNodeFromId("comp1234"),
+          flowGraphParser.getNodeFromId("comp5678"), 
+          new Edge(
+            new EdgeLocation("comp1234", "DCAE-HELLO-WORLD-PUB-MR"),
+            new EdgeLocation("comp5678", "DCAE-HELLO-WORLD-SUB-MR"),
+            new EdgeMetadata("sample_topic_1", "json", "MR")));
+        flowGraphParser.createAndProcessBlueprints();
+        } catch (RuntimeException rte) {
+            rte.printStackTrace();
+            throw rte;
+        } catch (Exception e) {
+            e.printStackTrace();
+            throw new RuntimeException(e);
+       }
     }
-
 }
index 3b39845..413ff9f 100644 (file)
@@ -1,4 +1,21 @@
 <?xml version="1.0" encoding="UTF-8"?>
+<!--
+============LICENSE_START=======================================================
+Copyright (c) 2019-2020 AT&T Intellectual Property. All rights reserved.
+================================================================================
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+============LICENSE_END=========================================================
+-->
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
                        <artifactId>json</artifactId>
                        <version>20190722</version>
                </dependency>
+               <dependency>
+                       <groupId>org.apache.httpcomponents</groupId>
+                       <artifactId>httpclient</artifactId>
+                       <version>4.5.8</version>
+                       <scope>test</scope>
+               </dependency>
        </dependencies>
 
        <build>
index bb6839c..789c9d1 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -39,6 +39,8 @@ public class BlueprintInventory {
 
     Logger logger = LoggerFactory.getLogger(BlueprintInventory.class);
 
+    private RestTemplate restTemplate = new RestTemplate();
+
     public void distributeToInventory(List<BlueprintVessel> blueprints) {
         for (BlueprintVessel bpv : blueprints) {
             JSONObject body = prepareBlueprintJsonObject(bpv.name, bpv.version, bpv.blueprint);
@@ -51,7 +53,6 @@ public class BlueprintInventory {
     // Should work with inventory too!
     private boolean postToDashboard(JSONObject blueprintJsonObject){
         //1. setup
-        RestTemplate restTemplate = new RestTemplate();
         HttpHeaders headers = new HttpHeaders();
         headers.setContentType(MediaType.APPLICATION_JSON);
         // NOTE: This commented out line is to be used for dcae dashboard api and not inventory
diff --git a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/ClientMocking.java b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/ClientMocking.java
new file mode 100644 (file)
index 0000000..14acf90
--- /dev/null
@@ -0,0 +1,346 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dcae.runtime.web;
+
+import java.io.IOException;
+import java.lang.invoke.MethodHandles;
+import java.util.Base64;
+import java.util.function.Consumer;
+import java.util.function.Predicate;
+import java.util.ArrayList;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.entity.ByteArrayEntity;
+import org.apache.http.entity.ContentType;
+import org.apache.http.HttpResponse;
+import org.apache.http.message.BasicHttpResponse;
+import org.apache.http.message.BasicStatusLine;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.ProtocolVersion;
+import org.apache.http.StatusLine;
+
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * Simulate responses from RestTemplate based clients.
+ */
+
+public class ClientMocking implements Answer<HttpResponse> {
+       private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+       /**
+        * Replace single quotes with double quotes.
+        * Makes it easy to write JSON strings.
+        *
+        * @param s String with single quotes.
+        * @return String replacing single quotes with double quotes.
+        */
+       public static String xq(String s) {
+               return s.replaceAll("'", "\"");
+       }
+
+       private static class BasicCloseableHttpResponse extends BasicHttpResponse implements CloseableHttpResponse {
+               public BasicCloseableHttpResponse(StatusLine line) {
+                       super(line);
+               }
+
+               @Override
+               public void close() throws IOException {
+                       // no op
+               }
+       }
+
+       /**
+        * Information on request being processed
+        */
+       public static class RequestInfo {
+               private HttpUriRequest req;
+               private String line;
+
+               /**
+                * Collect information on a request.
+                * @param req The request to examine.
+                */
+               public RequestInfo(HttpUriRequest req) {
+                       this.req = req;
+                       line = getMethod() + " " + getPath() + (req.getURI().getQuery() == null ? "": ("?" + req.getURI().getQuery()));
+               }
+
+               /**
+                * Get the method.
+                *
+                * @return The HTTP method of the request.
+                */
+               public String getMethod() {
+                       return req.getMethod();
+               }
+
+               /**
+                * Get the method and URI
+                *
+                * @return The method and URI of the request, including any query string.
+                */
+               public String getLine() {
+                       return line;
+               }
+
+               /**
+                * Get the path component of the URI
+                *
+                * @return The URI excluding the query string.
+                */
+               public String getPath() {
+                       return req.getURI().getPath();
+               }
+
+               /**
+                * Check whether the named header is missing.
+                *
+                * @return true if the header is absent.
+                */
+               public boolean lacksHeader(String name) {
+                       return req.getFirstHeader(name) == null;
+               }
+
+               /**
+                * Check whether the header has the specified header value.
+                *
+                * @return true if the header is missing or has the wrong value.
+                */
+               public boolean lacksHeaderValue(String name, String value) {
+                       return req.getFirstHeader(name) == null || !value.equals(req.getFirstHeader(name).getValue());
+               }
+       }
+
+       private static class Response {
+               private Predicate<RequestInfo> matcher;
+               private byte[] body;
+               private Consumer<RequestInfo> action;
+               private int code = 200;
+               private String message = "OK";
+               private ContentType contentType = ContentType.APPLICATION_JSON;
+       }
+
+       private static Predicate<RequestInfo> s2p(String line) {
+               return r -> r.getLine().equals(line);
+       }
+
+       private ArrayList<Response> responses;
+       private HttpClient client;
+
+       /**
+        * Create a responder to handle requests.
+        */
+       public ClientMocking() throws IOException {
+               responses = new ArrayList<>();
+               client = mock(HttpClient.class);
+               when(client.execute(any(HttpUriRequest.class), any(HttpContext.class))).thenAnswer(this);
+       }
+
+       /**
+        * Redirect the template to this responder.
+        *
+        * @param template The RestTemplate to redirect.
+        * @return This responder.
+        */
+       public ClientMocking applyTo(RestTemplate template) {
+               template.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client));
+               return this;
+       }
+
+       /**
+        * Set the identified RestTemplate field to use this responder.
+        *
+        * @param object The object containing the RestTemplate.
+        * @param fieldName The name of the RestTemplate field in the object.
+        * @return This responder.
+        */
+       public ClientMocking applyTo(Object object, String fieldName) {
+               return applyTo((RestTemplate)ReflectionTestUtils.getField(object, fieldName));
+       }
+
+       /**
+        * Set the restTemplate field of an object to use this responder.
+        *
+        * Typically, the object will be a FederationClient or a GatewayClient.
+        * @param object The object with the restTemplate field.
+        * @return This responder.
+        */
+       public ClientMocking applyTo(Object object) {
+               return applyTo(object, "restTemplate");
+       }
+
+       @Override
+       public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
+               RequestInfo info = new RequestInfo((HttpUriRequest)invocation.getArguments()[0]);
+               for (Response r: responses) {
+                       if (r.matcher.test(info)) {
+                               if (r.action != null) {
+                                       r.action.accept(info);
+                               }
+                               BasicCloseableHttpResponse ret = new BasicCloseableHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), r.code, r.message));
+                               if (r.body != null) {
+                                       ret.setEntity(new ByteArrayEntity(r.body, r.contentType));
+                                       ret.addHeader("Content-Length", String.valueOf(r.body.length));
+                                       if (r.body.length != 0) {
+                                               ret.addHeader("Content-Type", r.contentType.toString());
+                                       }
+                               }
+                               if (log.isInfoEnabled()) {
+                                       log.info("Mock client response to {} is {}", info.getLine(), (r.body == null? "null": new String(r.body)));
+                               }
+                               return ret;
+                       }
+               }
+               throw new IOException("Mock unhandled " + info.getLine());
+       }
+
+       /**
+        * Handle the specified requests.
+        *
+        * @param matcher A predicate for matching requests.
+        * @param body The response body to return.
+        * @param type The content type of the body.
+        * @param action An action to perform, whenever the request is handled.
+        * @return This responder.
+        */
+       public ClientMocking on(Predicate<RequestInfo> matcher, byte[] body, ContentType type, Consumer<RequestInfo> action) {
+               Response r = new Response();
+               r.matcher = matcher;
+               r.body = body;
+               r.contentType = type;
+               r.action = action;
+               responses.add(r);
+               return this;
+       }
+
+       /**
+        * Handle the specified request.
+        *
+        * @param line The HTTP method and URI to handle.
+        * @param body The response body to return.
+        * @param type The content type of the body.
+        * @param action An action to perform, whenever the request is handled.
+        * @return This responder.
+        */
+       public ClientMocking on(String line, String body, ContentType type, Consumer<RequestInfo> action) {
+               return on(s2p(line), body.getBytes(), type, action);
+       }
+
+       /**
+        * Handle the specified request.
+        *
+        * @param line The HTTP method and URI to handle.
+        * @param body The response body to return, as a JSON string.
+        * @param action An action to perform, whenever the request is handled.
+        * @return This responder.
+        */
+       public ClientMocking on(String line, String body, Consumer<RequestInfo> action) {
+               return on(line, body, ContentType.APPLICATION_JSON, action);
+       }
+
+       /**
+        * Handle the specified request.
+        *
+        * @param line The HTTP method and URI to handle.
+        * @param body The response body to return, as a JSON string.
+        * @return This responder.
+        */
+       public ClientMocking on(String line, String body) {
+               return on(line, body, ContentType.APPLICATION_JSON);
+       }
+
+       /**
+        * Handle the specified request.
+        *
+        * @param line The HTTP method and URI to handle.
+        * @param body The response body to return, as a JSON string.
+        * @param type The content type of the body.
+        * @return This responder.
+        */
+       public ClientMocking on(String line, String body, ContentType type) {
+               return on(line, body, type, null);
+       }
+
+       /**
+        * Fail the specified requests.
+        *
+        * @param matcher A predicate for matching requests.
+        * @param code The HTTP error code to return.
+        * @param message The HTTP error status message to return.
+        * @return This responder.
+        */
+       public ClientMocking errorOn(Predicate<RequestInfo> matcher, int code, String message) {
+               Response r = new Response();
+               r.matcher = matcher;
+               r.code = code;
+               r.message = message;
+               responses.add(r);
+               return this;
+       }
+
+       /**
+        * Fail the specified request.
+        *
+        * @param line The HTTP method and URI to handle.
+        * @param code The HTTP error code to return.
+        * @param message The HTTP error status message to return.
+        * @return This responder.
+        */
+       public ClientMocking errorOn(String line, int code, String message) {
+               return errorOn(s2p(line), code, message);
+       }
+
+       /**
+        * Fail the request if no auth header
+        *
+        * @param code The HTTP error code to return.
+        * @param message The HTTP error status message to return.
+        * @return This responder.
+        */
+       public ClientMocking errorOnNoAuth(int code, String message) {
+               return errorOn(ri -> ri.lacksHeader("Authorization"), code, message);
+       }
+
+       /**
+        * Fail the request if wrong auth header
+        *
+        * @param username The expected user name.
+        * @param password The expected password.
+        * @param code The HTTP error code to return.
+        * @param message The HTTP error status message to return.
+        * @return This responder.
+        */
+       public ClientMocking errorOnBadAuth(String username, String password, int code, String message) {
+               String authhdr = "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
+               return errorOn(ri -> ri.lacksHeaderValue("Authorization", authhdr), code, message);
+       }
+}
diff --git a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestBeans.java b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestBeans.java
new file mode 100644 (file)
index 0000000..9751486
--- /dev/null
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dcae.runtime.web;
+
+import org.junit.Test;
+
+import org.onap.dcae.runtime.web.exception.ActionsNotDefinedException;
+import org.onap.dcae.runtime.web.exception.MainGraphAlreadyExistException;
+import org.onap.dcae.runtime.web.exception.MainGraphNotFoundException;
+import org.onap.dcae.runtime.web.models.Action;
+import org.onap.dcae.runtime.web.models.DashboardConfig;
+import org.onap.dcae.runtime.web.models.DistributeGraphRequest;
+
+public class TestBeans {
+    @Test
+    public void testBeans() {
+       Action act = new Action();
+       act.setCommand(act.getCommand());
+       act.setTarget_graph_id(act.getTarget_graph_id());
+       act.setPayload(act.getPayload());
+        DashboardConfig dc = new DashboardConfig();
+       dc.setUrl(dc.getUrl());
+       dc.setUsername(dc.getUsername());
+       dc.setPassword(dc.getPassword());
+       DistributeGraphRequest dgr = new DistributeGraphRequest();
+       dgr.setActions(dgr.getActions());
+       new ActionsNotDefinedException("some message");
+       new MainGraphNotFoundException();
+       new MainGraphAlreadyExistException("some message");
+    }
+}
diff --git a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestIntegration.java b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestIntegration.java
deleted file mode 100644 (file)
index 60e192c..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcae.runtime.web;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.*;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = RANDOM_PORT)
-public class TestIntegration {
-
-    @Autowired
-    private TestRestTemplate restTemplate;
-
-    @Test
-    public void testInitializeGraph() throws Exception{
-
-    }
-}
diff --git a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestDistributeEndpoint.java b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestDistributeEndpoint.java
deleted file mode 100644 (file)
index ad41b37..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcae.runtime.web.controllers;
-
-import org.onap.dcae.runtime.web.Helper;
-import org.onap.dcae.runtime.web.models.DistributeGraphRequest;
-import org.onap.dcae.runtime.web.models.GraphRequest;
-import org.onap.dcae.runtime.web.service.GraphServiceImpl;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.web.client.TestRestTemplate;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.test.context.junit4.SpringRunner;
-
-import java.util.Map;
-
-import static junit.framework.TestCase.assertTrue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
-
-// TODO: Unit test is failiing so ignoring for now since not familiar with unit testing in Spring.
-@Ignore
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = RANDOM_PORT)
-public class TestDistributeEndpoint {
-
-    @Autowired
-    private TestRestTemplate restTemplate;
-
-    @Autowired
-    private GraphServiceImpl graphService;
-
-    private DistributeGraphRequest distributeGraphRequest;
-
-    @Before
-    public void setUp() throws Exception{
-        //initialze the Main Graph
-        GraphRequest graphRequest = new GraphRequest();
-        graphRequest.setId("1234");
-        graphRequest.setName("nifi-main");
-        graphRequest.setDescription("mock graph");
-        graphService.initializeMainGraph(graphRequest);
-        distributeGraphRequest = new DistributeGraphRequest();
-
-    }
-
-    @Test
-    @Ignore
-    public void testAddNodesGeneratesBlueprints() throws Exception{
-
-        distributeGraphRequest.setActions(Helper.getAddNodeActionsForRequest());
-        Map<String,String> expectedResult = Helper.prepareExpectedResult();
-
-        ResponseEntity<Map> response = restTemplate.postForEntity("/api/graph/1234/distribute",distributeGraphRequest,Map.class);
-        assertEquals(HttpStatus.OK,response.getStatusCode());
-        assertTrue(expectedResult.equals(response.getBody()));
-
-//        mockMvc.perform(post("/api/graph/1234/distribute")
-//        .contentType(MediaType.APPLICATION_JSON)
-//        .content(TestUtils.convertObjectToJsonBytes(distributeGraphRequest)))
-//        .andExpect(status().isOk());
-
-//        assertEquals(Helper.loadFileContent("src/test/data/blueprints_samples/helloworld_test_2.yaml"),
-//                Helper.loadFileContent("src/test/data/blueprints_from_tests/HelloWorld_blueprint.yaml"));
-//        fail("Needs to complete the test");
-    }
-
-    @Test
-    public void testAddNodesAndEdgeGeneratesCorrectBlueprints() throws Exception{
-        distributeGraphRequest.setActions(Helper.getAddNodesWithEdge());
-        Map<String,String> expectedResult = Helper.prepareExpectedResultForAddEdge();
-
-        ResponseEntity<Map> response = restTemplate.postForEntity("/api/graph/1234/distribute",distributeGraphRequest,Map.class);
-
-        assertEquals(HttpStatus.OK,response.getStatusCode());
-        assertTrue(expectedResult.equals(response.getBody()));
-
-    }
-}
index e17e1c6..dbbfd8d 100644 (file)
@@ -1,6 +1,6 @@
 /*-
  * ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  */
 package org.onap.dcae.runtime.web.controllers;
 
+import java.util.HashMap;
+import java.util.LinkedList;
+
 import org.onap.dcae.runtime.core.Edge;
 import org.onap.dcae.runtime.core.FlowGraph;
 import org.onap.dcae.runtime.core.Node;
+import org.onap.dcae.runtime.web.ClientMocking;
+import org.onap.dcae.runtime.web.Helper;
 import org.onap.dcae.runtime.web.TestUtils;
+import org.onap.dcae.runtime.web.models.Action;
+import org.onap.dcae.runtime.web.models.DistributeGraphRequest;
 import org.onap.dcae.runtime.web.models.GraphRequest;
 import org.onap.dcae.runtime.web.service.GraphServiceImpl;
+import org.onap.dcae.runtime.web.service.BlueprintInventory;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.boot.test.mock.mockito.MockBean;
 import org.springframework.http.MediaType;
 import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.test.web.servlet.MockMvc;
 
 import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
 @RunWith(SpringRunner.class)
-@WebMvcTest
+@SpringBootTest
+@AutoConfigureMockMvc
 public class TestFlowGraphController {
 
     @Autowired
     private MockMvc mockMvc;
 
-    @MockBean
+    @Autowired
+    private BlueprintInventory blueprintInventory;
+
+    @Autowired
     private GraphServiceImpl graphService;
 
+    private DistributeGraphRequest distributeGraphRequest;
     private GraphRequest graphRequest;
 
     @Before
@@ -57,41 +72,37 @@ public class TestFlowGraphController {
         graphRequest.setId("1234");
         graphRequest.setName("nifi-main");
         graphRequest.setDescription("mock graph");
+       distributeGraphRequest = new DistributeGraphRequest();
+       ClientMocking inv = new ClientMocking()
+               .on("POST /ccsdk-app/api-if", "\"OK\"")
+               .applyTo(blueprintInventory);
     }
 
     @Test
     public void testInitializeGraph() throws Exception{
         graphRequest.setMain(true);
+        mockMvc.perform(get("/api/graph/main"))
+                .andExpect(status().isNotFound());
         mockMvc.perform(post("/api/graph/main")
                         .contentType(MediaType.APPLICATION_JSON)
                         .content(TestUtils.convertObjectToJsonBytes(graphRequest)))
                         .andExpect(status().isCreated());
-    }
-
-    @Test
-    public void testGetMainGraph() throws Exception{
-        FlowGraph<Node, Edge> flowGraph = new FlowGraph<>("1234","nifi-main",true,"demo");
-        when(this.graphService.getMainGraph()).thenReturn(flowGraph);
+        mockMvc.perform(post("/api/graph/main")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content(TestUtils.convertObjectToJsonBytes(graphRequest)))
+                        .andExpect(status().isConflict());
         mockMvc.perform(get("/api/graph/main"))
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("id").value("1234"))
                 .andExpect(jsonPath("name").value("nifi-main"));
+       distributeGraphRequest.setActions(Helper.getAddNodesWithEdge());
+       mockMvc.perform(post("/api/graph/" + graphRequest.getId() + "/distribute")
+                       .contentType(MediaType.APPLICATION_JSON)
+                       .content(TestUtils.convertObjectToJsonBytes(distributeGraphRequest)))
+                       .andExpect(status().isOk());
+       mockMvc.perform(delete("/api/graph/main"))
+                       .andExpect(status().isOk());
+       mockMvc.perform(delete("/api/graph/main"))
+                       .andExpect(status().isNotFound());
     }
-
-//    @Test
-//    public void testMainGraphNotFound() throws Exception{
-//        when(this.graphService.getMainGraph()).thenReturn(null);
-//        mockMvc.perform(get("/api/graph/main"))
-//                .andExpect(status().isNotFound());
-//    }
-
-//    @Test
-//    public void testConflictIfMainGraphExists() throws Exception{
-//        when(this.graphService.initializeMainGraph(graphRequest)).thenThrow(new MainGraphAlreadyExistException(""));
-//        mockMvc.perform(post("/api/graph/main")
-//                .contentType(MediaType.APPLICATION_JSON)
-//                .content(TestUtils.convertObjectToJsonBytes(graphRequest)))
-//                .andExpect(status().isConflict());
-//    }
-
 }
diff --git a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/service/GraphServiceImplTest.java b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/service/GraphServiceImplTest.java
deleted file mode 100644 (file)
index 8f6c945..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcae.runtime.web.service;
-
-import org.onap.dcae.runtime.core.Node;
-import org.onap.dcae.runtime.web.Helper;
-import org.onap.dcae.runtime.web.exception.MainGraphAlreadyExistException;
-import org.onap.dcae.runtime.web.exception.MainGraphNotFoundException;
-import org.onap.dcae.runtime.web.models.GraphRequest;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.Ignore;
-
-import java.util.*;
-
-import static org.junit.Assert.*;
-
-// TODO: Running into null pointer issue. GraphServiceImpl depends upon FlowGraphParser but that is null.  FlowGraphParser
-// relies on BlueprintCreator which means blueprint generator.  This needs to be mocked I believe.  Or the fix maybe
-// with getting Spring to work right (ugh).  Ignore for now.
-@Ignore
-public class GraphServiceImplTest {
-
-    private GraphService graphService;
-    private GraphRequest graphRequest;
-
-    @Before
-    public void setUp() throws Exception{
-        graphService = new GraphServiceImpl();
-        graphRequest = new GraphRequest();
-        graphRequest.setId("1234");
-        graphRequest.setName("nifi-main");
-        graphRequest.setDescription("mock graph");
-    }
-
-    @Test
-    public void testInitializeMainFlowGraph() throws Exception{
-        graphService.initializeMainGraph(graphRequest);
-        assertEquals(graphService.getMainGraph().getName(),"nifi-main");
-        assertTrue(graphService.getMainGraph().isMain());
-    }
-
-    @Test
-    public void testThrowConflictIfMainGraphAlreadyExist() throws Exception{
-        graphService.initializeMainGraph(graphRequest);
-        try {
-            graphService.initializeMainGraph(graphRequest);
-            fail("Exception has to be thrown since Main Graph already exists");
-        }catch(MainGraphAlreadyExistException ex){
-            assertEquals("Can not initialize the main graph, it already exists",ex.getMessage());
-        }
-    }
-
-    @Test
-    public void testMainGraphNotFound() throws Exception{
-        try{
-            graphService.getMainGraph();
-            fail("Error should be thrown if the main graph is not initialized");
-        }catch (MainGraphNotFoundException ex){
-        }
-    }
-
-    @Test
-    public void testAddNodesWithEdgeGeneratesBlueprints() throws Exception{
-        /*
-        TODO: FIX
-        //arrange
-        graphService.initializeMainGraph(graphRequest);
-        DistributeGraphRequest distributeGraphRequest = new DistributeGraphRequest();
-        distributeGraphRequest.setActions(Helper.getAddNodesWithEdge());
-        Set<Node> nodes = prepareTestNodes();
-
-        //act
-        Map<String,String> result = graphService.distribute(distributeGraphRequest);
-
-        //assert
-        assertEquals(nodes.size(),graphService.getMainGraph().getNodes().size());
-        //assertArrayEquals(nodes.toArray(),graphService.getMainGraph().getNodes().toArray());
-        assertEquals(Helper.prepareExpectedResult(),result);
-        */
-    }
-
-    private Set<Node> prepareTestNodes() {
-        Set<Node> nodes = new HashSet<Node>();
-        nodes.add(new Node("comp123","HelloWorld",
-                Helper.loadFileContent("src/test/data/compspecs/componentSpec_hello_world.json")));
-        nodes.add(new Node("comp456","Toolbox",
-                Helper.loadFileContent("src/test/data/compspecs/componentSpec_New_Toolbox.json")));
-        return nodes;
-    }
-
-}