953f7da0a72df14deaa71a4a45437b8beace6832
[vfc/nfvo/driver/vnfm/svnfm.git] / nokiav2 / driver / src / test / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / nokia / onap / direct / TestAAIRestApiProvider.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
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 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.onap.direct;
17
18 import org.junit.Before;
19 import org.junit.Test;
20 import org.mockito.ArgumentCaptor;
21 import org.mockito.Mock;
22 import org.mockito.Mockito;
23 import org.onap.aai.domain.yang.v11.GenericVnf;
24 import org.onap.aai.domain.yang.v11.L3Network;
25 import org.onap.aai.domain.yang.v11.ObjectFactory;
26 import org.onap.aai.restclient.client.OperationResult;
27 import org.onap.aai.restclient.client.RestClient;
28 import org.onap.aai.restclient.enums.RestAuthenticationMode;
29 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.TestBase;
30
31 import javax.xml.bind.JAXBContext;
32 import java.io.ByteArrayOutputStream;
33 import java.io.StringReader;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.NoSuchElementException;
37
38 import static com.google.common.collect.Lists.newArrayList;
39 import static java.util.Base64.getEncoder;
40 import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE;
41 import static junit.framework.TestCase.*;
42 import static org.mockito.Matchers.eq;
43 import static org.mockito.Mockito.verify;
44 import static org.mockito.Mockito.when;
45 import static org.springframework.test.util.ReflectionTestUtils.setField;
46
47 public class TestAAIRestApiProvider extends TestBase {
48     private ObjectFactory OBJECT_FACTORY = new ObjectFactory();
49     @Mock
50     private RestClient restClient;
51     private AAIRestApiProvider aaiRestApiProvider;
52     private ArgumentCaptor<Map> headers = ArgumentCaptor.forClass(Map.class);
53     private ArgumentCaptor<String> payload = ArgumentCaptor.forClass(String.class);
54
55     private OperationResult result = new OperationResult();
56
57     public static String marshall(Object object) throws Exception {
58         ByteArrayOutputStream bos = new ByteArrayOutputStream();
59         JAXBContext.newInstance(object.getClass()).createMarshaller().marshal(object, bos);
60         return bos.toString();
61     }
62
63     public static <T> T unmarshal(String content, Class<T> clazz) {
64         try {
65             return (T) JAXBContext.newInstance(clazz).createUnmarshaller().unmarshal(new StringReader(content));
66         } catch (Exception e) {
67             throw new RuntimeException();
68         }
69     }
70
71     @Before
72     public void init() {
73         //MockitoAnnotations.initMocks(this);
74         AAIRestApiProvider real = new AAIRestApiProvider(msbApiProvider);
75         setField(AAIRestApiProvider.class, "logger", logger);
76         setFieldWithPropertyAnnotation(real, "${aaiUsername}", "aaiUsername");
77         setFieldWithPropertyAnnotation(real, "${aaiPassword}", "aaiPassword");
78         aaiRestApiProvider = Mockito.spy(real);
79         when(aaiRestApiProvider.buildRawClient()).thenReturn(restClient);
80         when(restClient.basicAuthPassword("aaiPassword")).thenReturn(restClient);
81         when(restClient.basicAuthUsername("aaiUsername")).thenReturn(restClient);
82         when(restClient.authenticationMode(RestAuthenticationMode.SSL_BASIC)).thenReturn(restClient);
83         when(msbApiProvider.getMicroServiceUrl(AAIRestApiProvider.AAIService.CLOUD.getServiceName(), "v11")).thenReturn("x://1.2.3.4:4/a");
84         result.setResultCode(201);
85     }
86
87     /**
88      * test HTTP GET success scenario
89      */
90     @Test
91     public void testGetSuccess() throws Exception {
92         GenericVnf vnf = OBJECT_FACTORY.createGenericVnf();
93         vnf.setVnfId("myVnfId");
94         when(restClient.get(eq("x://1.2.3.4:4/a/myurl"), headers.capture(), eq(APPLICATION_XML_TYPE))).thenReturn(result);
95         result.setResult(marshall(vnf));
96         //when
97         GenericVnf actualVnf = aaiRestApiProvider.get(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl", GenericVnf.class);
98         //verify
99         assertEquals(vnf.getVnfId(), actualVnf.getVnfId());
100         assertHeaders();
101     }
102
103     /**
104      * HTTP GET on non existing resource results in {@link java.util.NoSuchElementException}
105      */
106     @Test
107     public void testGetMissingResource() throws Exception {
108         when(restClient.get(eq("x://1.2.3.4:4/a/myurl"), headers.capture(), eq(APPLICATION_XML_TYPE))).thenReturn(result);
109         result.setResultCode(404);
110         //when
111         try {
112             aaiRestApiProvider.get(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl", GenericVnf.class);
113             fail();
114         } catch (NoSuchElementException e) {
115             verify(logger).debug("The resource at /myurl does not exists");
116             assertEquals("The resource at /myurl does not exists", e.getMessage());
117         }
118     }
119
120     /**
121      * Non known HTTP response code is propagated
122      */
123     @Test
124     public void testUnknownErroCode() throws Exception {
125         when(restClient.get(eq("x://1.2.3.4:4/a/myurl"), headers.capture(), eq(APPLICATION_XML_TYPE))).thenReturn(result);
126         result.setResultCode(502);
127         result.setFailureCause("myFail");
128         //when
129         try {
130             aaiRestApiProvider.get(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl", GenericVnf.class);
131             fail();
132         } catch (RuntimeException e) {
133             verify(logger).error("Bad response. Code: 502 cause: myFail");
134             assertEquals("Bad response. Code: 502 cause: myFail", e.getMessage());
135         }
136     }
137
138     /**
139      * response content is not used when not requesting result
140      */
141     @Test
142     public void testNoResult() throws Exception {
143         when(restClient.get(eq("x://1.2.3.4:4/a/myurl"), headers.capture(), eq(APPLICATION_XML_TYPE))).thenReturn(result);
144         result.setResultCode(202);
145         //when
146         Void result = aaiRestApiProvider.get(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl", Void.class);
147         //verify
148         assertNull(result);
149     }
150
151     /**
152      * test HTTP PUT success scenario
153      */
154     @Test
155     public void putSuccess() throws Exception {
156         when(restClient.put(eq("x://1.2.3.4:4/a/myurl"), payload.capture(), headers.capture(), eq(APPLICATION_XML_TYPE), eq(APPLICATION_XML_TYPE))).thenReturn(result);
157         GenericVnf request = OBJECT_FACTORY.createGenericVnf();
158         request.setVnfId("myVnfId");
159         L3Network response = OBJECT_FACTORY.createL3Network();
160         response.setNetworkId("myNetworkId");
161         result.setResult(marshall(response));
162         //when
163         L3Network actualResponse = aaiRestApiProvider.put(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl", request, L3Network.class);
164         //verify
165         GenericVnf actualValue = unmarshal(payload.getValue(), GenericVnf.class);
166         assertEquals("myVnfId", actualValue.getVnfId());
167         assertEquals("myNetworkId", actualResponse.getNetworkId());
168         assertHeaders();
169     }
170
171     /**
172      * test HTTP delete success scenario
173      */
174     @Test
175     public void deleteSuccess() throws Exception {
176         when(restClient.delete(eq("x://1.2.3.4:4/a/myurl"), headers.capture(), eq(APPLICATION_XML_TYPE))).thenReturn(result);
177         //when
178         aaiRestApiProvider.delete(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl");
179         //verify
180         assertHeaders();
181         //the when above is the verify
182     }
183
184     /**
185      * invalid request content results in error
186      */
187     @Test
188     public void testInvalidInput() throws Exception {
189         when(restClient.put(eq("x://1.2.3.4:4/a/myurl"), payload.capture(), headers.capture(), eq(APPLICATION_XML_TYPE), eq(APPLICATION_XML_TYPE))).thenReturn(result);
190         //when
191         try {
192             aaiRestApiProvider.put(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl", "Invalid content", L3Network.class);
193             //verify
194             fail();
195         } catch (Exception e) {
196             assertEquals("Unable to marshal content", e.getMessage());
197             verify(logger).error("Unable to marshal content", e.getCause());
198         }
199     }
200
201     /**
202      * invalid response content results in error
203      */
204     @Test
205     public void testInvalidResponse() throws Exception {
206         when(restClient.put(eq("x://1.2.3.4:4/a/myurl"), payload.capture(), headers.capture(), eq(APPLICATION_XML_TYPE), eq(APPLICATION_XML_TYPE))).thenReturn(result);
207         GenericVnf request = OBJECT_FACTORY.createGenericVnf();
208         request.setVnfId("myVnfId");
209         result.setResult("invalid");
210         //when
211         try {
212             aaiRestApiProvider.put(logger, AAIRestApiProvider.AAIService.CLOUD, "/myurl", request, L3Network.class);
213             //verify
214             fail();
215         } catch (Exception e) {
216             assertEquals("Unable to unmarshal content", e.getMessage());
217             verify(logger).error("Unable to unmarshal content", e.getCause());
218         }
219     }
220
221     /**
222      * test AAI service names in AAI
223      */
224     @Test
225     public void testServiceNames() {
226         //the names have been base64-ed to prevent "smart" IDEs (idea) to refactor the tests too for the otherwise known fix constants in external systems
227         assertEquals("YWFpLWNsb3VkSW5mcmFzdHJ1Y3R1cmU=", getEncoder().encodeToString(AAIRestApiProvider.AAIService.CLOUD.getServiceName().getBytes()));
228         assertEquals("YWFpLW5ldHdvcms=", getEncoder().encodeToString(AAIRestApiProvider.AAIService.NETWORK.getServiceName().getBytes()));
229         assertEquals("YWFpLWV4dGVybmFsU3lzdGVt", getEncoder().encodeToString(AAIRestApiProvider.AAIService.ESR.getServiceName().getBytes()));
230     }
231
232     private void assertHeaders() {
233         Map<String, List<String>> actualHeaders = headers.getValue();
234         assertEquals(2, actualHeaders.size());
235         assertEquals(newArrayList("NokiaSVNFM"), actualHeaders.get("X-FromAppId"));
236         assertEquals(newArrayList("application/xml"), actualHeaders.get("Accept"));
237     }
238 }