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.doThrow;
36 import static org.mockito.Mockito.times;
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;
46 import java.sql.SQLException;
47 import java.util.ArrayList;
48 import java.util.List;
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;
67 @RunWith(MockitoJUnitRunner.class)
68 public class NetboxClientImplTest {
70 private static final String APPLICATION_JSON = "application/json";
73 public WireMockRule wm = new WireMockRule(wireMockConfig().dynamicPort());
75 private DbLibService dbLib;
77 private SvcLogicContext svcLogicContext;
79 private Appender<ILoggingEvent> appender;
81 private ArgumentCaptor<ILoggingEvent> captor;
84 private String token = "token";
85 private String serviceInstanceId = UUID.randomUUID().toString();
86 private String vfModuleId = UUID.randomUUID().toString();
88 private Map<String, String> params = ImmutableMap
89 .of("service_instance_id", serviceInstanceId,
90 "vf_module_id", vfModuleId,
95 private NetboxHttpClient httpClient;
96 private NetboxClientImpl netboxClient;
99 private NetboxHttpClient httpClientMock;
101 private NetboxClientImpl netboxClientMock;
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);
110 String baseUrl = "http://localhost:" + wm.port();
112 httpClient = new NetboxHttpClient(baseUrl, token);
114 netboxClient = new NetboxClientImpl(httpClient, dbLib);
116 netboxClientMock = new NetboxClientImpl(httpClientMock, dbLib);
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());
128 public void tearDown() throws IOException {
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");
140 public void unassignIpAddressFailedRequest() throws IOException {
141 doThrow(new IOException("Failed request")).when(httpClientMock).delete(anyString());
142 QueryStatus status = netboxClientMock
143 .unassignIpAddress(params, svcLogicContext);
145 Assert.assertEquals(QueryStatus.FAILURE, status);
146 verifyLogEntry("Fail to unassign IP for IPAddress(id= 3). Failed request");
150 public void unassignIpAddressServerError() {
152 String expectedUrl = "/api/ipam/ip-addresses/3/";
153 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(serverError()));
155 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
157 Assert.assertEquals(QueryStatus.FAILURE, status);
158 verifyLogEntry("Fail to unassign IP for IPAddress(id=3). HTTP code=500.");
162 public void unassignIpAddressFailSQL() throws IOException, SQLException {
164 String response = "{}";
166 String expectedUrl = "/api/ipam/ip-addresses/3/";
167 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
169 doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
171 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
173 Assert.assertEquals(QueryStatus.FAILURE, status);
174 verifyLogEntry("Caught SQL exception");
178 public void unassignIpAddressSuccess() throws IOException, SQLException {
179 String response = "{}";
181 String expectedUrl = "/api/ipam/ip-addresses/3/";
182 givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
184 QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
186 verify(deleteRequestedFor(urlEqualTo(expectedUrl))
187 .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
188 .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
189 .withHeader(AUTHORIZATION, equalTo("Token " + token)));
191 Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
192 Assert.assertEquals(QueryStatus.SUCCESS, status);
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");
204 public void nextAvailableIpInPrefixFailedRequest() throws IOException {
205 doThrow(new IOException("Failed request")).when(httpClientMock).post(anyString(), anyString());
206 QueryStatus status = netboxClientMock.assignIpAddress(params, svcLogicContext);
208 Assert.assertEquals(QueryStatus.FAILURE, status);
209 verifyLogEntry("Fail to assign IP for Prefix(id=3). Failed request");
213 public void nextAvailableIpInPrefixBadRespPayload() throws IOException {
214 URL url = Resources.getResource("badResponse.json");
215 String response = Resources.toString(url, Charsets.UTF_8);
217 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
218 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
220 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
222 Assert.assertEquals(QueryStatus.FAILURE, status);
223 verifyLogEntry("Fail to parse IPAM JSON reponse to IPAddress POJO. IPAM JSON Response={\n"
225 + " \"address\": \"192.168.20.7/32\"\n"
230 public void nextAvailableIpInPrefixFailSQL() throws IOException, SQLException {
231 URL url = Resources.getResource("nextAvailableIpResponse.json");
232 String response = Resources.toString(url, Charsets.UTF_8);
234 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
235 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
237 doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
239 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
241 Assert.assertEquals(QueryStatus.FAILURE, status);
242 verifyLogEntry("Caught SQL exception");
246 public void nextAvailableIpInPrefixError500() throws IOException {
247 URL url = Resources.getResource("nextAvailableIpResponse.json");
248 String response = Resources.toString(url, Charsets.UTF_8);
250 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
251 givenThat(post(urlEqualTo(expectedUrl)).willReturn(serverError().withBody(response)));
253 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
255 Assert.assertEquals(QueryStatus.FAILURE, status);
256 verifyLogEntry("Fail to assign IP for Prefix(id=3). HTTP code 201!=500.");
260 public void nextAvailableIpInPrefixSuccess() throws IOException, SQLException {
261 URL url = Resources.getResource("nextAvailableIpResponse.json");
262 String response = Resources.toString(url, Charsets.UTF_8);
264 String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
265 givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
267 QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
269 verify(postRequestedFor(urlEqualTo(expectedUrl))
270 .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
271 .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
272 .withHeader(AUTHORIZATION, equalTo("Token " + token)));
274 Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
275 Assert.assertEquals(QueryStatus.SUCCESS, status);
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));