Enhancements for the aai-common library
[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 com.google.gson.Gson;
24 import org.apache.http.conn.ConnectTimeoutException;
25 import org.junit.Before;
26 import org.junit.Rule;
27 import org.junit.Test;
28 import org.mockito.Mockito;
29 import org.onap.aai.PayloadUtil;
30 import org.onap.aai.exceptions.AAIException;
31 import org.onap.aai.restclient.RestClient;
32 import org.springframework.boot.test.rule.OutputCapture;
33 import org.springframework.http.HttpMethod;
34 import org.springframework.http.ResponseEntity;
35
36 import java.io.IOException;
37 import java.net.ConnectException;
38 import java.net.SocketTimeoutException;
39 import java.util.List;
40
41 import static org.hamcrest.CoreMatchers.containsString;
42 import static org.hamcrest.CoreMatchers.is;
43 import static org.junit.Assert.assertNotNull;
44 import static org.junit.Assert.assertThat;
45 import static org.mockito.Matchers.any;
46 import static org.mockito.Matchers.eq;
47
48 public class ValidationServiceTest {
49
50     private RestClient restClient;
51
52     private ValidationService validationService;
53
54     @Rule
55     public OutputCapture capture = new OutputCapture();
56
57     private Gson gson;
58
59     @Before
60     public void setUp() throws Exception {
61         gson = new Gson();
62         restClient = Mockito.mock(RestClient.class);
63         validationService = Mockito.spy(new ValidationService(restClient, "JUNIT", "generic-vnf", null));
64     }
65
66     @Test
67     public void testNodeTypeThatIsAllowedAndItShouldReturnTrue() {
68         boolean shouldValidate = validationService.shouldValidate("generic-vnf");
69         assertThat(shouldValidate, is(true));
70     }
71
72     @Test
73     public void testNodeTypeThatIsNotAllowedAndItShouldReturnFalse() {
74         boolean shouldValidate = validationService.shouldValidate("customer");
75         assertThat(shouldValidate, is(false));
76     }
77
78     @Test
79     public void testPreValidateWithSuccessRequestAndServiceIsDownAndShouldErrorWithConnectionRefused() throws IOException, AAIException {
80
81         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
82
83         Mockito
84             .when(
85                 restClient.execute(
86                     eq(ValidationService.VALIDATION_ENDPOINT),
87                     eq(HttpMethod.POST),
88                     any(),
89                     eq(pserverRequest)
90                 )
91             ).thenThrow(new RuntimeException(new ConnectException("Connection refused")));
92
93         validationService.preValidate(pserverRequest);
94
95         assertThat(capture.toString(), containsString("Connection refused to the validation microservice due to service unreachable"));
96     }
97
98     @Test
99     public void testPreValidateWithSuccessRequestAndServiceIsUnreachableAndShouldErrorWithConnectionTimeout() throws IOException, AAIException {
100
101         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
102
103         Mockito
104             .when(
105                 restClient.execute(
106                     eq(ValidationService.VALIDATION_ENDPOINT),
107                     eq(HttpMethod.POST),
108                     any(),
109                     eq(pserverRequest)
110                 )
111             ).thenThrow(new RuntimeException(new ConnectTimeoutException("Connection timed out")));
112
113         validationService.preValidate(pserverRequest);
114
115         assertThat(capture.toString(), containsString("Connection timeout to the validation microservice as this could indicate the server is unable to reach port"));
116     }
117
118     @Test
119     public void testPreValidateWithSuccessRequestAndRespondSuccessfullyWithinAllowedTime() throws IOException, AAIException {
120
121         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
122         String validationResponse = PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json");
123
124         ResponseEntity responseEntity = Mockito.mock(ResponseEntity.class, Mockito.RETURNS_DEEP_STUBS);
125
126         Mockito
127             .when(
128                 restClient.execute(
129                     eq(ValidationService.VALIDATION_ENDPOINT),
130                     eq(HttpMethod.POST),
131                     any(),
132                     eq(pserverRequest)
133                 )
134             ).thenReturn(responseEntity);
135
136         Mockito.when(responseEntity.getStatusCodeValue()).thenReturn(200);
137         Mockito.when(responseEntity.getBody()).thenReturn(validationResponse);
138
139         Mockito.doReturn(true).when(validationService).isSuccess(responseEntity);
140
141         List<String> errorMessages = validationService.preValidate(pserverRequest);
142         assertNotNull("Expected the error messages to be not null", errorMessages);
143         assertThat(errorMessages.size(), is(0));
144     }
145
146     @Test
147     public void testPreValidateWithSuccessRequestAndServiceIsAvailableAndRequestIsTakingTooLongAndClientShouldTimeout() throws IOException, AAIException {
148
149         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
150
151         Mockito
152             .when(
153                 restClient.execute(
154                     eq(ValidationService.VALIDATION_ENDPOINT),
155                     eq(HttpMethod.POST),
156                     any(),
157                     eq(pserverRequest)
158                 )
159             ).thenThrow(new RuntimeException(new SocketTimeoutException("Request timed out due to taking longer than client expected")));
160
161         validationService.preValidate(pserverRequest);
162
163         assertThat(capture.toString(), containsString("Request to validation service took longer than the currently set timeout"));
164     }
165
166     @Test
167     public void testExtractViolationsReturnsSuccessfullyAListWhenViolationsAreFound() throws IOException {
168
169         String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/failed-response-with-violations.json");
170
171         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
172         List<String> errorMessages = validationService.extractViolations(validation);
173         assertNotNull("Expected the error messages to be not null", errorMessages);
174         assertThat(errorMessages.size(), is(1));
175         assertThat(errorMessages.get(0), is("Invalid nf values, check nf-type, nf-role, nf-function, and nf-naming-code"));
176     }
177
178     @Test
179     public void testErrorMessagesAreEmptyListWhenViolationsReturnEmptyList() throws IOException {
180
181         String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json");
182
183         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
184         List<String> errorMessages = validationService.extractViolations(validation);
185         assertNotNull("Expected the error messages to be not null", errorMessages);
186         assertThat(errorMessages.size(), is(0));
187     }
188
189     @Test
190     public void testErrorMessagesAreEmptyListWhenViolationsIsNotFoundInJson() throws IOException {
191
192         String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/success-response-with-exclude-violations.json");
193
194         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
195         List<String> errorMessages = validationService.extractViolations(validation);
196         assertNotNull("Expected the error messages to be not null", errorMessages);
197         assertThat(errorMessages.size(), is(0));
198     }
199 }