Merge "Migrate Mockito 1 to version 2 in aai-core"
[aai/aai-common.git] / aai-core / src / test / java / org / onap / aai / prevalidation / ValidationServiceTest.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2018-19 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.prevalidation;
22
23 import static org.hamcrest.CoreMatchers.containsString;
24 import static org.hamcrest.CoreMatchers.is;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertThat;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.ArgumentMatchers.eq;
29
30 import java.io.IOException;
31 import java.net.ConnectException;
32 import java.net.SocketTimeoutException;
33 import java.util.List;
34
35 import org.apache.http.conn.ConnectTimeoutException;
36 import org.junit.Before;
37 import org.junit.Rule;
38 import org.junit.Test;
39 import org.mockito.Mockito;
40 import org.onap.aai.PayloadUtil;
41 import org.onap.aai.exceptions.AAIException;
42 import org.onap.aai.restclient.RestClient;
43 import org.springframework.boot.test.rule.OutputCapture;
44 import org.springframework.http.HttpMethod;
45 import org.springframework.http.ResponseEntity;
46
47 import com.google.gson.Gson;
48
49 public class ValidationServiceTest {
50
51     private RestClient restClient;
52
53     private ValidationService validationService;
54
55     @Rule
56     public OutputCapture capture = new OutputCapture();
57
58     private Gson gson;
59
60     @Before
61     public void setUp() throws Exception {
62         gson = new Gson();
63         restClient = Mockito.mock(RestClient.class);
64         validationService = Mockito.spy(new ValidationService(restClient, "JUNIT", "generic-vnf", null));
65     }
66
67     @Test
68     public void testNodeTypeThatIsAllowedAndItShouldReturnTrue() {
69         boolean shouldValidate = validationService.shouldValidate("generic-vnf");
70         assertThat(shouldValidate, is(true));
71     }
72
73     @Test
74     public void testNodeTypeThatIsNotAllowedAndItShouldReturnFalse() {
75         boolean shouldValidate = validationService.shouldValidate("customer");
76         assertThat(shouldValidate, is(false));
77     }
78
79     @Test
80     public void testPreValidateWithSuccessRequestAndServiceIsDownAndShouldErrorWithConnectionRefused() throws IOException, AAIException {
81
82         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
83
84         Mockito
85             .when(
86                 restClient.execute(
87                     eq(ValidationService.VALIDATION_ENDPOINT),
88                     eq(HttpMethod.POST),
89                     any(),
90                     eq(pserverRequest)
91                 )
92             ).thenThrow(new RuntimeException(new ConnectException("Connection refused")));
93
94         validationService.preValidate(pserverRequest);
95
96         assertThat(capture.toString(), containsString("Connection refused to the validation microservice due to service unreachable"));
97     }
98
99     @Test
100     public void testPreValidateWithSuccessRequestAndServiceIsUnreachableAndShouldErrorWithConnectionTimeout() throws IOException, AAIException {
101
102         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
103
104         Mockito
105             .when(
106                 restClient.execute(
107                     eq(ValidationService.VALIDATION_ENDPOINT),
108                     eq(HttpMethod.POST),
109                     any(),
110                     eq(pserverRequest)
111                 )
112             ).thenThrow(new RuntimeException(new ConnectTimeoutException("Connection timed out")));
113
114         validationService.preValidate(pserverRequest);
115
116         assertThat(capture.toString(), containsString("Connection timeout to the validation microservice as this could indicate the server is unable to reach port"));
117     }
118
119     @Test
120     public void testPreValidateWithSuccessRequestAndRespondSuccessfullyWithinAllowedTime() throws IOException, AAIException {
121
122         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
123         String validationResponse = PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json");
124
125         ResponseEntity responseEntity = Mockito.mock(ResponseEntity.class, Mockito.RETURNS_DEEP_STUBS);
126
127         Mockito
128             .when(
129                 restClient.execute(
130                     eq(ValidationService.VALIDATION_ENDPOINT),
131                     eq(HttpMethod.POST),
132                     any(),
133                     eq(pserverRequest)
134                 )
135             ).thenReturn(responseEntity);
136
137         Mockito.when(responseEntity.getStatusCodeValue()).thenReturn(200);
138         Mockito.when(responseEntity.getBody()).thenReturn(validationResponse);
139
140         Mockito.doReturn(true).when(validationService).isSuccess(responseEntity);
141
142         List<String> errorMessages = validationService.preValidate(pserverRequest);
143         assertNotNull("Expected the error messages to be not null", errorMessages);
144         assertThat(errorMessages.size(), is(0));
145     }
146
147     @Test
148     public void testPreValidateWithSuccessRequestAndServiceIsAvailableAndRequestIsTakingTooLongAndClientShouldTimeout() throws IOException, AAIException {
149
150         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
151
152         Mockito
153             .when(
154                 restClient.execute(
155                     eq(ValidationService.VALIDATION_ENDPOINT),
156                     eq(HttpMethod.POST),
157                     any(),
158                     eq(pserverRequest)
159                 )
160             ).thenThrow(new RuntimeException(new SocketTimeoutException("Request timed out due to taking longer than client expected")));
161
162         validationService.preValidate(pserverRequest);
163
164         assertThat(capture.toString(), containsString("Request to validation service took longer than the currently set timeout"));
165     }
166
167     @Test
168     public void testExtractViolationsReturnsSuccessfullyAListWhenViolationsAreFound() throws IOException {
169
170         String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/failed-response-with-violations.json");
171
172         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
173         List<String> errorMessages = validationService.extractViolations(validation);
174         assertNotNull("Expected the error messages to be not null", errorMessages);
175         assertThat(errorMessages.size(), is(1));
176         assertThat(errorMessages.get(0), is("Invalid nf values, check nf-type, nf-role, nf-function, and nf-naming-code"));
177     }
178
179     @Test
180     public void testErrorMessagesAreEmptyListWhenViolationsReturnEmptyList() throws IOException {
181
182         String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json");
183
184         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
185         List<String> errorMessages = validationService.extractViolations(validation);
186         assertNotNull("Expected the error messages to be not null", errorMessages);
187         assertThat(errorMessages.size(), is(0));
188     }
189
190     @Test
191     public void testErrorMessagesAreEmptyListWhenViolationsIsNotFoundInJson() throws IOException {
192
193         String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/success-response-with-exclude-violations.json");
194
195         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
196         List<String> errorMessages = validationService.extractViolations(validation);
197         assertNotNull("Expected the error messages to be not null", errorMessages);
198         assertThat(errorMessages.size(), is(0));
199     }
200 }