f1eda736ad7047f8fddde5d334f5f23540546245
[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.ok;
24 import static com.github.tomakehurst.wiremock.client.WireMock.post;
25 import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
26 import static com.github.tomakehurst.wiremock.client.WireMock.serverError;
27 import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
28 import static com.github.tomakehurst.wiremock.client.WireMock.verify;
29 import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
30 import static org.apache.http.HttpHeaders.ACCEPT;
31 import static org.apache.http.HttpHeaders.AUTHORIZATION;
32 import static org.apache.http.HttpHeaders.CONTENT_TYPE;
33 import static org.mockito.ArgumentMatchers.any;
34 import static org.mockito.ArgumentMatchers.anyString;
35 import static org.mockito.ArgumentMatchers.eq;
36 import static org.mockito.Mockito.doReturn;
37 import static org.mockito.Mockito.mock;
38
39 import com.github.tomakehurst.wiremock.junit.WireMockRule;
40 import com.google.common.base.Charsets;
41 import com.google.common.io.Resources;
42 import java.io.ByteArrayInputStream;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.net.URL;
46 import java.nio.charset.StandardCharsets;
47 import java.sql.SQLException;
48 import java.util.ArrayList;
49 import java.util.UUID;
50 import org.apache.http.HttpEntity;
51 import org.apache.http.HttpResponse;
52 import org.apache.http.StatusLine;
53 import org.junit.After;
54 import org.junit.Assert;
55 import org.junit.Before;
56 import org.junit.Rule;
57 import org.junit.Test;
58 import org.junit.runner.RunWith;
59 import org.mockito.Mock;
60 import org.mockito.Mockito;
61 import org.mockito.runners.MockitoJUnitRunner;
62 import org.onap.ccsdk.sli.adaptors.netbox.api.IpamException;
63 import org.onap.ccsdk.sli.adaptors.netbox.model.IPAddress;
64 import org.onap.ccsdk.sli.adaptors.netbox.model.Prefix;
65 import org.onap.ccsdk.sli.adaptors.netbox.model.Status.Values;
66 import org.onap.ccsdk.sli.core.dblib.DbLibService;
67
68 @RunWith(MockitoJUnitRunner.class)
69 public class NetboxClientImplTest {
70
71     private static final String APPLICATION_JSON = "application/json";
72
73     @Rule
74     public WireMockRule wm = new WireMockRule(wireMockConfig().dynamicPort());
75
76     @Mock
77     private DbLibService dbLib;
78
79     private String token = "token";
80     private String serviceInstanceId = UUID.randomUUID().toString();
81     private String vfModuleId = UUID.randomUUID().toString();
82
83     private NetboxHttpClient httpClient;
84     private NetboxClientImpl netboxClient;
85
86     @Before
87     public void setup() {
88         String baseUrl = "http://localhost:" + wm.port();
89
90         httpClient = new NetboxHttpClient(baseUrl, token);
91         httpClient.init();
92
93         netboxClient = new NetboxClientImpl(httpClient, dbLib);
94
95         wm.addMockServiceRequestListener(
96             (request, response) -> {
97                 System.out.println("Request URL :" + request.getAbsoluteUrl());
98                 System.out.println("Request body :" + request.getBodyAsString());
99                 System.out.println("Response status :" + response.getStatus());
100                 System.out.println("Response body :" + response.getBodyAsString());
101             });
102     }
103
104     @After
105     public void tearDown() throws IOException {
106         httpClient.close();
107     }
108
109     @Test
110     public void nextAvailableIpInPrefixTestNoId() throws SQLException {
111         Prefix prefix = mock(Prefix.class);
112         doReturn(null).when(prefix).getId();
113         try {
114             netboxClient.assign(prefix, serviceInstanceId, vfModuleId);
115         } catch (IpamException e) {
116             Assert.assertEquals("Id must be set", e.getMessage());
117             return;
118         }
119         Assert.fail();
120     }
121
122     @Test
123     public void nextAvailableIpInPrefixTest() throws IOException, IpamException, SQLException {
124         Integer id = 3;
125         Prefix prefix = mock(Prefix.class);
126         doReturn(id).when(prefix).getId();
127
128         URL url = Resources.getResource("nextAvailableIpResponse.json");
129         String response = Resources.toString(url, Charsets.UTF_8);
130
131         String expectedUrl = "/api/ipam/prefixes/" + id + "/available-ips/";
132         givenThat(post(urlEqualTo(expectedUrl)).willReturn(created().withBody(response)));
133
134         netboxClient.assign(prefix, serviceInstanceId, vfModuleId);
135
136         verify(postRequestedFor(urlEqualTo(expectedUrl))
137             .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
138             .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
139             .withHeader(AUTHORIZATION, equalTo("Token " + token)));
140         Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq((null)));
141     }
142
143     @Test
144     public void deleteIpTestError500() throws SQLException {
145         Integer id = 3;
146         IPAddress ipAddress = mock(IPAddress.class);
147         doReturn(id).when(ipAddress).getId();
148
149         String expectedUrl = "/api/ipam/ip-addresses/" + id + "/";
150         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(serverError()));
151         try {
152             netboxClient.unassign(ipAddress, serviceInstanceId, vfModuleId);
153         } catch (IpamException e) {
154             Assert.assertEquals(IllegalStateException.class, e.getCause().getClass());
155             Assert.assertTrue(e.getMessage().contains(
156                 "Fail to unassign IP for IPAddress(id= 3). java.lang.IllegalStateException: Netbox request failed with status: HTTP/1.1 500 Server Error"));
157             return;
158         }
159         Assert.fail();
160     }
161
162     @Test
163     public void deleteIpTest() throws IpamException, SQLException {
164         Integer id = 3;
165         IPAddress ipAddress = mock(IPAddress.class);
166         doReturn(id).when(ipAddress).getId();
167
168         String expectedUrl = "/api/ipam/ip-addresses/" + id + "/";
169         givenThat(delete(urlEqualTo(expectedUrl)).willReturn(ok()));
170         netboxClient.unassign(ipAddress, serviceInstanceId, vfModuleId);
171         verify(deleteRequestedFor(urlEqualTo(expectedUrl))
172             .withHeader(ACCEPT, equalTo(APPLICATION_JSON))
173             .withHeader(CONTENT_TYPE, equalTo(APPLICATION_JSON))
174             .withHeader(AUTHORIZATION, equalTo("Token " + token)));
175         Mockito.verify(dbLib).writeData(anyString(), any(ArrayList.class), eq((null)));
176     }
177
178
179     @Test
180     public void getIpAddressTest() throws IOException {
181         StatusLine statusLine = mock(StatusLine.class);
182         doReturn(201).when(statusLine).getStatusCode();
183
184         URL url = Resources.getResource("nextAvailableIpResponse.json");
185         String response = Resources.toString(url, Charsets.UTF_8);
186         InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));
187
188         HttpEntity entity = mock(HttpEntity.class);
189         doReturn(stream).when(entity).getContent();
190
191         HttpResponse httpResponse = mock(HttpResponse.class);
192         doReturn(statusLine).when(httpResponse).getStatusLine();
193         doReturn(entity).when(httpResponse).getEntity();
194
195         IPAddress ipAddress = netboxClient.getIpAddress(httpResponse);
196
197         Assert.assertEquals("192.168.20.7/32", ipAddress.getAddress());
198         Assert.assertEquals(Integer.valueOf(8), ipAddress.getId());
199         Assert.assertEquals(Values.ACTIVE, ipAddress.getStatus());
200     }
201 }