4f9631250d0c2ee9f7bd1648e4bedbb4ed23c81c
[sdc.git] / openecomp-be / lib / openecomp-sdc-externaltesting-lib / openecomp-sdc-externaltesting-impl / src / test / java / org / openecomp / core / externaltesting / impl / ExternalTestingManagerImplTest.java
1 /*
2  * Copyright © 2019 iconectiv
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.core.externaltesting.impl;
18
19 import com.fasterxml.jackson.core.type.TypeReference;
20 import com.fasterxml.jackson.databind.ObjectMapper;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.IOException;
24 import java.nio.charset.Charset;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Optional;
30 import java.util.UUID;
31 import org.apache.commons.io.FileUtils;
32 import org.apache.commons.io.IOUtils;
33 import org.apache.commons.lang3.tuple.Pair;
34 import org.junit.Assert;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.junit.runner.RunWith;
38 import org.mockito.ArgumentMatchers;
39 import org.mockito.InjectMocks;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.MockitoAnnotations;
43 import org.mockito.junit.MockitoJUnitRunner;
44 import org.openecomp.core.externaltesting.api.ClientConfiguration;
45 import org.openecomp.core.externaltesting.api.ExternalTestingManager;
46 import org.openecomp.core.externaltesting.api.RemoteTestingEndpointDefinition;
47 import org.openecomp.core.externaltesting.api.TestTreeNode;
48 import org.openecomp.core.externaltesting.api.VtpNameDescriptionPair;
49 import org.openecomp.core.externaltesting.api.VtpTestCase;
50 import org.openecomp.core.externaltesting.api.VtpTestExecutionRequest;
51 import org.openecomp.core.externaltesting.api.VtpTestExecutionResponse;
52 import org.openecomp.core.externaltesting.errors.ExternalTestingException;
53 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
54 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
55 import org.openecomp.sdc.versioning.VersioningManager;
56 import org.openecomp.sdc.versioning.dao.types.Version;
57 import org.springframework.core.ParameterizedTypeReference;
58 import org.springframework.http.HttpHeaders;
59 import org.springframework.http.HttpMethod;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.http.MediaType;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.util.LinkedMultiValueMap;
64 import org.springframework.web.client.HttpServerErrorException;
65 import org.springframework.web.client.HttpStatusCodeException;
66 import org.springframework.web.client.ResourceAccessException;
67 import org.springframework.web.client.RestTemplate;
68
69 @RunWith(MockitoJUnitRunner.class)
70 public class ExternalTestingManagerImplTest {
71
72   @Mock
73   private RestTemplate restTemplate;
74
75   @Mock
76   private VersioningManager versioningManager;
77
78   @Mock
79   private VendorSoftwareProductManager vendorSoftwareProductManager;
80
81   @Mock
82   private OrchestrationTemplateCandidateManager candidateManager;
83
84   @InjectMocks
85   private ExternalTestingManagerImpl mgr = new ExternalTestingManagerImpl();
86
87   @SuppressWarnings("unchecked")
88   private ExternalTestingManagerImpl configTestManager(boolean loadConfig) throws IOException {
89
90     MockitoAnnotations.initMocks(this);
91
92     if (loadConfig) {
93       mgr.init();
94     }
95
96     ObjectMapper mapper = new ObjectMapper();
97
98     // read mock data for API calls.
99
100     File scenarioFile = new File("src/test/data/scenarios.json");
101     TypeReference<List<VtpNameDescriptionPair>> typ = new TypeReference<List<VtpNameDescriptionPair>>(){};
102     List<VtpNameDescriptionPair> scenarios = mapper.readValue(scenarioFile, typ);
103
104     File testSuitesFile = new File("src/test/data/testsuites.json");
105     List<VtpNameDescriptionPair> testSuites = mapper.readValue(testSuitesFile, new TypeReference<List<VtpNameDescriptionPair>>(){});
106
107     File testCasesFile = new File("src/test/data/testcases.json");
108     List<VtpTestCase> testCases = mapper.readValue(testCasesFile, new TypeReference<List<VtpTestCase>>(){});
109
110     File testCaseFile = new File("src/test/data/testcase-sriov.json");
111     VtpTestCase testCase = mapper.readValue(testCaseFile, VtpTestCase.class);
112
113     File runResultFile = new File("src/test/data/runresult.json");
114     List<VtpTestExecutionResponse> runResults = mapper.readValue(runResultFile, new TypeReference<List<VtpTestExecutionResponse>>(){});
115
116     File priorExecutionFile = new File("src/test/data/priorexecution.json");
117     VtpTestExecutionResponse priorExecution = mapper.readValue(priorExecutionFile, VtpTestExecutionResponse.class);
118
119     // create an error response as well
120     String notFound = FileUtils.readFileToString(new File("src/test/data/notfound.json"), "UTF-8");
121
122     ParameterizedTypeReference<List<VtpNameDescriptionPair>> listOfPairType = new ParameterizedTypeReference<List<VtpNameDescriptionPair>>() {};
123     ParameterizedTypeReference<List<VtpTestCase>> listOfCasesType = new ParameterizedTypeReference<List<VtpTestCase>>() {};
124     ParameterizedTypeReference<VtpTestCase> caseType = new ParameterizedTypeReference<VtpTestCase>() {};
125
126     HttpHeaders headers = new HttpHeaders();
127     headers.setContentType(MediaType.parseMediaType("application/problem+json"));
128
129     byte[] csar = IOUtils.toByteArray(new FileInputStream("src/test/data/csar.zip"));
130     byte[] heat = IOUtils.toByteArray(new FileInputStream("src/test/data/heat.zip"));
131
132     List<Version> versionList = new ArrayList<>();
133     versionList.add(new Version(UUID.randomUUID().toString()));
134
135     Mockito
136         .when(candidateManager.get(
137             ArgumentMatchers.contains("csar"),
138             ArgumentMatchers.any()))
139         .thenReturn(Optional.of(Pair.of("Processed.zip", csar)));
140
141     Mockito
142         .when(candidateManager.get(
143             ArgumentMatchers.contains("heat"),
144             ArgumentMatchers.any()))
145         .thenReturn(Optional.empty());
146
147     Mockito
148         .when(vendorSoftwareProductManager.get(
149             ArgumentMatchers.contains("heat"),
150             ArgumentMatchers.any()))
151         .thenReturn(Optional.of(Pair.of("Processed.zip", heat)));
152
153
154
155     Mockito
156         .when(vendorSoftwareProductManager.get(
157             ArgumentMatchers.contains("missing"),
158             ArgumentMatchers.any()))
159         .thenReturn(Optional.empty());
160
161     Mockito
162         .when(candidateManager.get(
163             ArgumentMatchers.contains("missing"),
164             ArgumentMatchers.any()))
165         .thenReturn(Optional.empty());
166
167
168     Mockito
169         .when(versioningManager.list(
170             ArgumentMatchers.contains("missing")))
171         .thenReturn(versionList);
172
173
174
175
176
177
178     Mockito
179         .when(restTemplate.exchange(
180             ArgumentMatchers.endsWith("/scenarios"),
181             ArgumentMatchers.eq(HttpMethod.GET),
182             ArgumentMatchers.any(),
183             ArgumentMatchers.eq(listOfPairType)))
184         .thenReturn(new ResponseEntity(scenarios, HttpStatus.OK));
185
186     Mockito
187         .when(restTemplate.exchange(
188             ArgumentMatchers.endsWith("/testsuites"),
189             ArgumentMatchers.eq(HttpMethod.GET),
190             ArgumentMatchers.any(),
191             ArgumentMatchers.eq(listOfPairType)))
192         .thenReturn(new ResponseEntity(testSuites, HttpStatus.OK));
193
194     Mockito
195         .when(restTemplate.exchange(
196             ArgumentMatchers.endsWith("/testcases"),
197             ArgumentMatchers.eq(HttpMethod.GET),
198             ArgumentMatchers.any(),
199             ArgumentMatchers.eq(listOfCasesType)))
200         .thenReturn(new ResponseEntity(testCases, HttpStatus.OK));
201
202     Mockito
203         .when(restTemplate.exchange(
204             ArgumentMatchers.endsWith("/sriov"),
205             ArgumentMatchers.eq(HttpMethod.GET),
206             ArgumentMatchers.any(),
207             ArgumentMatchers.eq(caseType)))
208         .thenReturn(new ResponseEntity(testCase, HttpStatus.OK));
209
210
211     // POST for execution
212
213     Mockito
214         .when(restTemplate.exchange(
215             ArgumentMatchers.contains("executions"),
216             ArgumentMatchers.eq(HttpMethod.POST),
217             ArgumentMatchers.any(),
218             ArgumentMatchers.eq(new ParameterizedTypeReference<List<VtpTestExecutionResponse>>() {})))
219         .thenReturn(new ResponseEntity(runResults, HttpStatus.OK));
220
221
222     Mockito
223         .when(restTemplate.exchange(
224             ArgumentMatchers.contains("/executions/"),
225             ArgumentMatchers.eq(HttpMethod.GET),
226             ArgumentMatchers.any(),
227             ArgumentMatchers.eq(new ParameterizedTypeReference<VtpTestExecutionResponse>() {})))
228         .thenReturn(new ResponseEntity(priorExecution, HttpStatus.OK));
229
230
231     HttpStatusCodeException missingException = new HttpServerErrorException(HttpStatus.NOT_FOUND, "Not Found", headers, notFound.getBytes(), Charset.defaultCharset());
232     Mockito
233         .when(restTemplate.exchange(
234             ArgumentMatchers.endsWith("/missing"),
235             ArgumentMatchers.eq(HttpMethod.GET),
236             ArgumentMatchers.any(),
237             ArgumentMatchers.eq(caseType)))
238         .thenThrow(missingException);
239
240
241     Mockito
242         .when(restTemplate.exchange(
243             ArgumentMatchers.endsWith("/sitedown"),
244             ArgumentMatchers.eq(HttpMethod.GET),
245             ArgumentMatchers.any(),
246             ArgumentMatchers.eq(caseType)))
247         .thenThrow(new ResourceAccessException("Remote site is down"));
248
249     Mockito
250         .when(restTemplate.exchange(
251             ArgumentMatchers.endsWith("throwexception"),
252             ArgumentMatchers.eq(HttpMethod.POST),
253             ArgumentMatchers.any(),
254             ArgumentMatchers.eq(new ParameterizedTypeReference<List<VtpTestExecutionResponse>>() {})))
255         .thenThrow(missingException);
256
257
258     return mgr;
259   }
260
261   @Before
262   public void setConfigLocation() {
263     System.setProperty("config.location", "src/test/data");
264   }
265
266   @Test
267   public void testManager() throws IOException {
268     ExternalTestingManager m = configTestManager(true);
269
270     ClientConfiguration config = m.getConfig();
271     Assert.assertNotNull(config);
272
273     List<RemoteTestingEndpointDefinition> endpoints = m.getEndpoints();
274     Assert.assertEquals("two endpoints", 2, endpoints.size());
275
276
277     // this will exercise the internal APIs as well.
278     TestTreeNode root = m.getTestCasesAsTree();
279     Assert.assertEquals("two scenarios", 2, root.getChildren().size());
280
281
282     // handle case where remote endpoint is down.
283     try {
284       m.getTestCase("repository", "scen", "suite", "sitedown");
285       Assert.fail("not expected to retrieve sitedown test case");
286     }
287     catch (ExternalTestingException e) {
288       // expecting this exception.
289       Assert.assertNotNull(e.getDetail());
290       Assert.assertNotEquals(0, e.getHttpStatus());
291       Assert.assertNotNull(e.getMessageCode());
292     }
293
294     // get a particular test case
295     try {
296       m.getTestCase("repository", "scen", "suite", "missing");
297       Assert.fail("not expected to retrieve missing test case");
298     }
299     catch (ExternalTestingException e) {
300       // expecting this exception.
301       Assert.assertNotNull(e.getDetail());
302       Assert.assertNotEquals(0, e.getHttpStatus());
303       Assert.assertNotNull(e.getMessageCode());
304     }
305   }
306
307   @Test
308   public void testManagerExecution() throws IOException {
309     ExternalTestingManager m = configTestManager(true);
310
311     // execute a test.
312     List<VtpTestExecutionRequest> requests = new ArrayList<>();
313     VtpTestExecutionRequest req = new VtpTestExecutionRequest();
314     req.setEndpoint("repository");
315     requests.add(req);
316
317     // send a request with the endpoint defined.
318     List<VtpTestExecutionResponse> responses = m.execute(requests, "rid");
319     Assert.assertEquals(1, responses.size());
320
321     // send a request for a prior execution.
322     VtpTestExecutionResponse execRsp = m.getExecution("repository", "execId");
323     Assert.assertEquals("COMPLETE", execRsp.getStatus());
324   }
325
326   @Test
327   public void testMissingConfig() throws IOException {
328     // directory exists but no config file should be found here.
329     System.setProperty("config.location", "src/test");
330     ExternalTestingManager m = configTestManager(true);
331     Assert.assertFalse("missing config client enabled false", m.getConfig().isEnabled());
332     Assert.assertEquals("missing config no endpoints", 0, m.getEndpoints().size());
333   }
334
335   @Test
336   public void testMissingEndpoint() throws IOException {
337     ExternalTestingManager m = configTestManager(true);
338
339     // execute a test.
340     List<VtpTestExecutionRequest> requests = new ArrayList<>();
341     VtpTestExecutionRequest req = new VtpTestExecutionRequest();
342     req.setEndpoint("repository");
343     requests.add(req);
344
345     // send a request with the endpoint defined.
346     try {
347       m.execute(requests, "throwexception");
348     }
349     catch (ExternalTestingException e) {
350       // expected.
351     }
352   }
353
354
355   @Test
356   public void testManagerConfigOverrides() throws IOException {
357     ExternalTestingManager m = configTestManager(false);
358
359     ClientConfiguration cc = new ClientConfiguration();
360     cc.setEnabled(true);
361     m.setConfig(cc);
362     Assert.assertTrue(m.getConfig().isEnabled());
363
364     List<RemoteTestingEndpointDefinition> lst = new ArrayList<>();
365     lst.add(new RemoteTestingEndpointDefinition());
366     lst.get(0).setEnabled(true);
367     m.setEndpoints(lst);
368     Assert.assertEquals(1,m.getEndpoints().size());
369   }
370
371   @Test
372   public void testManagerErrorCases() throws IOException {
373     ExternalTestingManager m = configTestManager(false);
374     ClientConfiguration emptyConfig = m.getConfig();
375     Assert.assertFalse("empty configuration should have client enabled of false", emptyConfig.isEnabled());
376
377     try {
378       m.getEndpoints();
379       Assert.assertTrue("should have exception here", true);
380     }
381     catch (ExternalTestingException e) {
382       // eat the exception cause this is what should happen.
383     }
384   }
385
386   @Test
387   public void testExecutionDistribution() throws IOException {
388     ExternalTestingManager m = configTestManager(true);
389
390     VtpTestExecutionRequest r1 = new VtpTestExecutionRequest();
391     r1.setScenario("scenario1");
392     r1.setEndpoint("vtp");
393
394     VtpTestExecutionRequest r2 = new VtpTestExecutionRequest();
395     r2.setScenario("scenario2");
396     r2.setEndpoint("vtp");
397
398     VtpTestExecutionRequest r3 = new VtpTestExecutionRequest();
399     r3.setScenario("scenario3");
400     r3.setEndpoint("repository");
401
402     List<VtpTestExecutionResponse> results = m.execute(Arrays.asList(r1,r2,r3), "rid");
403     Assert.assertEquals("three in two out merged", 2, results.size());
404   }
405
406   @Test
407   public void testArchiveProcessing() throws IOException {
408     ExternalTestingManagerImpl m = configTestManager(true);
409     VtpTestExecutionRequest r1 = new VtpTestExecutionRequest();
410     r1.setScenario("scenario1");
411     r1.setEndpoint("vtp");
412     r1.setParameters(new HashMap<>());
413     r1.getParameters().put(ExternalTestingManagerImpl.VSP_ID, "something.with.csar.content");
414     r1.getParameters().put(ExternalTestingManagerImpl.VSP_VERSION, UUID.randomUUID().toString());
415
416     LinkedMultiValueMap<String,Object> body = new LinkedMultiValueMap<>();
417     m.attachArchiveContent(r1, body);
418
419     r1.setParameters(new HashMap<>());
420     r1.getParameters().put(ExternalTestingManagerImpl.VSP_ID, "something.with.heat.content");
421     r1.getParameters().put(ExternalTestingManagerImpl.VSP_VERSION, UUID.randomUUID().toString());
422
423     LinkedMultiValueMap<String,Object> body2 = new LinkedMultiValueMap<>();
424     m.attachArchiveContent(r1, body2);
425
426     // now, let's handle a missing archive.
427     r1.setParameters(new HashMap<>());
428     r1.getParameters().put(ExternalTestingManagerImpl.VSP_ID, "something.with.missing.content");
429     r1.getParameters().put(ExternalTestingManagerImpl.VSP_VERSION, UUID.randomUUID().toString());
430
431     LinkedMultiValueMap<String,Object> body3 = new LinkedMultiValueMap<>();
432     try {
433       m.attachArchiveContent(r1, body3);
434       Assert.fail("expected to receive an exception here");
435     }
436     catch (ExternalTestingException ex) {
437       Assert.assertEquals(500, ex.getHttpStatus());
438     }
439
440   }
441 }