blob: 72e9a00e3bf5d51806bab5ab6828025116b4a2b5 [file] [log] [blame]
Ray Milkey4f5de002014-12-17 19:26:11 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
Ray Milkey4f5de002014-12-17 19:26:11 -08003 *
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 */
Jian Li8ae91202016-03-24 14:36:16 -070016package org.onosproject.rest.resources;
Ray Milkey4f5de002014-12-17 19:26:11 -080017
Ray Milkey094a1352018-01-22 14:03:54 -080018import com.eclipsesource.json.Json;
19import com.eclipsesource.json.JsonArray;
20import com.eclipsesource.json.JsonObject;
21import com.google.common.collect.ImmutableSet;
Ray Milkey4f5de002014-12-17 19:26:11 -080022import org.hamcrest.Description;
Ray Milkeyeb5c7172015-06-23 14:59:27 -070023import org.hamcrest.Matchers;
Ray Milkey4f5de002014-12-17 19:26:11 -080024import org.hamcrest.TypeSafeMatcher;
25import org.junit.After;
26import org.junit.Before;
27import org.junit.Test;
28import org.onlab.osgi.ServiceDirectory;
29import org.onlab.osgi.TestServiceDirectory;
30import org.onlab.packet.MacAddress;
Jian Li2907ad22016-05-12 23:08:54 -070031import org.onosproject.app.ApplicationService;
Ray Milkey4f5de002014-12-17 19:26:11 -080032import org.onosproject.codec.CodecService;
33import org.onosproject.codec.impl.CodecManager;
Jonathan Hart9b80da82016-11-10 21:46:15 +000034import org.onosproject.codec.impl.FlowRuleCodec;
Ray Milkeyd43fe452015-05-29 09:35:12 -070035import org.onosproject.core.CoreService;
Ray Milkey4f5de002014-12-17 19:26:11 -080036import org.onosproject.core.GroupId;
37import org.onosproject.net.DefaultDevice;
38import org.onosproject.net.Device;
39import org.onosproject.net.DeviceId;
Ray Milkeyd43fe452015-05-29 09:35:12 -070040import org.onosproject.net.NetTestTools;
Ray Milkey4f5de002014-12-17 19:26:11 -080041import org.onosproject.net.device.DeviceService;
42import org.onosproject.net.flow.DefaultTrafficSelector;
43import org.onosproject.net.flow.DefaultTrafficTreatment;
44import org.onosproject.net.flow.FlowEntry;
Ray Milkey634eb172017-04-05 14:48:50 -070045import org.onosproject.net.flow.FlowEntryAdapter;
Ray Milkey4f5de002014-12-17 19:26:11 -080046import org.onosproject.net.flow.FlowId;
Jonathan Hartf44e42c2015-08-04 09:58:46 -070047import org.onosproject.net.flow.FlowRule;
Ray Milkey4f5de002014-12-17 19:26:11 -080048import org.onosproject.net.flow.FlowRuleService;
49import org.onosproject.net.flow.TrafficSelector;
50import org.onosproject.net.flow.TrafficTreatment;
51import org.onosproject.net.flow.criteria.Criterion;
52import org.onosproject.net.flow.instructions.Instruction;
jcc3d4e14a2015-04-21 11:32:05 +080053
Ray Milkey094a1352018-01-22 14:03:54 -080054import javax.ws.rs.NotFoundException;
55import javax.ws.rs.client.Entity;
56import javax.ws.rs.client.WebTarget;
57import javax.ws.rs.core.MediaType;
58import javax.ws.rs.core.Response;
59import java.io.InputStream;
60import java.net.HttpURLConnection;
61import java.util.HashMap;
62import java.util.HashSet;
63import java.util.Set;
64import java.util.concurrent.TimeUnit;
Ray Milkey4f5de002014-12-17 19:26:11 -080065
Thiago Santos877914d2016-07-20 18:29:29 -030066import static java.util.concurrent.TimeUnit.SECONDS;
Ray Milkey4f5de002014-12-17 19:26:11 -080067import static org.easymock.EasyMock.anyObject;
Ray Milkeyd43fe452015-05-29 09:35:12 -070068import static org.easymock.EasyMock.anyShort;
Jian Li2907ad22016-05-12 23:08:54 -070069import static org.easymock.EasyMock.anyString;
Ray Milkey4f5de002014-12-17 19:26:11 -080070import static org.easymock.EasyMock.createMock;
71import static org.easymock.EasyMock.expect;
Ray Milkeyd43fe452015-05-29 09:35:12 -070072import static org.easymock.EasyMock.expectLastCall;
Ray Milkey4f5de002014-12-17 19:26:11 -080073import static org.easymock.EasyMock.replay;
74import static org.easymock.EasyMock.verify;
75import static org.hamcrest.Matchers.containsString;
76import static org.hamcrest.Matchers.hasSize;
77import static org.hamcrest.Matchers.is;
78import static org.hamcrest.Matchers.not;
79import static org.hamcrest.Matchers.notNullValue;
80import static org.junit.Assert.assertThat;
81import static org.junit.Assert.fail;
Ray Milkeyeb5c7172015-06-23 14:59:27 -070082import static org.onosproject.net.NetTestTools.APP_ID;
Ray Milkey4f5de002014-12-17 19:26:11 -080083
84/**
85 * Unit tests for Flows REST APIs.
86 */
Ray Milkey9c3d3362015-01-28 10:39:56 -080087public class FlowsResourceTest extends ResourceTest {
Ray Milkey4f5de002014-12-17 19:26:11 -080088 final FlowRuleService mockFlowService = createMock(FlowRuleService.class);
Ray Milkeyd43fe452015-05-29 09:35:12 -070089 CoreService mockCoreService = createMock(CoreService.class);
90
Ray Milkey4f5de002014-12-17 19:26:11 -080091 final HashMap<DeviceId, Set<FlowEntry>> rules = new HashMap<>();
92
93 final DeviceService mockDeviceService = createMock(DeviceService.class);
94
95 final DeviceId deviceId1 = DeviceId.deviceId("1");
96 final DeviceId deviceId2 = DeviceId.deviceId("2");
97 final DeviceId deviceId3 = DeviceId.deviceId("3");
98 final Device device1 = new DefaultDevice(null, deviceId1, Device.Type.OTHER,
99 "", "", "", "", null);
100 final Device device2 = new DefaultDevice(null, deviceId2, Device.Type.OTHER,
101 "", "", "", "", null);
102
Jian Li2907ad22016-05-12 23:08:54 -0700103 final ApplicationService mockApplicationService = createMock(ApplicationService.class);
104
Ray Milkey4f5de002014-12-17 19:26:11 -0800105 final MockFlowEntry flow1 = new MockFlowEntry(deviceId1, 1);
106 final MockFlowEntry flow2 = new MockFlowEntry(deviceId1, 2);
107
108 final MockFlowEntry flow3 = new MockFlowEntry(deviceId2, 3);
109 final MockFlowEntry flow4 = new MockFlowEntry(deviceId2, 4);
110
111 final MockFlowEntry flow5 = new MockFlowEntry(deviceId2, 5);
112 final MockFlowEntry flow6 = new MockFlowEntry(deviceId2, 6);
113
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530114 final Set<FlowEntry> flowEntries = ImmutableSet.of(flow1, flow2, flow3, flow4, flow5, flow6);
Jian Li2907ad22016-05-12 23:08:54 -0700115
Ray Milkey4f5de002014-12-17 19:26:11 -0800116 /**
117 * Mock class for a flow entry.
118 */
Ray Milkey634eb172017-04-05 14:48:50 -0700119 private static class MockFlowEntry extends FlowEntryAdapter {
Ray Milkey4f5de002014-12-17 19:26:11 -0800120 final DeviceId deviceId;
121 final long baseValue;
122 TrafficTreatment treatment;
123 TrafficSelector selector;
124
125 public MockFlowEntry(DeviceId deviceId, long id) {
126 this.deviceId = deviceId;
127 this.baseValue = id * 100;
128 }
129
130 @Override
131 public FlowEntryState state() {
132 return FlowEntryState.ADDED;
133 }
134
135 @Override
136 public long life() {
Thiago Santos877914d2016-07-20 18:29:29 -0300137 return life(SECONDS);
138 }
139
140 @Override
141 public long life(TimeUnit timeUnit) {
142 return SECONDS.convert(baseValue + 11, timeUnit);
Ray Milkey4f5de002014-12-17 19:26:11 -0800143 }
144
145 @Override
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900146 public FlowLiveType liveType() {
147 return FlowLiveType.IMMEDIATE;
148 }
149
150 @Override
Ray Milkey4f5de002014-12-17 19:26:11 -0800151 public long packets() {
152 return baseValue + 22;
153 }
154
155 @Override
156 public long bytes() {
157 return baseValue + 33;
158 }
159
160 @Override
161 public long lastSeen() {
162 return baseValue + 44;
163 }
164
165 @Override
Ray Milkey4f5de002014-12-17 19:26:11 -0800166 public FlowId id() {
167 final long id = baseValue + 55;
168 return FlowId.valueOf(id);
169 }
170
171 @Override
alshabib08d98982015-04-21 16:25:50 -0700172 public GroupId groupId() {
Yi Tsengfa394de2017-02-01 11:26:40 -0800173 return new GroupId(3);
Ray Milkey4f5de002014-12-17 19:26:11 -0800174 }
175
176 @Override
alshabib08d98982015-04-21 16:25:50 -0700177 public short appId() {
178 return 2;
Ray Milkey4f5de002014-12-17 19:26:11 -0800179 }
180
181 @Override
182 public int priority() {
183 return (int) (baseValue + 66);
184 }
185
186 @Override
187 public DeviceId deviceId() {
188 return deviceId;
189 }
190
191 @Override
192 public TrafficSelector selector() {
193 return selector;
194 }
195
196 @Override
197 public TrafficTreatment treatment() {
198 return treatment;
199 }
200
201 @Override
202 public int timeout() {
203 return (int) (baseValue + 77);
204 }
205
206 @Override
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700207 public FlowRemoveReason reason() {
208 return FlowRemoveReason.NO_REASON;
209 }
Ray Milkey4f5de002014-12-17 19:26:11 -0800210 }
211
Jian Li2907ad22016-05-12 23:08:54 -0700212
213 /**
Ray Milkey4f5de002014-12-17 19:26:11 -0800214 * Populates some flows used as testing data.
215 */
216 private void setupMockFlows() {
217 flow2.treatment = DefaultTrafficTreatment.builder()
Ray Milkey4f5de002014-12-17 19:26:11 -0800218 .setEthDst(MacAddress.BROADCAST)
219 .build();
220 flow2.selector = DefaultTrafficSelector.builder()
221 .matchEthType((short) 3)
222 .matchIPProtocol((byte) 9)
223 .build();
224 flow4.treatment = DefaultTrafficTreatment.builder()
Ray Milkey4f5de002014-12-17 19:26:11 -0800225 .build();
226 final Set<FlowEntry> flows1 = new HashSet<>();
227 flows1.add(flow1);
228 flows1.add(flow2);
229
230 final Set<FlowEntry> flows2 = new HashSet<>();
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700231 flows2.add(flow3);
232 flows2.add(flow4);
Ray Milkey4f5de002014-12-17 19:26:11 -0800233
234 rules.put(deviceId1, flows1);
235 rules.put(deviceId2, flows2);
236
237 expect(mockFlowService.getFlowEntries(deviceId1))
238 .andReturn(rules.get(deviceId1)).anyTimes();
239 expect(mockFlowService.getFlowEntries(deviceId2))
240 .andReturn(rules.get(deviceId2)).anyTimes();
241 }
242
243 /**
244 * Sets up the global values for all the tests.
245 */
246 @Before
Ray Milkeyed0b1662015-02-05 09:34:29 -0800247 public void setUpTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800248 // Mock device service
249 expect(mockDeviceService.getDevice(deviceId1))
250 .andReturn(device1);
251 expect(mockDeviceService.getDevice(deviceId2))
252 .andReturn(device2);
253 expect(mockDeviceService.getDevices())
254 .andReturn(ImmutableSet.of(device1, device2));
255
Ray Milkeyd43fe452015-05-29 09:35:12 -0700256 // Mock Core Service
257 expect(mockCoreService.getAppId(anyShort()))
258 .andReturn(NetTestTools.APP_ID).anyTimes();
Jian Li2907ad22016-05-12 23:08:54 -0700259 expect(mockCoreService.getAppId(anyString()))
260 .andReturn(NetTestTools.APP_ID).anyTimes();
Jonathan Hart9b80da82016-11-10 21:46:15 +0000261 expect(mockCoreService.registerApplication(FlowRuleCodec.REST_APP_ID))
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700262 .andReturn(APP_ID).anyTimes();
Ray Milkeyd43fe452015-05-29 09:35:12 -0700263 replay(mockCoreService);
264
Ray Milkey4f5de002014-12-17 19:26:11 -0800265 // Register the services needed for the test
266 final CodecManager codecService = new CodecManager();
267 codecService.activate();
268 ServiceDirectory testDirectory =
269 new TestServiceDirectory()
270 .add(FlowRuleService.class, mockFlowService)
271 .add(DeviceService.class, mockDeviceService)
Ray Milkeyd43fe452015-05-29 09:35:12 -0700272 .add(CodecService.class, codecService)
Jian Li2907ad22016-05-12 23:08:54 -0700273 .add(CoreService.class, mockCoreService)
274 .add(ApplicationService.class, mockApplicationService);
Ray Milkey4f5de002014-12-17 19:26:11 -0800275
Ray Milkey094a1352018-01-22 14:03:54 -0800276 setServiceDirectory(testDirectory);
Ray Milkey4f5de002014-12-17 19:26:11 -0800277 }
278
279 /**
280 * Cleans up and verifies the mocks.
Ray Milkey4f5de002014-12-17 19:26:11 -0800281 */
282 @After
Ray Milkeyed0b1662015-02-05 09:34:29 -0800283 public void tearDownTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800284 verify(mockFlowService);
Ray Milkeyd43fe452015-05-29 09:35:12 -0700285 verify(mockCoreService);
Ray Milkey4f5de002014-12-17 19:26:11 -0800286 }
287
288 /**
289 * Hamcrest matcher to check that a flow representation in JSON matches
290 * the actual flow entry.
291 */
Jian Li2907ad22016-05-12 23:08:54 -0700292 public static class FlowEntryJsonMatcher extends TypeSafeMatcher<JsonObject> {
Ray Milkey4f5de002014-12-17 19:26:11 -0800293 private final FlowEntry flow;
Ray Milkeybe539db2015-09-04 11:00:43 -0700294 private final String expectedAppId;
Ray Milkey4f5de002014-12-17 19:26:11 -0800295 private String reason = "";
296
Jian Li2907ad22016-05-12 23:08:54 -0700297 public FlowEntryJsonMatcher(FlowEntry flowValue, String expectedAppIdValue) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800298 flow = flowValue;
Ray Milkeybe539db2015-09-04 11:00:43 -0700299 expectedAppId = expectedAppIdValue;
Ray Milkey4f5de002014-12-17 19:26:11 -0800300 }
301
302 @Override
303 public boolean matchesSafely(JsonObject jsonFlow) {
304 // check id
305 final String jsonId = jsonFlow.get("id").asString();
306 final String flowId = Long.toString(flow.id().value());
307 if (!jsonId.equals(flowId)) {
308 reason = "id " + flow.id().toString();
309 return false;
310 }
311
312 // check application id
Ray Milkeybe539db2015-09-04 11:00:43 -0700313 final String jsonAppId = jsonFlow.get("appId").asString();
314 if (!jsonAppId.equals(expectedAppId)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800315 reason = "appId " + Short.toString(flow.appId());
316 return false;
317 }
318
319 // check device id
320 final String jsonDeviceId = jsonFlow.get("deviceId").asString();
321 if (!jsonDeviceId.equals(flow.deviceId().toString())) {
322 reason = "deviceId " + flow.deviceId();
323 return false;
324 }
325
326 // check treatment and instructions array
327 if (flow.treatment() != null) {
328 final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
329 final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
Ray Milkey42507352015-03-20 15:16:10 -0700330 if (flow.treatment().immediate().size() != jsonInstructions.size()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800331 reason = "instructions array size of " +
Ray Milkey42507352015-03-20 15:16:10 -0700332 Integer.toString(flow.treatment().immediate().size());
Ray Milkey4f5de002014-12-17 19:26:11 -0800333 return false;
334 }
Ray Milkey42507352015-03-20 15:16:10 -0700335 for (final Instruction instruction : flow.treatment().immediate()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800336 boolean instructionFound = false;
Ray Milkey4f5de002014-12-17 19:26:11 -0800337 for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800338 final String jsonType =
339 jsonInstructions.get(instructionIndex)
340 .asObject().get("type").asString();
341 final String instructionType = instruction.type().name();
342 if (jsonType.equals(instructionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800343 instructionFound = true;
344 }
345 }
346 if (!instructionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800347 reason = "instruction " + instruction.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800348 return false;
349 }
350 }
351 }
352
353 // check selector and criteria array
354 if (flow.selector() != null) {
355 final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
356 final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
357 if (flow.selector().criteria().size() != jsonCriteria.size()) {
358 reason = "criteria array size of " +
359 Integer.toString(flow.selector().criteria().size());
360 return false;
361 }
362 for (final Criterion criterion : flow.selector().criteria()) {
363 boolean criterionFound = false;
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800364
Ray Milkey4f5de002014-12-17 19:26:11 -0800365 for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800366 final String jsonType =
367 jsonCriteria.get(criterionIndex)
368 .asObject().get("type").asString();
369 final String criterionType = criterion.type().name();
370 if (jsonType.equals(criterionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800371 criterionFound = true;
372 }
373 }
374 if (!criterionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800375 reason = "criterion " + criterion.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800376 return false;
377 }
378 }
379 }
380
381 return true;
382 }
383
384 @Override
385 public void describeTo(Description description) {
386 description.appendText(reason);
387 }
388 }
389
390 /**
391 * Factory to allocate a flow matcher.
392 *
393 * @param flow flow object we are looking for
394 * @return matcher
395 */
Jian Li2907ad22016-05-12 23:08:54 -0700396 private static FlowEntryJsonMatcher matchesFlow(FlowEntry flow, String expectedAppName) {
397 return new FlowEntryJsonMatcher(flow, expectedAppName);
Ray Milkey4f5de002014-12-17 19:26:11 -0800398 }
399
400 /**
401 * Hamcrest matcher to check that a flow is represented properly in a JSON
402 * array of flows.
403 */
Jian Li2907ad22016-05-12 23:08:54 -0700404 public static class FlowEntryJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
Ray Milkey4f5de002014-12-17 19:26:11 -0800405 private final FlowEntry flow;
406 private String reason = "";
407
Jian Li2907ad22016-05-12 23:08:54 -0700408 public FlowEntryJsonArrayMatcher(FlowEntry flowValue) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800409 flow = flowValue;
410 }
411
412 @Override
413 public boolean matchesSafely(JsonArray json) {
414 boolean flowFound = false;
415
416 for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
417 jsonFlowIndex++) {
418
419 final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
420
421 final String flowId = Long.toString(flow.id().value());
422 final String jsonFlowId = jsonFlow.get("id").asString();
423 if (jsonFlowId.equals(flowId)) {
424 flowFound = true;
425
426 // We found the correct flow, check attribute values
Ray Milkeybe539db2015-09-04 11:00:43 -0700427 assertThat(jsonFlow, matchesFlow(flow, APP_ID.name()));
Ray Milkey4f5de002014-12-17 19:26:11 -0800428 }
429 }
430 if (!flowFound) {
431 reason = "Flow with id " + flow.id().toString() + " not found";
432 return false;
433 } else {
434 return true;
435 }
436 }
437
438 @Override
439 public void describeTo(Description description) {
440 description.appendText(reason);
441 }
442 }
443
444 /**
445 * Factory to allocate a flow array matcher.
446 *
447 * @param flow flow object we are looking for
448 * @return matcher
449 */
Jian Li2907ad22016-05-12 23:08:54 -0700450 private static FlowEntryJsonArrayMatcher hasFlow(FlowEntry flow) {
451 return new FlowEntryJsonArrayMatcher(flow);
452 }
453
454 /**
455 * Hamcrest matcher to check that a flow representation in JSON matches
456 * the actual flow rule.
457 */
458 public static class FlowRuleJsonMatcher extends TypeSafeMatcher<JsonObject> {
459 private final FlowRule flow;
460 private final String expectedAppId;
461 private String reason = "";
462
463 public FlowRuleJsonMatcher(FlowRule flowValue, String expectedAppIdValue) {
464 flow = flowValue;
465 expectedAppId = expectedAppIdValue;
466 }
467
468 @Override
469 public boolean matchesSafely(JsonObject jsonFlow) {
470 // check id
471 final String jsonId = jsonFlow.get("id").asString();
472 final String flowId = Long.toString(flow.id().value());
473 if (!jsonId.equals(flowId)) {
474 reason = "id " + flow.id().toString();
475 return false;
476 }
477
478 // check application id
479 final String jsonAppId = jsonFlow.get("appId").asString();
480 if (!jsonAppId.equals(expectedAppId)) {
481 reason = "appId " + Short.toString(flow.appId());
482 return false;
483 }
484
485 // check device id
486 final String jsonDeviceId = jsonFlow.get("deviceId").asString();
487 if (!jsonDeviceId.equals(flow.deviceId().toString())) {
488 reason = "deviceId " + flow.deviceId();
489 return false;
490 }
491
492 // check treatment and instructions array
493 if (flow.treatment() != null) {
494 final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
495 final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
496 if (flow.treatment().immediate().size() != jsonInstructions.size()) {
497 reason = "instructions array size of " +
498 Integer.toString(flow.treatment().immediate().size());
499 return false;
500 }
501 for (final Instruction instruction : flow.treatment().immediate()) {
502 boolean instructionFound = false;
503 for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
504 final String jsonType =
505 jsonInstructions.get(instructionIndex)
506 .asObject().get("type").asString();
507 final String instructionType = instruction.type().name();
508 if (jsonType.equals(instructionType)) {
509 instructionFound = true;
510 }
511 }
512 if (!instructionFound) {
513 reason = "instruction " + instruction.toString();
514 return false;
515 }
516 }
517 }
518
519 // check selector and criteria array
520 if (flow.selector() != null) {
521 final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
522 final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
523 if (flow.selector().criteria().size() != jsonCriteria.size()) {
524 reason = "criteria array size of " +
525 Integer.toString(flow.selector().criteria().size());
526 return false;
527 }
528 for (final Criterion criterion : flow.selector().criteria()) {
529 boolean criterionFound = false;
530
531 for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
532 final String jsonType =
533 jsonCriteria.get(criterionIndex)
534 .asObject().get("type").asString();
535 final String criterionType = criterion.type().name();
536 if (jsonType.equals(criterionType)) {
537 criterionFound = true;
538 }
539 }
540 if (!criterionFound) {
541 reason = "criterion " + criterion.toString();
542 return false;
543 }
544 }
545 }
546
547 return true;
548 }
549
550 @Override
551 public void describeTo(Description description) {
552 description.appendText(reason);
553 }
554 }
555
556 /**
557 * Factory to allocate a flow matcher.
558 *
559 * @param flow flow rule object we are looking for
560 * @return matcher
561 */
562 private static FlowRuleJsonMatcher matchesFlowRule(FlowRule flow, String expectedAppName) {
563 return new FlowRuleJsonMatcher(flow, expectedAppName);
564 }
565
566 /**
567 * Hamcrest matcher to check that a flow is represented properly in a JSON
568 * array of flow rules.
569 */
570 public static class FlowRuleJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
571 private final FlowRule flow;
572 private String reason = "";
573
574 public FlowRuleJsonArrayMatcher(FlowRule flowValue) {
575 flow = flowValue;
576 }
577
578 @Override
579 public boolean matchesSafely(JsonArray json) {
580 boolean flowFound = false;
581
582 for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
583 jsonFlowIndex++) {
584
585 final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
586
587 final String flowId = Long.toString(flow.id().value());
588 final String jsonFlowId = jsonFlow.get("id").asString();
589 if (jsonFlowId.equals(flowId)) {
590 flowFound = true;
591
592 // We found the correct flow, check attribute values
593 assertThat(jsonFlow, matchesFlowRule(flow, APP_ID.name()));
594 }
595 }
596 if (!flowFound) {
597 reason = "Flow with id " + flow.id().toString() + " not found";
598 return false;
599 } else {
600 return true;
601 }
602 }
603
604 @Override
605 public void describeTo(Description description) {
606 description.appendText(reason);
607 }
608 }
609
610 /**
611 * Factory to allocate a flow array matcher.
612 *
613 * @param flow flow rule object we are looking for
614 * @return matcher
615 */
616 private static FlowRuleJsonArrayMatcher hasFlowRule(FlowRule flow) {
617 return new FlowRuleJsonArrayMatcher(flow);
Ray Milkey4f5de002014-12-17 19:26:11 -0800618 }
619
620 /**
621 * Tests the result of the rest api GET when there are no flows.
622 */
623 @Test
624 public void testFlowsEmptyArray() {
625 expect(mockFlowService.getFlowEntries(deviceId1))
626 .andReturn(null).anyTimes();
627 expect(mockFlowService.getFlowEntries(deviceId2))
628 .andReturn(null).anyTimes();
629 replay(mockFlowService);
630 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800631 final WebTarget wt = target();
632 final String response = wt.path("flows").request().get(String.class);
Ray Milkey4f5de002014-12-17 19:26:11 -0800633 assertThat(response, is("{\"flows\":[]}"));
634 }
635
636 /**
637 * Tests the result of the rest api GET when there are active flows.
638 */
639 @Test
640 public void testFlowsPopulatedArray() {
641 setupMockFlows();
642 replay(mockFlowService);
643 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800644 final WebTarget wt = target();
645 final String response = wt.path("flows").request().get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800646 final JsonObject result = Json.parse(response).asObject();
Ray Milkey4f5de002014-12-17 19:26:11 -0800647 assertThat(result, notNullValue());
648
649 assertThat(result.names(), hasSize(1));
650 assertThat(result.names().get(0), is("flows"));
651 final JsonArray jsonFlows = result.get("flows").asArray();
652 assertThat(jsonFlows, notNullValue());
653 assertThat(jsonFlows, hasFlow(flow1));
654 assertThat(jsonFlows, hasFlow(flow2));
655 assertThat(jsonFlows, hasFlow(flow3));
656 assertThat(jsonFlows, hasFlow(flow4));
657 }
658
659 /**
660 * Tests the result of a rest api GET for a device.
661 */
662 @Test
663 public void testFlowsSingleDevice() {
664 setupMockFlows();
665 final Set<FlowEntry> flows = new HashSet<>();
666 flows.add(flow5);
667 flows.add(flow6);
668 expect(mockFlowService.getFlowEntries(anyObject()))
669 .andReturn(flows).anyTimes();
670 replay(mockFlowService);
671 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800672 final WebTarget wt = target();
673 final String response = wt.path("flows/" + deviceId3).request().get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800674 final JsonObject result = Json.parse(response).asObject();
Ray Milkey4f5de002014-12-17 19:26:11 -0800675 assertThat(result, notNullValue());
676
677 assertThat(result.names(), hasSize(1));
678 assertThat(result.names().get(0), is("flows"));
679 final JsonArray jsonFlows = result.get("flows").asArray();
680 assertThat(jsonFlows, notNullValue());
681 assertThat(jsonFlows, hasFlow(flow5));
682 assertThat(jsonFlows, hasFlow(flow6));
683 }
684
685 /**
686 * Tests the result of a rest api GET for a device.
687 */
688 @Test
689 public void testFlowsSingleDeviceWithFlowId() {
690 setupMockFlows();
691 final Set<FlowEntry> flows = new HashSet<>();
692 flows.add(flow5);
693 flows.add(flow6);
694 expect(mockFlowService.getFlowEntries(anyObject()))
695 .andReturn(flows).anyTimes();
696 replay(mockFlowService);
697 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800698 final WebTarget wt = target();
699 final String response = wt.path("flows/" + deviceId3 + "/"
700 + Long.toString(flow5.id().value())).request().get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800701 final JsonObject result = Json.parse(response).asObject();
Ray Milkey4f5de002014-12-17 19:26:11 -0800702 assertThat(result, notNullValue());
703
704 assertThat(result.names(), hasSize(1));
705 assertThat(result.names().get(0), is("flows"));
706 final JsonArray jsonFlows = result.get("flows").asArray();
707 assertThat(jsonFlows, notNullValue());
708 assertThat(jsonFlows, hasFlow(flow5));
709 assertThat(jsonFlows, not(hasFlow(flow6)));
710 }
711
712 /**
713 * Tests that a fetch of a non-existent device object throws an exception.
714 */
715 @Test
716 public void testBadGet() {
Jian Li9d616492016-03-09 10:52:49 -0800717 expect(mockFlowService.getFlowEntries(anyObject()))
Ray Milkey4f5de002014-12-17 19:26:11 -0800718 .andReturn(null).anyTimes();
719 replay(mockFlowService);
720 replay(mockDeviceService);
721
Jian Li9d616492016-03-09 10:52:49 -0800722 WebTarget wt = target();
Ray Milkey4f5de002014-12-17 19:26:11 -0800723 try {
Jian Li9d616492016-03-09 10:52:49 -0800724 wt.path("flows/0").request().get(String.class);
Ray Milkey4f5de002014-12-17 19:26:11 -0800725 fail("Fetch of non-existent device did not throw an exception");
Jian Li9d616492016-03-09 10:52:49 -0800726 } catch (NotFoundException ex) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800727 assertThat(ex.getMessage(),
Jian Li9d616492016-03-09 10:52:49 -0800728 containsString("HTTP 404 Not Found"));
Ray Milkey4f5de002014-12-17 19:26:11 -0800729 }
730 }
Ray Milkeyd43fe452015-05-29 09:35:12 -0700731
732 /**
733 * Tests creating a flow with POST.
734 */
735 @Test
Jian Li2907ad22016-05-12 23:08:54 -0700736 public void testPostWithoutAppId() {
Jonathan Hart9b80da82016-11-10 21:46:15 +0000737 mockFlowService.applyFlowRules(anyObject());
738 expectLastCall();
Ray Milkeyd43fe452015-05-29 09:35:12 -0700739 replay(mockFlowService);
740
Jian Li9d616492016-03-09 10:52:49 -0800741 WebTarget wt = target();
Phaneendra Manda2be2f882015-11-11 15:23:40 +0530742 InputStream jsonStream = FlowsResourceTest.class
Ray Milkeyb82c42b2015-06-30 09:42:20 -0700743 .getResourceAsStream("post-flow.json");
Ray Milkeyd43fe452015-05-29 09:35:12 -0700744
Jian Li9d616492016-03-09 10:52:49 -0800745 Response response = wt.path("flows/of:0000000000000001")
746 .request(MediaType.APPLICATION_JSON_TYPE)
747 .post(Entity.json(jsonStream));
Jonathan Hart9b80da82016-11-10 21:46:15 +0000748 assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
749 String location = response.getLocation().getPath();
750 assertThat(location, Matchers.startsWith("/flows/of:0000000000000001/"));
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700751 }
752
753 /**
Jian Li2907ad22016-05-12 23:08:54 -0700754 * Tests creating a flow with POST while specifying application identifier.
755 */
756 @Test
757 public void testPostWithAppId() {
758 mockFlowService.applyFlowRules(anyObject());
759 expectLastCall();
760 replay(mockFlowService);
761
762 WebTarget wt = target();
763 InputStream jsonStream = FlowsResourceTest.class
764 .getResourceAsStream("post-flow.json");
765
766 Response response = wt.path("flows/of:0000000000000001")
767 .queryParam("appId", "org.onosproject.rest")
768 .request(MediaType.APPLICATION_JSON_TYPE)
769 .post(Entity.json(jsonStream));
770 assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
771 String location = response.getLocation().getPath();
772 assertThat(location, Matchers.startsWith("/flows/of:0000000000000001/"));
773 }
774
775 /**
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700776 * Tests deleting a flow.
777 */
778 @Test
779 public void testDelete() {
780 setupMockFlows();
781 mockFlowService.removeFlowRules(anyObject());
782 expectLastCall();
783 replay(mockFlowService);
784
Jian Li9d616492016-03-09 10:52:49 -0800785 WebTarget wt = target();
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700786
787 String location = "/flows/1/155";
788
Jian Li9d616492016-03-09 10:52:49 -0800789 Response deleteResponse = wt.path(location)
790 .request(MediaType.APPLICATION_JSON_TYPE)
791 .delete();
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700792 assertThat(deleteResponse.getStatus(),
793 is(HttpURLConnection.HTTP_NO_CONTENT));
Ray Milkeyd43fe452015-05-29 09:35:12 -0700794 }
Jian Li2907ad22016-05-12 23:08:54 -0700795
796 /**
797 * Tests the result of a rest api GET for an application.
798 */
799 @Test
800 public void testGetFlowByAppId() {
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530801 setupMockFlows();
Jian Li2907ad22016-05-12 23:08:54 -0700802
803 expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
804 replay(mockApplicationService);
805
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530806 expect(mockFlowService.getFlowEntriesById(APP_ID)).andReturn(flowEntries).anyTimes();
Jian Li2907ad22016-05-12 23:08:54 -0700807 replay(mockFlowService);
808
809 final WebTarget wt = target();
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530810 final String response = wt.path("/flows/application/1").request().get(String.class);
Jian Li2907ad22016-05-12 23:08:54 -0700811 final JsonObject result = Json.parse(response).asObject();
812 assertThat(result, notNullValue());
813
814 assertThat(result.names(), hasSize(1));
815 assertThat(result.names().get(0), is("flows"));
816 final JsonArray jsonFlows = result.get("flows").asArray();
817 assertThat(jsonFlows, notNullValue());
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530818 assertThat(jsonFlows, hasFlowRule(flow1));
819 assertThat(jsonFlows, hasFlowRule(flow2));
820 assertThat(jsonFlows, hasFlowRule(flow3));
821 assertThat(jsonFlows, hasFlowRule(flow4));
Jian Li2907ad22016-05-12 23:08:54 -0700822 }
823
824 /**
825 * Tests the result of a rest api DELETE for an application.
826 */
827 @Test
828 public void testRemoveFlowByAppId() {
829 expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
830 replay(mockApplicationService);
831
832 mockFlowService.removeFlowRulesById(APP_ID);
833 expectLastCall();
834 replay(mockFlowService);
835
836 WebTarget wt = target();
837
838 String location = "/flows/application/1";
839
840 Response deleteResponse = wt.path(location)
841 .request()
842 .delete();
843 assertThat(deleteResponse.getStatus(),
844 is(HttpURLConnection.HTTP_NO_CONTENT));
845 }
Ray Milkey4f5de002014-12-17 19:26:11 -0800846}