diff options
Diffstat (limited to 'mod/runtimeapi/runtime-web')
8 files changed, 457 insertions, 277 deletions
diff --git a/mod/runtimeapi/runtime-web/pom.xml b/mod/runtimeapi/runtime-web/pom.xml index 3b39845..413ff9f 100644 --- a/mod/runtimeapi/runtime-web/pom.xml +++ b/mod/runtimeapi/runtime-web/pom.xml @@ -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> @@ -59,6 +76,12 @@ <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> diff --git a/mod/runtimeapi/runtime-web/src/main/java/org/onap/dcae/runtime/web/service/BlueprintInventory.java b/mod/runtimeapi/runtime-web/src/main/java/org/onap/dcae/runtime/web/service/BlueprintInventory.java index bb6839c..789c9d1 100644 --- a/mod/runtimeapi/runtime-web/src/main/java/org/onap/dcae/runtime/web/service/BlueprintInventory.java +++ b/mod/runtimeapi/runtime-web/src/main/java/org/onap/dcae/runtime/web/service/BlueprintInventory.java @@ -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 index 0000000..14acf90 --- /dev/null +++ b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/ClientMocking.java @@ -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 index 0000000..9751486 --- /dev/null +++ b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestBeans.java @@ -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 index 60e192c..0000000 --- a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/TestIntegration.java +++ /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 index ad41b37..0000000 --- a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestDistributeEndpoint.java +++ /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())); - - } -} diff --git a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestFlowGraphController.java b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestFlowGraphController.java index e17e1c6..dbbfd8d 100644 --- a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestFlowGraphController.java +++ b/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/controllers/TestFlowGraphController.java @@ -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. @@ -17,38 +17,53 @@ */ 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 index 8f6c945..0000000 --- a/mod/runtimeapi/runtime-web/src/test/java/org/onap/dcae/runtime/web/service/GraphServiceImplTest.java +++ /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; - } - -} |