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(true).when(crs).next();
151 doReturn(crs).when(dbLib).getData(anyString(), any(ArrayList.class), eq(null));
153 QueryStatus status = netboxClientMock
154 .unassignIpAddress(params, svcLogicContext);
156 Assert.assertEquals(QueryStatus.FAILURE, status);
157 verifyLogEntry("Fail to unassign IP for IPAddress(id= 3). Failed request");
161 public void unassignIpAddressServerError() throws SQLException {
163 String expectedUrl = "/api/ipam/ip-addresses/3/";
164 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(serverError()));
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));
171 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
173 Assert.assertEquals(QueryStatus.FAILURE, status);
174 verifyLogEntry("Fail to unassign IP for IPAddress(id=3). HTTP code=500.");
178 public void unassignIpAddressFailSQL() throws IOException, SQLException {
180 String response = "{}";
182 String expectedUrl = "/api/ipam/ip-addresses/3/";
183 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
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));
190 doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
192 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
194 Assert.assertEquals(QueryStatus.FAILURE, status);
195 verifyLogEntry("Caught SQL exception");
199 public void unassignIpAddressSuccess() throws IOException, SQLException {
200 String response = "{}";
202 String expectedUrl = "/api/ipam/ip-addresses/3/";
203 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
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));
210 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
212 verify(deleteRequestedFor(urlEqualTo(expectedUrl))
213 .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
214 .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
215 .withHeader(AUTHORIZATION, equalTo("Token " + token)));
217 Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
218 Assert.assertEquals(QueryStatus.SUCCESS, status);
223 public void nextAvailableIpInPrefixTestNoId() {
224 QueryStatus status = netboxClient.assignIpAddress(ImmutableMap.of(), svcLogicContext);
225 Assert.assertEquals(QueryStatus.FAILURE, status);
227 "This method requires the parameters [service_instance_id,vf_module_id,prefix_id,resource_name,external_key], but no parameters were passed in.");
231 public void nextAvailableIpInPrefixFailedRequest() throws IOException {
232 doThrow(new IOException("Failed request")).when(httpClientMock).post(anyString(), anyString());
233 QueryStatus status = netboxClientMock.assignIpAddress(params, svcLogicContext);
235 Assert.assertEquals(QueryStatus.FAILURE, status);
236 verifyLogEntry("Fail to assign IP for Prefix(id=3). Failed request");
240 public void nextAvailableIpInPrefixBadRespPayload() throws IOException {
241 URL url = Resources.getResource("badResponse.json");
242 String response = Resources.toString(url, Charsets.UTF_8);
244 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
245 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
247 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
249 Assert.assertEquals(QueryStatus.FAILURE, status);
250 verifyLogEntry("Fail to parse IPAM JSON reponse to IPAddress POJO. IPAM JSON Response={\n"
252 + " \"address\": \"192.168.20.7/32\"\n"
257 public void nextAvailableIpInPrefixFailSQL() throws IOException, SQLException {
258 URL url = Resources.getResource("nextAvailableIpResponse.json");
259 String response = Resources.toString(url, Charsets.UTF_8);
261 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
262 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
264 doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
266 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
268 Assert.assertEquals(QueryStatus.FAILURE, status);
269 verifyLogEntry("Caught SQL exception");
273 public void nextAvailableIpInPrefixError500() throws IOException {
274 URL url = Resources.getResource("nextAvailableIpResponse.json");
275 String response = Resources.toString(url, Charsets.UTF_8);
277 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
278 givenThat(post(urlEqualTo(expectedUrl)).willReturn(serverError().withBody(response)));
280 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
282 Assert.assertEquals(QueryStatus.FAILURE, status);
283 verifyLogEntry("Fail to assign IP for Prefix(id=3). HTTP code 201!=500.");
287 public void nextAvailableIpInPrefixSuccess() throws IOException, SQLException {
288 URL url = Resources.getResource("nextAvailableIpResponse.json");
289 String response = Resources.toString(url, Charsets.UTF_8);
291 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
292 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
294 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
296 verify(postRequestedFor(urlEqualTo(expectedUrl))
297 .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
298 .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
299 .withHeader(AUTHORIZATION, equalTo("Token " + token)));
301 Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
302 Assert.assertEquals(QueryStatus.SUCCESS, status);
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));