Added support for external_key and resource_name
[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(crs).when(dbLib).getData(anyString(), any(ArrayList.class), eq(null));
151
152         QueryStatus status = netboxClientMock
153             .unassignIpAddress(params, svcLogicContext);
154
155         Assert.assertEquals(QueryStatus.FAILURE, status);
156         verifyLogEntry("Fail to unassign IP for IPAddress(id= 3). Failed request");
157     }
158
159     @Test
160     public void unassignIpAddressServerError() throws SQLException {
161
162         String expectedUrl = "/api/ipam/ip-addresses/3/";
163         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(serverError()));
164
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));
168
169         QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
170
171         Assert.assertEquals(QueryStatus.FAILURE, status);
172         verifyLogEntry("Fail to unassign IP for IPAddress(id=3). HTTP code=500.");
173     }
174
175     @Test
176     public void unassignIpAddressFailSQL() throws IOException, SQLException {
177
178         String response = "{}";
179
180         String expectedUrl = "/api/ipam/ip-addresses/3/";
181         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
182
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));
186
187         doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
188
189         QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
190
191         Assert.assertEquals(QueryStatus.FAILURE, status);
192         verifyLogEntry("Caught SQL exception");
193     }
194
195     @Test
196     public void unassignIpAddressSuccess() throws IOException, SQLException {
197         String response = "{}";
198
199         String expectedUrl = "/api/ipam/ip-addresses/3/";
200         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
201
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));
205
206         QueryStatus status = netboxClient.unassignIpAddress(params, svcLogicContext);
207
208         verify(deleteRequestedFor(urlEqualTo(expectedUrl))
209             .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
210             .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
211             .withHeader(AUTHORIZATION, equalTo("Token " + token)));
212
213         Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
214         Assert.assertEquals(QueryStatus.SUCCESS, status);
215     }
216
217
218     @Test
219     public void nextAvailableIpInPrefixTestNoId() {
220         QueryStatus status = netboxClient.assignIpAddress(ImmutableMap.of(), svcLogicContext);
221         Assert.assertEquals(QueryStatus.FAILURE, status);
222         verifyLogEntry(
223             "This method requires the parameters [service_instance_id,vf_module_id,prefix_id,resource_name,external_key], but no parameters were passed in.");
224     }
225
226     @Test
227     public void nextAvailableIpInPrefixFailedRequest() throws IOException {
228         doThrow(new IOException("Failed request")).when(httpClientMock).post(anyString(), anyString());
229         QueryStatus status = netboxClientMock.assignIpAddress(params, svcLogicContext);
230
231         Assert.assertEquals(QueryStatus.FAILURE, status);
232         verifyLogEntry("Fail to assign IP for Prefix(id=3). Failed request");
233     }
234
235     @Test
236     public void nextAvailableIpInPrefixBadRespPayload() throws IOException {
237         URL url = Resources.getResource("badResponse.json");
238         String response = Resources.toString(url, Charsets.UTF_8);
239
240         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
241         givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
242
243         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
244
245         Assert.assertEquals(QueryStatus.FAILURE, status);
246         verifyLogEntry("Fail to parse IPAM JSON reponse to IPAddress POJO. IPAM JSON Response={\n"
247             + "  \"id\": 8\n"
248             + "  \"address\": \"192.168.20.7/32\"\n"
249             + "}");
250     }
251
252     @Test
253     public void nextAvailableIpInPrefixFailSQL() throws IOException, SQLException {
254         URL url = Resources.getResource("nextAvailableIpResponse.json");
255         String response = Resources.toString(url, Charsets.UTF_8);
256
257         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
258         givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
259
260         doThrow(new SQLException("Failed")).when(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
261
262         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
263
264         Assert.assertEquals(QueryStatus.FAILURE, status);
265         verifyLogEntry("Caught SQL exception");
266     }
267
268     @Test
269     public void nextAvailableIpInPrefixError500() throws IOException {
270         URL url = Resources.getResource("nextAvailableIpResponse.json");
271         String response = Resources.toString(url, Charsets.UTF_8);
272
273         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
274         givenThat(post(urlEqualTo(expectedUrl)).willReturn(serverError().withBody(response)));
275
276         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
277
278         Assert.assertEquals(QueryStatus.FAILURE, status);
279         verifyLogEntry("Fail to assign IP for Prefix(id=3). HTTP code 201!=500.");
280     }
281
282     @Test
283     public void nextAvailableIpInPrefixSuccess() throws IOException, SQLException {
284         URL url = Resources.getResource("nextAvailableIpResponse.json");
285         String response = Resources.toString(url, Charsets.UTF_8);
286
287         String expectedUrl = "/api/ipam/prefixes/3/available-ips/";
288         givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
289
290         QueryStatus status = netboxClient.assignIpAddress(params, svcLogicContext);
291
292         verify(postRequestedFor(urlEqualTo(expectedUrl))
293             .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
294             .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
295             .withHeader(AUTHORIZATION, equalTo("Token " + token)));
296
297         Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq(null));
298         Assert.assertEquals(QueryStatus.SUCCESS, status);
299     }
300
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));
306         }
307     }
308
309 }