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