Add SvcLogicContext interaction with netbox-client
[ccsdk/sli/adaptors.git] / netbox-client / provider / src / test / java / org / onap / ccsdk / sli / adaptors / netbox / impl / NetboxClientImplTest.java
1 /*
2  * Copyright (C) 2018 Bell Canada.
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.ccsdk.sli.adaptors.netbox.impl;
17
18 import static com.github.tomakehurst.wiremock.client.WireMock.created;
19 import static com.github.tomakehurst.wiremock.client.WireMock.delete;
20 import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor;
21 import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
22 import static com.github.tomakehurst.wiremock.client.WireMock.givenThat;
23 import static com.github.tomakehurst.wiremock.client.WireMock.post;
24 import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
25 import static com.github.tomakehurst.wiremock.client.WireMock.serverError;
26 import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
27 import static com.github.tomakehurst.wiremock.client.WireMock.verify;
28 import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
29 import static org.apache.http.HttpHeaders.ACCEPT;
30 import static org.apache.http.HttpHeaders.AUTHORIZATION;
31 import static org.apache.http.HttpHeaders.CONTENT_TYPE;
32 import static org.mockito.ArgumentMatchers.any;
33 import static org.mockito.ArgumentMatchers.anyString;
34 import static org.mockito.ArgumentMatchers.eq;
35 import static org.mockito.Mockito.doThrow;
36 import static org.mockito.Mockito.times;
37
38 import ch.qos.logback.classic.spi.ILoggingEvent;
39 import ch.qos.logback.core.Appender;
40 import com.github.tomakehurst.wiremock.junit.WireMockRule;
41 import com.google.common.base.Charsets;
42 import com.google.common.collect.ImmutableMap;
43 import com.google.common.io.Resources;
44 import java.io.IOException;
45 import java.net.URL;
46 import java.sql.SQLException;
47 import java.util.ArrayList;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.UUID;
51 import org.junit.After;
52 import org.junit.Assert;
53 import org.junit.Before;
54 import org.junit.Rule;
55 import org.junit.Test;
56 import org.junit.runner.RunWith;
57 import org.mockito.ArgumentCaptor;
58 import org.mockito.Captor;
59 import org.mockito.Mock;
60 import org.mockito.Mockito;
61 import org.mockito.runners.MockitoJUnitRunner;
62 import org.onap.ccsdk.sli.core.dblib.DbLibService;
63 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
64 import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus;
65 import org.slf4j.LoggerFactory;
66
67 @RunWith(MockitoJUnitRunner.class)
68 public class NetboxClientImplTest {
69
70     private static final String APPLICATION_JSON = "application/json";
71
72     @Rule
73     public WireMockRule wm = new WireMockRule(wireMockConfig().dynamicPort());
74     @Mock
75     private DbLibService dbLib;
76     @Mock
77     private SvcLogicContext svcLogicContext;
78     @Mock
79     private Appender<ILoggingEvent> appender;
80     @Captor
81     private ArgumentCaptor<ILoggingEvent> captor;
82
83
84     private String token = "token";
85     private String serviceInstanceId = UUID.randomUUID().toString();
86     private String vfModuleId = UUID.randomUUID().toString();
87
88     private Map<String, String> params = ImmutableMap
89         .of("service_instance_id", serviceInstanceId,
90             "vf_module_id", vfModuleId,
91             "prefix_id", "3",
92             "ip_address_id", "3"
93         );
94
95     private NetboxHttpClient httpClient;
96     private NetboxClientImpl netboxClient;
97
98     @Mock
99     private NetboxHttpClient httpClientMock;
100     @Mock
101     private NetboxClientImpl netboxClientMock;
102
103
104     @Before
105     public void setup() {
106         ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
107             .getLogger(NetboxClientImpl.class);
108         logger.addAppender(appender);
109
110         String baseUrl = "http://localhost:" + wm.port();
111
112         httpClient = new NetboxHttpClient(baseUrl, token);
113
114         netboxClient = new NetboxClientImpl(httpClient, dbLib);
115
116         netboxClientMock = new NetboxClientImpl(httpClientMock, dbLib);
117
118         wm.addMockServiceRequestListener(
119             (request, response) -> {
120                 System.out.println("Request URL :" + request.getAbsoluteUrl());
121                 System.out.println("Request body :" + request.getBodyAsString());
122                 System.out.println("Response status :" + response.getStatus());
123                 System.out.println("Response body :" + response.getBodyAsString());
124             });
125     }
126
127     @After
128     public void tearDown() throws IOException {
129         httpClient.close();
130     }
131
132     @Test
133     public void unassignIpAddressTestNoParams() {
134         QueryStatus status = netboxClient.unassignIpAddress(ImmutableMap.of(), svcLogicContext);
135         Assert.assertEquals(QueryStatus.FAILURE, status);
136         verifyLogEntry("This method requires the parameters [service_instance_id,vf_module_id,ip_address_id], but no parameters were passed in");
137     }
138
139     @Test
140     public void unassignIpAddressFailedRequest() throws IOException {
141         doThrow(new IOException("Failed request")).when(httpClientMock).delete(anyString());
142         QueryStatus status = netboxClientMock
143             .unassignIpAddress(params, svcLogicContext);
144
145         Assert.assertEquals(QueryStatus.FAILURE, status);
146         verifyLogEntry("Fail to unassign IP for IPAddress(id= 3). Failed request");
147     }
148
149     @Test
150     public void unassignIpAddressServerError() {
151
152         String expectedUrl = "/api/ipam/ip-addresses/3/";
153         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(serverError()));
154
155         QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
156
157         Assert.assertEquals(QueryStatus.FAILURE, status);
158         verifyLogEntry("Fail to unassign IP for IPAddress(id=3). HTTP code=500.");
159     }
160
161     @Test
162     public void unassignIpAddressFailSQL() throws IOException, SQLException {
163
164         String response = "{}";
165
166         String expectedUrl = "/api/ipam/ip-addresses/3/";
167         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
168
169         doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
170
171         QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
172
173         Assert.assertEquals(QueryStatus.FAILURE, status);
174         verifyLogEntry("Caught SQL exception");
175     }
176
177     @Test
178     public void unassignIpAddressSuccess() throws IOException, SQLException {
179         String response = "{}";
180
181         String expectedUrl = "/api/ipam/ip-addresses/3/";
182         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
183
184         QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
185
186         verify(deleteRequestedFor(urlEqualTo(expectedUrl))
187             .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
188             .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
189             .withHeader(AUTHORIZATION, equalTo("Token " + token)));
190
191         Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
192         Assert.assertEquals(QueryStatus.SUCCESS, status);
193     }
194
195
196     @Test
197     public void nextAvailableIpInPrefixTestNoId() {
198         QueryStatus status = netboxClient.assignIpAddress(ImmutableMap.of(), svcLogicContext);
199         Assert.assertEquals(QueryStatus.FAILURE, status);
200         verifyLogEntry("This method requires the parameters [service_instance_id,vf_module_id,prefix_id], but no parameters were passed in");
201     }
202
203     @Test
204     public void nextAvailableIpInPrefixFailedRequest() throws IOException {
205         doThrow(new IOException("Failed request")).when(httpClientMock).post(anyString(), anyString());
206         QueryStatus status = netboxClientMock.assignIpAddress(params, svcLogicContext);
207
208         Assert.assertEquals(QueryStatus.FAILURE, status);
209         verifyLogEntry("Fail to assign IP for Prefix(id=3). Failed request");
210     }
211
212     @Test
213     public void nextAvailableIpInPrefixBadRespPayload() throws IOException {
214         URL url = Resources.getResource("badResponse.json");
215         String response = Resources.toString(url, Charsets.UTF_8);
216
217         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
218         givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
219
220         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
221
222         Assert.assertEquals(QueryStatus.FAILURE, status);
223         verifyLogEntry("Fail to parse IPAM JSON reponse to IPAddress POJO. IPAM JSON Response={\n"
224             + "  \"id\": 8\n"
225             + "  \"address\": \"192.168.20.7/32\"\n"
226             + "}");
227     }
228
229     @Test
230     public void nextAvailableIpInPrefixFailSQL() throws IOException, SQLException {
231         URL url = Resources.getResource("nextAvailableIpResponse.json");
232         String response = Resources.toString(url, Charsets.UTF_8);
233
234         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
235         givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
236
237         doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
238
239         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
240
241         Assert.assertEquals(QueryStatus.FAILURE, status);
242         verifyLogEntry("Caught SQL exception");
243     }
244
245     @Test
246     public void nextAvailableIpInPrefixError500() throws IOException {
247         URL url = Resources.getResource("nextAvailableIpResponse.json");
248         String response = Resources.toString(url, Charsets.UTF_8);
249
250         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
251         givenThat(post(urlEqualTo(expectedUrl)).willReturn(serverError().withBody(response)));
252
253         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
254
255         Assert.assertEquals(QueryStatus.FAILURE, status);
256         verifyLogEntry("Fail to assign IP for Prefix(id=3). HTTP code 201!=500.");
257     }
258
259     @Test
260     public void nextAvailableIpInPrefixSuccess() throws IOException, SQLException {
261         URL url = Resources.getResource("nextAvailableIpResponse.json");
262         String response = Resources.toString(url, Charsets.UTF_8);
263
264         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
265         givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
266
267         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
268
269         verify(postRequestedFor(urlEqualTo(expectedUrl))
270             .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
271             .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
272             .withHeader(AUTHORIZATION, equalTo("Token " + token)));
273
274         Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
275         Assert.assertEquals(QueryStatus.SUCCESS, status);
276     }
277
278     private void verifyLogEntry(String message) {
279         Mockito.verify(appender, times(1)).doAppend(captor.capture());
280         List<ILoggingEvent> allValues = captor.getAllValues();
281         for (ILoggingEvent loggingEvent : allValues) {
282             Assert.assertTrue(loggingEvent.getFormattedMessage().contains(message));
283         }
284     }
285
286 }