d017408f6534338015c358fae1537176c5ebaf2f
[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 com.google.gson.Gson;
31
32 import java.io.IOException;
33 import java.net.ConnectException;
34 import java.net.SocketTimeoutException;
35 import java.util.List;
36
37 import org.apache.http.conn.ConnectTimeoutException;
38 import org.junit.Before;
39 import org.junit.Rule;
40 import org.junit.Test;
41 import org.mockito.Mockito;
42 import org.onap.aai.PayloadUtil;
43 import org.onap.aai.exceptions.AAIException;
44 import org.onap.aai.restclient.RestClient;
45 import org.springframework.boot.test.rule.OutputCapture;
46 import org.springframework.http.HttpMethod;
47 import org.springframework.http.ResponseEntity;
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()
81             throws IOException, AAIException {
82
83         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
84
85         Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
86                 eq(pserverRequest))).thenThrow(new RuntimeException(new ConnectException("Connection refused")));
87
88         validationService.preValidate(pserverRequest);
89
90         assertThat(capture.toString(),
91                 containsString("Connection refused to the validation microservice due to service unreachable"));
92     }
93
94     @Test
95     public void testPreValidateWithSuccessRequestAndServiceIsUnreachableAndShouldErrorWithConnectionTimeout()
96             throws IOException, AAIException {
97
98         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
99
100         Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
101                 eq(pserverRequest)))
102                 .thenThrow(new RuntimeException(new ConnectTimeoutException("Connection timed out")));
103
104         validationService.preValidate(pserverRequest);
105
106         assertThat(capture.toString(), containsString(
107                 "Connection timeout to the validation microservice as this could indicate the server is unable to reach port"));
108     }
109
110     @Test
111     public void testPreValidateWithSuccessRequestAndRespondSuccessfullyWithinAllowedTime()
112             throws IOException, AAIException {
113
114         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
115         String validationResponse =
116                 PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json");
117
118         ResponseEntity<String> responseEntity = Mockito.mock(ResponseEntity.class, Mockito.RETURNS_DEEP_STUBS);
119
120         Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
121                 eq(pserverRequest))).thenReturn(responseEntity);
122
123         Mockito.when(responseEntity.getStatusCodeValue()).thenReturn(200);
124         Mockito.when(responseEntity.getBody()).thenReturn(validationResponse);
125
126         Mockito.doReturn(true).when(validationService).isSuccess(responseEntity);
127
128         List<String> errorMessages = validationService.preValidate(pserverRequest);
129         assertNotNull("Expected the error messages to be not null", errorMessages);
130         assertThat(errorMessages.size(), is(0));
131     }
132
133     @Test
134     public void testPreValidateWithSuccessRequestAndServiceIsAvailableAndRequestIsTakingTooLongAndClientShouldTimeout()
135             throws IOException, AAIException {
136
137         String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json");
138
139         Mockito.when(restClient.execute(eq(ValidationService.VALIDATION_ENDPOINT), eq(HttpMethod.POST), any(),
140                 eq(pserverRequest)))
141                 .thenThrow(new RuntimeException(
142                         new SocketTimeoutException("Request timed out due to taking longer than client expected")));
143
144         validationService.preValidate(pserverRequest);
145
146         assertThat(capture.toString(),
147                 containsString("Request to validation service took longer than the currently set timeout"));
148     }
149
150     @Test
151     public void testExtractViolationsReturnsSuccessfullyAListWhenViolationsAreFound() throws IOException {
152
153         String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/failed-response-with-violations.json");
154
155         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
156         List<String> errorMessages = validationService.extractViolations(validation);
157         assertNotNull("Expected the error messages to be not null", errorMessages);
158         assertThat(errorMessages.size(), is(1));
159         assertThat(errorMessages.get(0),
160                 is("Invalid nf values, check nf-type, nf-role, nf-function, and nf-naming-code"));
161     }
162
163     @Test
164     public void testErrorMessagesAreEmptyListWhenViolationsReturnEmptyList() throws IOException {
165
166         String genericVnfRequest =
167                 PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json");
168
169         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
170         List<String> errorMessages = validationService.extractViolations(validation);
171         assertNotNull("Expected the error messages to be not null", errorMessages);
172         assertThat(errorMessages.size(), is(0));
173     }
174
175     @Test
176     public void testErrorMessagesAreEmptyListWhenViolationsIsNotFoundInJson() throws IOException {
177
178         String genericVnfRequest =
179                 PayloadUtil.getResourcePayload("prevalidation/success-response-with-exclude-violations.json");
180
181         Validation validation = gson.fromJson(genericVnfRequest, Validation.class);
182         List<String> errorMessages = validationService.extractViolations(validation);
183         assertNotNull("Expected the error messages to be not null", errorMessages);
184         assertThat(errorMessages.size(), is(0));
185     }
186 }