2 * Copyright (C) 2018 Bell Canada.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.ccsdk.sli.adaptors.netbox.impl;
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;
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;
48 import java.sql.SQLException;
49 import java.util.ArrayList;
50 import java.util.List;
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;
70 @RunWith(MockitoJUnitRunner.class)
71 public class NetboxClientImplTest {
73 private static final String APPLICATION_JSON = "application/json";
76 public WireMockRule wm = new WireMockRule(wireMockConfig().dynamicPort());
78 private DbLibService dbLib;
80 private SvcLogicContext svcLogicContext;
82 private Appender<ILoggingEvent> appender;
84 private ArgumentCaptor<ILoggingEvent> captor;
87 private String token = "token";
88 private String serviceInstanceId = UUID.randomUUID().toString();
89 private String vfModuleId = UUID.randomUUID().toString();
91 private Map<String, String> params = ImmutableMap
92 .of("service_instance_id", serviceInstanceId,
93 "vf_module_id", vfModuleId,
99 private NetboxHttpClient httpClient;
100 private NetboxClientImpl netboxClient;
103 private NetboxHttpClient httpClientMock;
105 private NetboxClientImpl netboxClientMock;
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);
114 String baseUrl = "http://localhost:" + wm.port();
116 httpClient = new NetboxHttpClient(baseUrl, token);
118 netboxClient = new NetboxClientImpl(httpClient, dbLib);
120 netboxClientMock = new NetboxClientImpl(httpClientMock, dbLib);
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());
132 public void tearDown() throws IOException {
137 public void unassignIpAddressTestNoParams() {
138 QueryStatus status = netboxClient.unassignIpAddress(ImmutableMap.of(), svcLogicContext);
139 Assert.assertEquals(QueryStatus.FAILURE, status);
141 "This method requires the parameters [service_instance_id,external_key], but no parameters were passed in.");
145 public void unassignIpAddressFailedRequest() throws IOException, SQLException {
146 doThrow(new IOException("Failed request")).when(httpClientMock).delete(anyString());
148 CachedRowSet crs = mock(CachedRowSet.class);
149 doReturn("3").when(crs).getString(eq("ip_address_id"));
150 doReturn(crs).when(dbLib).getData(anyString(), any(ArrayList.class), eq(null));
152 QueryStatus status = netboxClientMock
153 .unassignIpAddress(params, svcLogicContext);
155 Assert.assertEquals(QueryStatus.FAILURE, status);
156 verifyLogEntry("Fail to unassign IP for IPAddress(id= 3). Failed request");
160 public void unassignIpAddressServerError() throws SQLException {
162 String expectedUrl = "/api/ipam/ip-addresses/3/";
163 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(serverError()));
165 CachedRowSet crs = mock(CachedRowSet.class);
166 doReturn("3").when(crs).getString(eq("ip_address_id"));
167 doReturn(crs).when(dbLib).getData(anyString(), any(ArrayList.class), eq(null));
169 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
171 Assert.assertEquals(QueryStatus.FAILURE, status);
172 verifyLogEntry("Fail to unassign IP for IPAddress(id=3). HTTP code=500.");
176 public void unassignIpAddressFailSQL() throws IOException, SQLException {
178 String response = "{}";
180 String expectedUrl = "/api/ipam/ip-addresses/3/";
181 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
183 CachedRowSet crs = mock(CachedRowSet.class);
184 doReturn("3").when(crs).getString(eq("ip_address_id"));
185 doReturn(crs).when(dbLib).getData(anyString(), any(ArrayList.class), eq(null));
187 doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
189 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
191 Assert.assertEquals(QueryStatus.FAILURE, status);
192 verifyLogEntry("Caught SQL exception");
196 public void unassignIpAddressSuccess() throws IOException, SQLException {
197 String response = "{}";
199 String expectedUrl = "/api/ipam/ip-addresses/3/";
200 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
202 CachedRowSet crs = mock(CachedRowSet.class);
203 doReturn("3").when(crs).getString(eq("ip_address_id"));
204 doReturn(crs).when(dbLib).getData(anyString(), any(ArrayList.class), eq(null));
206 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
208 verify(deleteRequestedFor(urlEqualTo(expectedUrl))
209 .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
210 .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
211 .withHeader(AUTHORIZATION, equalTo("Token " + token)));
213 Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
214 Assert.assertEquals(QueryStatus.SUCCESS, status);
219 public void nextAvailableIpInPrefixTestNoId() {
220 QueryStatus status = netboxClient.assignIpAddress(ImmutableMap.of(), svcLogicContext);
221 Assert.assertEquals(QueryStatus.FAILURE, status);
223 "This method requires the parameters [service_instance_id,vf_module_id,prefix_id,resource_name,external_key], but no parameters were passed in.");
227 public void nextAvailableIpInPrefixFailedRequest() throws IOException {
228 doThrow(new IOException("Failed request")).when(httpClientMock).post(anyString(), anyString());
229 QueryStatus status = netboxClientMock.assignIpAddress(params, svcLogicContext);
231 Assert.assertEquals(QueryStatus.FAILURE, status);
232 verifyLogEntry("Fail to assign IP for Prefix(id=3). Failed request");
236 public void nextAvailableIpInPrefixBadRespPayload() throws IOException {
237 URL url = Resources.getResource("badResponse.json");
238 String response = Resources.toString(url, Charsets.UTF_8);
240 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
241 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
243 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
245 Assert.assertEquals(QueryStatus.FAILURE, status);
246 verifyLogEntry("Fail to parse IPAM JSON reponse to IPAddress POJO. IPAM JSON Response={\n"
248 + " \"address\": \"192.168.20.7/32\"\n"
253 public void nextAvailableIpInPrefixFailSQL() throws IOException, SQLException {
254 URL url = Resources.getResource("nextAvailableIpResponse.json");
255 String response = Resources.toString(url, Charsets.UTF_8);
257 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
258 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
260 doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
262 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
264 Assert.assertEquals(QueryStatus.FAILURE, status);
265 verifyLogEntry("Caught SQL exception");
269 public void nextAvailableIpInPrefixError500() throws IOException {
270 URL url = Resources.getResource("nextAvailableIpResponse.json");
271 String response = Resources.toString(url, Charsets.UTF_8);
273 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
274 givenThat(post(urlEqualTo(expectedUrl)).willReturn(serverError().withBody(response)));
276 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
278 Assert.assertEquals(QueryStatus.FAILURE, status);
279 verifyLogEntry("Fail to assign IP for Prefix(id=3). HTTP code 201!=500.");
283 public void nextAvailableIpInPrefixSuccess() throws IOException, SQLException {
284 URL url = Resources.getResource("nextAvailableIpResponse.json");
285 String response = Resources.toString(url, Charsets.UTF_8);
287 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
288 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
290 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
292 verify(postRequestedFor(urlEqualTo(expectedUrl))
293 .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
294 .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
295 .withHeader(AUTHORIZATION, equalTo("Token " + token)));
297 Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
298 Assert.assertEquals(QueryStatus.SUCCESS, status);
301 private void verifyLogEntry(String message) {
302 Mockito.verify(appender, times(1)).doAppend(captor.capture());
303 List<ILoggingEvent> allValues = captor.getAllValues();
304 for (ILoggingEvent loggingEvent : allValues) {
305 Assert.assertTrue(loggingEvent.getFormattedMessage().contains(message));