blob: 4d4c933dde2c3550ed7891342058e6200f5b8ae1 [file] [log] [blame]
Jian Liecb3c0f2015-12-15 10:07:49 -08001/*
2 * Copyright 2014-2015 Open Networking Laboratory
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
17package org.onosproject.rest;
18
Jian Li80cfe452016-01-14 16:04:58 -080019import com.eclipsesource.json.Json;
Jian Liecb3c0f2015-12-15 10:07:49 -080020import com.eclipsesource.json.JsonArray;
21import com.eclipsesource.json.JsonObject;
22import com.google.common.collect.ImmutableSet;
23import com.sun.jersey.api.client.ClientResponse;
24import com.sun.jersey.api.client.WebResource;
25import org.hamcrest.Description;
26import org.hamcrest.TypeSafeMatcher;
27import org.junit.After;
28import org.junit.Before;
29import org.junit.Test;
30import org.onlab.osgi.ServiceDirectory;
31import org.onlab.osgi.TestServiceDirectory;
32import org.onlab.rest.BaseResource;
33import org.onosproject.codec.CodecService;
34import org.onosproject.codec.impl.CodecManager;
35import org.onosproject.codec.impl.GroupCodec;
36import org.onosproject.core.ApplicationId;
37import org.onosproject.core.CoreService;
38import org.onosproject.core.DefaultApplicationId;
39import org.onosproject.core.DefaultGroupId;
40import org.onosproject.core.GroupId;
41import org.onosproject.net.DefaultDevice;
42import org.onosproject.net.Device;
43import org.onosproject.net.DeviceId;
44import org.onosproject.net.NetTestTools;
45import org.onosproject.net.device.DeviceService;
46import org.onosproject.net.group.DefaultGroupKey;
47import org.onosproject.net.group.Group;
48import org.onosproject.net.group.GroupBucket;
49import org.onosproject.net.group.GroupBuckets;
50import org.onosproject.net.group.GroupDescription;
51import org.onosproject.net.group.GroupKey;
52import org.onosproject.net.group.GroupService;
Jian Lia7f86ce2015-12-20 13:42:10 -080053import org.onosproject.rest.resources.CoreWebApplication;
Jian Liecb3c0f2015-12-15 10:07:49 -080054
55import javax.ws.rs.core.MediaType;
56import java.io.InputStream;
57import java.net.HttpURLConnection;
58import java.util.ArrayList;
59import java.util.HashMap;
60import java.util.HashSet;
61import java.util.List;
62import java.util.Set;
63
64import static org.easymock.EasyMock.anyObject;
65import static org.easymock.EasyMock.anyShort;
66import static org.easymock.EasyMock.createMock;
67import static org.easymock.EasyMock.expect;
68import static org.easymock.EasyMock.expectLastCall;
69import static org.easymock.EasyMock.replay;
70import static org.easymock.EasyMock.verify;
71import static org.hamcrest.Matchers.hasSize;
72import static org.hamcrest.Matchers.is;
73import static org.hamcrest.Matchers.notNullValue;
74import static org.junit.Assert.assertThat;
Jian Lia7f86ce2015-12-20 13:42:10 -080075import static org.junit.Assert.assertEquals;
Jian Liecb3c0f2015-12-15 10:07:49 -080076import static org.onosproject.net.NetTestTools.APP_ID;
77
78/**
79 * Unit tests for Groups REST APIs.
80 */
81public class GroupsResourceTest extends ResourceTest {
82 final GroupService mockGroupService = createMock(GroupService.class);
83 CoreService mockCoreService = createMock(CoreService.class);
84 final DeviceService mockDeviceService = createMock(DeviceService.class);
85
86 final HashMap<DeviceId, Set<Group>> groups = new HashMap<>();
87
88
89 final DeviceId deviceId1 = DeviceId.deviceId("1");
90 final DeviceId deviceId2 = DeviceId.deviceId("2");
91 final DeviceId deviceId3 = DeviceId.deviceId("3");
92 final Device device1 = new DefaultDevice(null, deviceId1, Device.Type.OTHER,
93 "", "", "", "", null);
94 final Device device2 = new DefaultDevice(null, deviceId2, Device.Type.OTHER,
95 "", "", "", "", null);
96
97 final MockGroup group1 = new MockGroup(deviceId1, 1, "111", 1);
98 final MockGroup group2 = new MockGroup(deviceId1, 2, "222", 2);
99
100 final MockGroup group3 = new MockGroup(deviceId2, 3, "333", 3);
101 final MockGroup group4 = new MockGroup(deviceId2, 4, "444", 4);
102
103 final MockGroup group5 = new MockGroup(deviceId3, 5, "555", 5);
104 final MockGroup group6 = new MockGroup(deviceId3, 6, "666", 6);
105
Jian Lia7f86ce2015-12-20 13:42:10 -0800106 public GroupsResourceTest() {
107 super(CoreWebApplication.class);
108 }
109
Jian Liecb3c0f2015-12-15 10:07:49 -0800110 /**
111 * Mock class for a group.
112 */
113 private static class MockGroup implements Group {
114
115 final DeviceId deviceId;
116 final ApplicationId appId;
117 final GroupKey appCookie;
118 final long baseValue;
119 final List<GroupBucket> bucketList;
120 GroupBuckets buckets;
121
122 public MockGroup(DeviceId deviceId, int appId, String appCookie, int id) {
123 this.deviceId = deviceId;
124 this.appId = new DefaultApplicationId(appId, String.valueOf(appId));
125 this.appCookie = new DefaultGroupKey(appCookie.getBytes());
126 this.baseValue = id * 100;
127 this.bucketList = new ArrayList<>();
128 this.buckets = new GroupBuckets(bucketList);
129 }
130
131 @Override
132 public GroupId id() {
133 return new DefaultGroupId((int) baseValue + 55);
134 }
135
136 @Override
137 public GroupState state() {
138 return GroupState.ADDED;
139 }
140
141 @Override
142 public long life() {
143 return baseValue + 11;
144 }
145
146 @Override
147 public long packets() {
148 return baseValue + 22;
149 }
150
151 @Override
152 public long bytes() {
153 return baseValue + 33;
154 }
155
156 @Override
157 public long referenceCount() {
158 return baseValue + 44;
159 }
160
161 @Override
162 public Type type() {
163 return GroupDescription.Type.ALL;
164 }
165
166 @Override
167 public DeviceId deviceId() {
168 return this.deviceId;
169 }
170
171 @Override
172 public ApplicationId appId() {
173 return this.appId;
174 }
175
176 @Override
177 public GroupKey appCookie() {
178 return this.appCookie;
179 }
180
181 @Override
182 public Integer givenGroupId() {
183 return (int) baseValue + 55;
184 }
185
186 @Override
187 public GroupBuckets buckets() {
188 return this.buckets;
189 }
190 }
191
192 /**
193 * Populates some groups used as testing data.
194 */
195 private void setupMockGroups() {
196 final Set<Group> groups1 = new HashSet<>();
197 groups1.add(group1);
198 groups1.add(group2);
199
200 final Set<Group> groups2 = new HashSet<>();
201 groups2.add(group3);
202 groups2.add(group4);
203
204 groups.put(deviceId1, groups1);
205 groups.put(deviceId2, groups2);
206
207 expect(mockGroupService.getGroups(deviceId1))
208 .andReturn(groups.get(deviceId1)).anyTimes();
209 expect(mockGroupService.getGroups(deviceId2))
210 .andReturn(groups.get(deviceId2)).anyTimes();
211 }
212
213 /**
214 * Sets up the global values for all the tests.
215 */
216 @Before
217 public void setUpTest() {
218 // Mock device service
219 expect(mockDeviceService.getDevice(deviceId1))
220 .andReturn(device1);
221 expect(mockDeviceService.getDevice(deviceId2))
222 .andReturn(device2);
223 expect(mockDeviceService.getDevices())
224 .andReturn(ImmutableSet.of(device1, device2));
225
226 // Mock Core Service
227 expect(mockCoreService.getAppId(anyShort()))
228 .andReturn(NetTestTools.APP_ID).anyTimes();
229 expect(mockCoreService.registerApplication(GroupCodec.REST_APP_ID))
230 .andReturn(APP_ID).anyTimes();
231 replay(mockCoreService);
232
233 // Register the services needed for the test
234 final CodecManager codecService = new CodecManager();
235 codecService.activate();
236 ServiceDirectory testDirectory =
237 new TestServiceDirectory()
238 .add(GroupService.class, mockGroupService)
239 .add(DeviceService.class, mockDeviceService)
240 .add(CodecService.class, codecService)
241 .add(CoreService.class, mockCoreService);
242
243 BaseResource.setServiceDirectory(testDirectory);
244 }
245
246 /**
247 * Cleans up and verifies the mocks.
248 */
249 @After
250 public void tearDownTest() {
251 verify(mockGroupService);
252 verify(mockCoreService);
253 }
254
255 /**
256 * Hamcrest matcher to check that a group representation in JSON matches
257 * the actual group.
258 */
259 public static class GroupJsonMatcher extends TypeSafeMatcher<JsonObject> {
260 private final Group group;
261 private final String expectedAppId;
262 private String reason = "";
263
264 public GroupJsonMatcher(Group groupValue, String expectedAppIdValue) {
265 group = groupValue;
266 expectedAppId = expectedAppIdValue;
267 }
268
269 @Override
270 public boolean matchesSafely(JsonObject jsonGroup) {
271 // check id
272 final String jsonId = jsonGroup.get("id").asString();
273 final String groupId = group.id().toString();
274 if (!jsonId.equals(groupId)) {
275 reason = "id " + group.id().toString();
276 return false;
277 }
278
279 // check application id
280 final String jsonAppId = jsonGroup.get("appId").asString();
281 final String appId = group.appId().toString();
282 if (!jsonAppId.equals(appId)) {
283 reason = "appId " + group.appId().toString();
284 return false;
285 }
286
287 // check device id
288 final String jsonDeviceId = jsonGroup.get("deviceId").asString();
289 if (!jsonDeviceId.equals(group.deviceId().toString())) {
290 reason = "deviceId " + group.deviceId();
291 return false;
292 }
293
294 // check bucket array
295 if (group.buckets().buckets() != null) {
296 final JsonArray jsonBuckets = jsonGroup.get("buckets").asArray();
297 if (group.buckets().buckets().size() != jsonBuckets.size()) {
298 reason = "buckets array size of " +
299 Integer.toString(group.buckets().buckets().size());
300 return false;
301 }
302 for (final GroupBucket groupBucket : group.buckets().buckets()) {
303 boolean groupBucketFound = false;
304 for (int groupBucketIndex = 0; groupBucketIndex < jsonBuckets.size(); groupBucketIndex++) {
305 final String jsonType = jsonBuckets.get(groupBucketIndex).asObject().get("type").asString();
306 final String bucketType = groupBucket.type().name();
307 if (jsonType.equals(bucketType)) {
308 groupBucketFound = true;
309 }
310 }
311 if (!groupBucketFound) {
312 reason = "group bucket " + groupBucket.toString();
313 return false;
314 }
315 }
316 }
317
318 return true;
319 }
320
321 @Override
322 public void describeTo(Description description) {
323 description.appendText(reason);
324 }
325 }
326
327 /**
328 * Factory to allocate a group matcher.
329 *
330 * @param group group object we are looking for
331 * @return matcher
332 */
333 private static GroupJsonMatcher matchesGroup(Group group, String expectedAppName) {
334 return new GroupJsonMatcher(group, expectedAppName);
335 }
336
337 /**
338 * Hamcrest matcher to check that a group is represented properly in a JSON
339 * array of flows.
340 */
341 public static class GroupJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
342 private final Group group;
343 private String reason = "";
344
345 public GroupJsonArrayMatcher(Group groupValue) {
346 group = groupValue;
347 }
348
349 @Override
350 public boolean matchesSafely(JsonArray json) {
351 boolean groupFound = false;
352 for (int jsonGroupIndex = 0; jsonGroupIndex < json.size();
353 jsonGroupIndex++) {
354
355 final JsonObject jsonGroup = json.get(jsonGroupIndex).asObject();
356
357 final String groupId = group.id().toString();
358 final String jsonGroupId = jsonGroup.get("id").asString();
359 if (jsonGroupId.equals(groupId)) {
360 groupFound = true;
361
362 // We found the correct group, check attribute values
363 assertThat(jsonGroup, matchesGroup(group, APP_ID.name()));
364 }
365 }
366 if (!groupFound) {
367 reason = "Group with id " + group.id().toString() + " not found";
368 return false;
369 } else {
370 return true;
371 }
372 }
373
374 @Override
375 public void describeTo(Description description) {
376 description.appendText(reason);
377 }
378 }
379
380 /**
381 * Factory to allocate a group array matcher.
382 *
383 * @param group group object we are looking for
384 * @return matcher
385 */
386 private static GroupJsonArrayMatcher hasGroup(Group group) {
387 return new GroupJsonArrayMatcher(group);
388 }
389
390 /**
391 * Tests the result of the rest api GET when there are no groups.
392 */
393 @Test
394 public void testGroupsEmptyArray() {
395 expect(mockGroupService.getGroups(deviceId1)).andReturn(null).anyTimes();
396 expect(mockGroupService.getGroups(deviceId2)).andReturn(null).anyTimes();
397 replay(mockGroupService);
398 replay(mockDeviceService);
399 final WebResource rs = resource();
400 final String response = rs.path("groups").get(String.class);
401 assertThat(response, is("{\"groups\":[]}"));
402 }
403
404 /**
405 * Tests the result of the rest api GET when there are active groups.
406 */
407 @Test
408 public void testGroupsPopulatedArray() {
409 setupMockGroups();
410 replay(mockGroupService);
411 replay(mockDeviceService);
412 final WebResource rs = resource();
413 final String response = rs.path("groups").get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800414 final JsonObject result = Json.parse(response).asObject();
Jian Liecb3c0f2015-12-15 10:07:49 -0800415 assertThat(result, notNullValue());
416
417 assertThat(result.names(), hasSize(1));
418 assertThat(result.names().get(0), is("groups"));
419 final JsonArray jsonGroups = result.get("groups").asArray();
420 assertThat(jsonGroups, notNullValue());
421 assertThat(jsonGroups, hasGroup(group1));
422 assertThat(jsonGroups, hasGroup(group2));
423 assertThat(jsonGroups, hasGroup(group3));
424 assertThat(jsonGroups, hasGroup(group4));
425 }
426
427 /**
428 * Tests the result of a rest api GET for a device.
429 */
430 @Test
431 public void testGroupsSingleDevice() {
432 setupMockGroups();
433 final Set<Group> groups = new HashSet<>();
434 groups.add(group5);
435 groups.add(group6);
436 expect(mockGroupService.getGroups(anyObject()))
437 .andReturn(groups).anyTimes();
438 replay(mockGroupService);
439 replay(mockDeviceService);
440 final WebResource rs = resource();
441 final String response = rs.path("groups/" + deviceId3).get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800442 final JsonObject result = Json.parse(response).asObject();
Jian Liecb3c0f2015-12-15 10:07:49 -0800443 assertThat(result, notNullValue());
444
445 assertThat(result.names(), hasSize(1));
446 assertThat(result.names().get(0), is("groups"));
Jian Li2e02fab2016-02-25 15:45:59 +0900447 final JsonArray jsonGroups = result.get("groups").asArray();
448 assertThat(jsonGroups, notNullValue());
449 assertThat(jsonGroups, hasGroup(group5));
450 assertThat(jsonGroups, hasGroup(group6));
Jian Liecb3c0f2015-12-15 10:07:49 -0800451 }
452
453 /**
Jian Lia7f86ce2015-12-20 13:42:10 -0800454 * Test the result of a rest api GET with specifying device id and appcookie.
455 */
456 @Test
457 public void testGroupByDeviceIdAndAppCookie() {
458 setupMockGroups();
459 expect(mockGroupService.getGroup(anyObject(), anyObject()))
460 .andReturn(group5).anyTimes();
461 replay(mockGroupService);
462 final WebResource rs = resource();
463 final String response = rs.path("groups/" + deviceId3 + "/" + "111").get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800464 final JsonObject result = Json.parse(response).asObject();
Jian Lia7f86ce2015-12-20 13:42:10 -0800465 assertThat(result, notNullValue());
466
467 assertThat(result.names(), hasSize(1));
468 assertThat(result.names().get(0), is("groups"));
469 final JsonArray jsonFlows = result.get("groups").asArray();
470 assertThat(jsonFlows, notNullValue());
471 assertThat(jsonFlows, hasGroup(group5));
472 }
473
474 /**
475 * Test whether the REST API returns 404 if no entry has been found.
476 */
477 @Test
478 public void testGroupByDeviceIdAndAppCookieNull() {
479 setupMockGroups();
480 expect(mockGroupService.getGroup(anyObject(), anyObject()))
481 .andReturn(null).anyTimes();
482 replay(mockGroupService);
483 final WebResource rs = resource();
484 final ClientResponse response = rs.path("groups/" + deviceId3 + "/" + "222").get(ClientResponse.class);
485
486 assertEquals(404, response.getStatus());
487 }
488
489 /**
Jian Liecb3c0f2015-12-15 10:07:49 -0800490 * Tests creating a group with POST.
491 */
492 @Test
493 public void testPost() {
494 mockGroupService.addGroup(anyObject());
495 expectLastCall();
496 replay(mockGroupService);
497
498 WebResource rs = resource();
499 InputStream jsonStream = GroupsResourceTest.class
500 .getResourceAsStream("post-group.json");
501
502 ClientResponse response = rs.path("groups/of:0000000000000001")
503 .type(MediaType.APPLICATION_JSON_TYPE)
504 .post(ClientResponse.class, jsonStream);
505 assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
506 }
507
508 /**
509 * Tests deleting a group.
510 */
511 @Test
512 public void testDelete() {
513 setupMockGroups();
514 mockGroupService.removeGroup(anyObject(), anyObject(), anyObject());
515 expectLastCall();
516 replay(mockGroupService);
517
518 WebResource rs = resource();
519
520 String location = "/groups/1/111";
521
522 ClientResponse deleteResponse = rs.path(location)
523 .type(MediaType.APPLICATION_JSON_TYPE)
524 .delete(ClientResponse.class);
525 assertThat(deleteResponse.getStatus(),
526 is(HttpURLConnection.HTTP_NO_CONTENT));
527 }
528}