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