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