From b731e2f1dd0972409b136aebc7b463dd72c9cfad Mon Sep 17 00:00:00 2001 From: CNlucius Date: Tue, 13 Sep 2016 11:40:12 +0800 Subject: ONOSFW-171 O/S-SFC-ONOS scenario documentation Change-Id: I51ae1cf736ea24ab6680f8edca1b2bf5dd598365 Signed-off-by: CNlucius --- .../onosproject/rest/ApplicationsResourceTest.java | 332 ----------- .../java/org/onosproject/rest/BadRequestTest.java | 61 -- .../rest/ComponentConfigWebResourceTest.java | 128 ----- .../org/onosproject/rest/DevicesResourceTest.java | 377 ------------- .../org/onosproject/rest/FlowsResourceTest.java | 619 --------------------- .../org/onosproject/rest/HostResourceTest.java | 390 ------------- .../org/onosproject/rest/IntentsResourceTest.java | 492 ---------------- .../org/onosproject/rest/LinksResourceTest.java | 351 ------------ .../org/onosproject/rest/PathsResourceTest.java | 238 -------- .../java/org/onosproject/rest/ResourceTest.java | 54 -- .../onosproject/rest/StatisticsResourceTest.java | 179 ------ .../org/onosproject/rest/TopologyResourceTest.java | 281 ---------- .../rest/exceptions/ExceptionMapperTest.java | 35 -- .../resources/NetworkConfigWebResourceTest.java | 352 ------------ .../src/test/java/org/onosproject/rest/topo.json | 19 - 15 files changed, 3908 deletions(-) delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/ApplicationsResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/BadRequestTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/ComponentConfigWebResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/DevicesResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/FlowsResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/HostResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/IntentsResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/LinksResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/PathsResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/ResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/StatisticsResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/TopologyResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/exceptions/ExceptionMapperTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java delete mode 100644 framework/src/onos/web/api/src/test/java/org/onosproject/rest/topo.json (limited to 'framework/src/onos/web/api/src/test/java/org/onosproject/rest') diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ApplicationsResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ApplicationsResourceTest.java deleted file mode 100644 index 3e72f18d..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ApplicationsResourceTest.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.WebResource; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.app.ApplicationAdminService; -import org.onosproject.app.ApplicationService; -import org.onosproject.app.ApplicationState; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.ApplicationCodec; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.codec.impl.MockCodecContext; -import org.onosproject.core.Application; -import org.onosproject.core.ApplicationId; -import org.onosproject.core.ApplicationRole; -import org.onosproject.core.DefaultApplication; -import org.onosproject.core.DefaultApplicationId; -import org.onosproject.core.Version; - -import java.io.InputStream; -import java.net.URI; -import java.util.Optional; - -import static org.easymock.EasyMock.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; - -/** - * Unit tests for applications REST APIs. - */ - -public class ApplicationsResourceTest extends ResourceTest { - - private static class MockCodecContextWithService extends MockCodecContext { - private ApplicationAdminService service; - - MockCodecContextWithService(ApplicationAdminService service) { - this.service = service; - } - - @Override - @SuppressWarnings("unchecked") - public T getService(Class serviceClass) { - return (T) service; - } - } - - private ApplicationAdminService service; - private ApplicationId id1 = new DefaultApplicationId(1, "app1"); - private ApplicationId id2 = new DefaultApplicationId(2, "app2"); - private ApplicationId id3 = new DefaultApplicationId(3, "app3"); - private ApplicationId id4 = new DefaultApplicationId(4, "app4"); - - private static final URI FURL = URI.create("mvn:org.foo-features/1.2a/xml/features"); - private static final Version VER = Version.version(1, 2, "a", null); - - private Application app1 = - new DefaultApplication(id1, VER, - "app1", "origin1", ApplicationRole.ADMIN, ImmutableSet.of(), Optional.of(FURL), - ImmutableList.of("My Feature"), ImmutableList.of()); - private Application app2 = - new DefaultApplication(id2, VER, - "app2", "origin2", ApplicationRole.ADMIN, ImmutableSet.of(), Optional.of(FURL), - ImmutableList.of("My Feature"), ImmutableList.of()); - private Application app3 = - new DefaultApplication(id3, VER, - "app3", "origin3", ApplicationRole.ADMIN, ImmutableSet.of(), Optional.of(FURL), - ImmutableList.of("My Feature"), ImmutableList.of()); - private Application app4 = - new DefaultApplication(id4, VER, - "app4", "origin4", ApplicationRole.ADMIN, ImmutableSet.of(), Optional.of(FURL), - ImmutableList.of("My Feature"), ImmutableList.of()); - - /** - * Hamcrest matcher to check that an application representation in JSON matches - * the actual device. - */ - private static class AppJsonMatcher extends TypeSafeMatcher { - private final Application app; - private String reason = ""; - - public AppJsonMatcher(Application appValue) { - app = appValue; - } - - @Override - public boolean matchesSafely(JsonObject jsonApp) { - // check id - short jsonId = (short) jsonApp.get("id").asInt(); - if (jsonId != app.id().id()) { - reason = "id " + app.id().id(); - return false; - } - - // check name - String jsonName = jsonApp.get("name").asString(); - if (!jsonName.equals(app.id().name())) { - reason = "name " + app.id().name(); - return false; - } - - // check origin - String jsonOrigin = jsonApp.get("origin").asString(); - if (!jsonOrigin.equals(app.origin())) { - reason = "manufacturer " + app.origin(); - return false; - } - - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate an application matcher. - * - * @param app application object we are looking for - * @return matcher - */ - private static AppJsonMatcher matchesApp(Application app) { - return new AppJsonMatcher(app); - } - - /** - * Initializes test mocks and environment. - */ - @Before - public void setUpMocks() { - service = createMock(ApplicationAdminService.class); - - expect(service.getId("one")) - .andReturn(id1) - .anyTimes(); - expect(service.getId("two")) - .andReturn(id2) - .anyTimes(); - expect(service.getId("three")) - .andReturn(id3) - .anyTimes(); - expect(service.getId("four")) - .andReturn(id4) - .anyTimes(); - - expect(service.getApplication(id3)) - .andReturn(app3) - .anyTimes(); - expect(service.getState(isA(ApplicationId.class))) - .andReturn(ApplicationState.ACTIVE) - .anyTimes(); - - // Register the services needed for the test - CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(ApplicationAdminService.class, service) - .add(ApplicationService.class, service) - .add(CodecService.class, codecService); - - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Verifies test mocks. - */ - @After - public void tearDownMocks() { - verify(service); - } - - /** - * Tests a GET of all applications when no applications are present. - */ - @Test - public void getAllApplicationsEmpty() { - expect(service.getApplications()) - .andReturn(ImmutableSet.of()); - replay(service); - - WebResource rs = resource(); - String response = rs.path("applications").get(String.class); - assertThat(response, is("{\"applications\":[]}")); - } - - /** - * Tests a GET of all applications with data. - */ - @Test - public void getAllApplicationsPopulated() { - expect(service.getApplications()) - .andReturn(ImmutableSet.of(app1, app2, app3, app4)); - replay(service); - - WebResource rs = resource(); - String response = rs.path("applications").get(String.class); - assertThat(response, containsString("{\"applications\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("applications")); - - JsonArray jsonApps = result.get("applications").asArray(); - assertThat(jsonApps, notNullValue()); - assertThat(jsonApps.size(), is(4)); - - assertThat(jsonApps.get(0).asObject(), matchesApp(app1)); - assertThat(jsonApps.get(1).asObject(), matchesApp(app2)); - assertThat(jsonApps.get(2).asObject(), matchesApp(app3)); - assertThat(jsonApps.get(3).asObject(), matchesApp(app4)); - } - - /** - * Tests a GET of a single application. - */ - @Test - public void getSingleApplication() { - replay(service); - - WebResource rs = resource(); - String response = rs.path("applications/three").get(String.class); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result, matchesApp(app3)); - } - - /** - * Tests a DELETE of a single application - this should - * attempt to uninstall it. - */ - @Test - public void deleteApplication() { - service.uninstall(id3); - expectLastCall(); - - replay(service); - - WebResource rs = resource(); - rs.path("applications/three").delete(); - } - - /** - * Tests a DELETE of a single active application - this should - * attempt to uninstall it. - */ - @Test - public void deleteActiveApplication() { - service.deactivate(id3); - expectLastCall(); - - replay(service); - - WebResource rs = resource(); - rs.path("applications/three/active").delete(); - } - - /** - * Tests a POST operation to the "active" URL. This should attempt to - * activate the application. - */ - @Test - public void postActiveApplication() { - service.activate(id3); - expectLastCall(); - - replay(service); - - WebResource rs = resource(); - rs.path("applications/three/active").post(); - } - - /** - * Tests a POST operation. This should attempt to - * install the application. - */ - @Test - public void postApplication() { - expect(service.install(isA(InputStream.class))) - .andReturn(app4) - .once(); - - replay(service); - - ApplicationCodec codec = new ApplicationCodec(); - String app4Json = codec.encode(app4, - new MockCodecContextWithService(service)) - .asText(); - - WebResource rs = resource(); - String response = rs.path("applications").post(String.class, app4Json); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result, matchesApp(app4)); - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/BadRequestTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/BadRequestTest.java deleted file mode 100644 index 1b462f6e..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/BadRequestTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import org.junit.Test; - -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -/** - * Unit tests for bad REST requests. - */ -public class BadRequestTest extends ResourceTest { - - /** - * Tests the response for an invalid URL. - */ - @Test - public void badUrl() { - WebResource rs = resource(); - try { - rs.path("ThisIsABadURL").get(String.class); - fail("Fetch of non-existent URL did not throw an exception"); - } catch (UniformInterfaceException ex) { - assertThat(ex.getMessage(), - containsString("returned a response status of 404 Not Found")); - } - } - - /** - * Tests the response for a request with a bad method. - */ - @Test - public void badMethod() { - WebResource rs = resource(); - try { - rs.path("hosts").delete(); - fail("Fetch of non-existent URL did not throw an exception"); - } catch (UniformInterfaceException ex) { - assertThat(ex.getMessage(), - containsString("returned a response status of 405 Method Not Allowed")); - } - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ComponentConfigWebResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ComponentConfigWebResourceTest.java deleted file mode 100644 index 4edba503..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ComponentConfigWebResourceTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.cfg.ComponentConfigAdapter; -import org.onosproject.cfg.ComponentConfigService; -import org.onosproject.cfg.ConfigProperty; - -import java.util.Set; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.onosproject.cfg.ConfigProperty.Type.INTEGER; -import static org.onosproject.cfg.ConfigProperty.Type.STRING; -import static org.onosproject.cfg.ConfigProperty.defineProperty; - -/** - * Test of the component config REST API. - */ -public class ComponentConfigWebResourceTest extends ResourceTest { - - private TestConfigManager service; - - @Before - public void setUp() { - service = new TestConfigManager(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(ComponentConfigService.class, service); - BaseResource.setServiceDirectory(testDirectory); - } - - @Test - public void getAllConfigs() { - WebResource rs = resource(); - String response = rs.path("configuration").get(String.class); - assertThat(response, containsString("\"foo\":")); - assertThat(response, containsString("\"bar\":")); - } - - @Test - public void getConfigs() { - WebResource rs = resource(); - String response = rs.path("configuration/foo").get(String.class); - assertThat(response, containsString("{\"foo\":")); - assertThat(response, not(containsString("{\"bar\":"))); - } - - @Test - public void setConfigs() { - WebResource rs = resource(); - try { - rs.path("configuration/foo").post(String.class, "{ \"k\" : \"v\" }"); - } catch (UniformInterfaceException e) { - assertEquals("incorrect key", "foo", service.component); - assertEquals("incorrect key", "k", service.name); - assertEquals("incorrect value", "v", service.value); - } - } - - @Test - public void unsetConfigs() { - WebResource rs = resource(); - try { - rs.path("configuration/foo").delete(String.class, "{ \"k\" : \"v\" }"); - } catch (UniformInterfaceException e) { - assertEquals("incorrect key", "foo", service.component); - assertEquals("incorrect key", "k", service.name); - assertEquals("incorrect value", null, service.value); - } - } - - - private class TestConfigManager extends ComponentConfigAdapter { - - private String component; - private String name; - private String value; - - @Override - public Set getComponentNames() { - return ImmutableSet.of("foo", "bar"); - } - - @Override - public void setProperty(String componentName, String name, String value) { - this.component = componentName; - this.name = name; - this.value = value; - } - - @Override - public void unsetProperty(String componentName, String name) { - this.component = componentName; - this.name = name; - this.value = null; - } - - @Override - public Set getProperties(String componentName) { - return ImmutableSet.of(defineProperty("k1", STRING, "d1", "dv1"), - defineProperty("k2", INTEGER, "d2", "321")); - } - } -} \ No newline at end of file diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/DevicesResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/DevicesResourceTest.java deleted file mode 100644 index b5164a7a..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/DevicesResourceTest.java +++ /dev/null @@ -1,377 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import java.util.List; - -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.net.DefaultPort; -import org.onosproject.net.Device; -import org.onosproject.net.DeviceId; -import org.onosproject.net.MastershipRole; -import org.onosproject.net.Port; -import org.onosproject.net.device.DeviceService; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableList; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.onosproject.net.NetTestTools.device; -import static org.onosproject.net.NetTestTools.did; -import static org.onosproject.net.PortNumber.portNumber; - -/** - * Unit tests for devices REST APIs. - */ -public class DevicesResourceTest extends ResourceTest { - DeviceService mockDeviceService; - - /** - * Hamcrest matcher to check that an device representation in JSON matches - * the actual device. - */ - public static class DeviceJsonMatcher extends TypeSafeMatcher { - private final Device device; - private String reason = ""; - - public DeviceJsonMatcher(Device deviceValue) { - device = deviceValue; - } - - @Override - public boolean matchesSafely(JsonObject jsonDevice) { - // check id - String jsonId = jsonDevice.get("id").asString(); - if (!jsonId.equals(device.id().toString())) { - reason = "id " + device.id().toString(); - return false; - } - - // check type - String jsonType = jsonDevice.get("type").asString(); - if (!jsonType.equals(device.type().toString())) { - reason = "appId " + device.type().toString(); - return false; - } - - // check manufacturer - String jsonManufacturer = jsonDevice.get("mfr").asString(); - if (!jsonManufacturer.equals(device.manufacturer())) { - reason = "manufacturer " + device.manufacturer(); - return false; - } - - // check HW version field - String jsonHwVersion = jsonDevice.get("hw").asString(); - if (!jsonHwVersion.equals(device.hwVersion())) { - reason = "hw Version " + device.hwVersion(); - return false; - } - - // check SW version field - String jsonSwVersion = jsonDevice.get("sw").asString(); - if (!jsonSwVersion.equals(device.swVersion())) { - reason = "sw Version " + device.swVersion(); - return false; - } - - // check serial number field - String jsonSerialNumber = jsonDevice.get("serial").asString(); - if (!jsonSerialNumber.equals(device.serialNumber())) { - reason = "serial number " + device.serialNumber(); - return false; - } - - // check chassis id field - String jsonChassisId = jsonDevice.get("chassisId").asString(); - if (!jsonChassisId.equals(device.chassisId().toString())) { - reason = "Chassis id " + device.chassisId().toString(); - return false; - } - - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate an device matcher. - * - * @param device device object we are looking for - * @return matcher - */ - private static DeviceJsonMatcher matchesDevice(Device device) { - return new DeviceJsonMatcher(device); - } - - /** - * Hamcrest matcher to check that an device is represented properly in a JSON - * array of devices. - */ - private static class DeviceJsonArrayMatcher extends TypeSafeMatcher { - private final Device device; - private String reason = ""; - - public DeviceJsonArrayMatcher(Device deviceValue) { - device = deviceValue; - } - - @Override - public boolean matchesSafely(JsonArray json) { - final int minExpectedAttributes = 9; - final int maxExpectedAttributes = 10; - - boolean deviceFound = false; - - for (int jsonDeviceIndex = 0; jsonDeviceIndex < json.size(); - jsonDeviceIndex++) { - - JsonObject jsonDevice = json.get(jsonDeviceIndex).asObject(); - - if (jsonDevice.names().size() < minExpectedAttributes || - jsonDevice.names().size() > maxExpectedAttributes) { - reason = "Found a device with the wrong number of attributes"; - return false; - } - - String jsonDeviceId = jsonDevice.get("id").asString(); - if (jsonDeviceId.equals(device.id().toString())) { - deviceFound = true; - - // We found the correct device, check attribute values - assertThat(jsonDevice, matchesDevice(device)); - } - } - if (!deviceFound) { - reason = "Device with id " + device.id().toString() + " not found"; - return false; - } else { - return true; - } - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate an device array matcher. - * - * @param device device object we are looking for - * @return matcher - */ - private static DeviceJsonArrayMatcher hasDevice(Device device) { - return new DeviceJsonArrayMatcher(device); - } - - /** - * Initializes test mocks and environment. - */ - @Before - public void setUpMocks() { - mockDeviceService = createMock(DeviceService.class); - - expect(mockDeviceService.isAvailable(isA(DeviceId.class))) - .andReturn(true) - .anyTimes(); - expect(mockDeviceService.getRole(isA(DeviceId.class))) - .andReturn(MastershipRole.MASTER) - .anyTimes(); - - // Register the services needed for the test - CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(DeviceService.class, mockDeviceService) - .add(CodecService.class, codecService); - - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Verifies test mocks. - */ - @After - public void tearDownMocks() { - verify(mockDeviceService); - } - - /** - * Tests the result of the rest api GET when there are no devices. - */ - @Test - public void testDevicesEmptyArray() { - expect(mockDeviceService.getDevices()).andReturn(ImmutableList.of()); - replay(mockDeviceService); - - WebResource rs = resource(); - String response = rs.path("devices").get(String.class); - assertThat(response, is("{\"devices\":[]}")); - } - - /** - * Tests the result of the rest api GET when there are devices present. - */ - @Test - public void testDevices() { - Device device1 = device("dev1"); - Device device2 = device("dev2"); - Device device3 = device("dev3"); - - expect(mockDeviceService.getDevices()) - .andReturn(ImmutableList.of(device1, device2, device3)) - .anyTimes(); - - replay(mockDeviceService); - - WebResource rs = resource(); - String response = rs.path("devices").get(String.class); - assertThat(response, containsString("{\"devices\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("devices")); - - JsonArray jsonDevices = result.get("devices").asArray(); - assertThat(jsonDevices, notNullValue()); - assertThat(jsonDevices.size(), is(3)); - - assertThat(jsonDevices, hasDevice(device1)); - assertThat(jsonDevices, hasDevice(device2)); - assertThat(jsonDevices, hasDevice(device3)); - } - - /** - * Tests the result of a rest api GET for a single device. - */ - @Test - public void testDevicesSingle() { - - String deviceIdString = "testdevice"; - DeviceId deviceId = did(deviceIdString); - Device device = device(deviceIdString); - - expect(mockDeviceService.getDevice(deviceId)) - .andReturn(device) - .once(); - replay(mockDeviceService); - - WebResource rs = resource(); - String response = rs.path("devices/" + deviceId).get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, matchesDevice(device)); - } - - /** - * Tests the result of a rest api GET for the ports of a single device. - */ - @Test - public void testDeviceAndPorts() { - - String deviceIdString = "testdevice"; - DeviceId deviceId = did(deviceIdString); - Device device = device(deviceIdString); - - Port port1 = new DefaultPort(device, portNumber(1), true); - Port port2 = new DefaultPort(device, portNumber(2), true); - Port port3 = new DefaultPort(device, portNumber(3), true); - List ports = ImmutableList.of(port1, port2, port3); - - expect(mockDeviceService.getDevice(deviceId)) - .andReturn(device) - .once(); - - expect(mockDeviceService.getPorts(deviceId)) - .andReturn(ports) - .once(); - replay(mockDeviceService); - - WebResource rs = resource(); - String response = - rs.path("devices/" + deviceId + "/ports") - .get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, matchesDevice(device)); - - JsonArray jsonPorts = result.get("ports").asArray(); - assertThat(jsonPorts.size(), is(3)); - for (int portIndex = 0; portIndex < jsonPorts.size(); portIndex++) { - JsonObject jsonPort = jsonPorts.get(portIndex).asObject(); - - assertThat(jsonPort.get("port").asString(), - is(Integer.toString(portIndex + 1))); - assertThat(jsonPort.get("isEnabled").asBoolean(), - is(true)); - assertThat(jsonPort.get("type").asString(), - equalTo("copper")); - assertThat(jsonPort.get("portSpeed").asLong(), - is(1000L)); - } - } - - /** - * Tests that a fetch of a non-existent device object throws an exception. - */ - @Test - public void testBadGet() { - - expect(mockDeviceService.getDevice(isA(DeviceId.class))) - .andReturn(null) - .anyTimes(); - replay(mockDeviceService); - - WebResource rs = resource(); - try { - rs.path("devices/0").get(String.class); - fail("Fetch of non-existent device did not throw an exception"); - } catch (UniformInterfaceException ex) { - assertThat(ex.getMessage(), - containsString("returned a response status of")); - } - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/FlowsResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/FlowsResourceTest.java deleted file mode 100644 index 8910e733..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/FlowsResourceTest.java +++ /dev/null @@ -1,619 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import org.hamcrest.Description; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeMatcher; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.packet.MacAddress; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.codec.impl.FlowRuleCodec; -import org.onosproject.core.CoreService; -import org.onosproject.core.DefaultGroupId; -import org.onosproject.core.GroupId; -import org.onosproject.net.DefaultDevice; -import org.onosproject.net.Device; -import org.onosproject.net.DeviceId; -import org.onosproject.net.IndexedLambda; -import org.onosproject.net.NetTestTools; -import org.onosproject.net.device.DeviceService; -import org.onosproject.net.flow.DefaultTrafficSelector; -import org.onosproject.net.flow.DefaultTrafficTreatment; -import org.onosproject.net.flow.FlowEntry; -import org.onosproject.net.flow.FlowId; -import org.onosproject.net.flow.FlowRule; -import org.onosproject.net.flow.FlowRuleExtPayLoad; -import org.onosproject.net.flow.FlowRuleService; -import org.onosproject.net.flow.TrafficSelector; -import org.onosproject.net.flow.TrafficTreatment; -import org.onosproject.net.flow.criteria.Criterion; -import org.onosproject.net.flow.instructions.Instruction; -import org.onosproject.net.flow.instructions.Instructions; - -import javax.ws.rs.core.MediaType; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.anyShort; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.onosproject.net.NetTestTools.APP_ID; - -/** - * Unit tests for Flows REST APIs. - */ -public class FlowsResourceTest extends ResourceTest { - final FlowRuleService mockFlowService = createMock(FlowRuleService.class); - CoreService mockCoreService = createMock(CoreService.class); - - final HashMap> rules = new HashMap<>(); - - final DeviceService mockDeviceService = createMock(DeviceService.class); - - final DeviceId deviceId1 = DeviceId.deviceId("1"); - final DeviceId deviceId2 = DeviceId.deviceId("2"); - final DeviceId deviceId3 = DeviceId.deviceId("3"); - final Device device1 = new DefaultDevice(null, deviceId1, Device.Type.OTHER, - "", "", "", "", null); - final Device device2 = new DefaultDevice(null, deviceId2, Device.Type.OTHER, - "", "", "", "", null); - - final MockFlowEntry flow1 = new MockFlowEntry(deviceId1, 1); - final MockFlowEntry flow2 = new MockFlowEntry(deviceId1, 2); - - final MockFlowEntry flow3 = new MockFlowEntry(deviceId2, 3); - final MockFlowEntry flow4 = new MockFlowEntry(deviceId2, 4); - - final MockFlowEntry flow5 = new MockFlowEntry(deviceId2, 5); - final MockFlowEntry flow6 = new MockFlowEntry(deviceId2, 6); - - /** - * Mock class for a flow entry. - */ - private static class MockFlowEntry implements FlowEntry { - final DeviceId deviceId; - final long baseValue; - TrafficTreatment treatment; - TrafficSelector selector; - - public MockFlowEntry(DeviceId deviceId, long id) { - this.deviceId = deviceId; - this.baseValue = id * 100; - } - - @Override - public FlowEntryState state() { - return FlowEntryState.ADDED; - } - - @Override - public long life() { - return baseValue + 11; - } - - @Override - public long packets() { - return baseValue + 22; - } - - @Override - public long bytes() { - return baseValue + 33; - } - - @Override - public long lastSeen() { - return baseValue + 44; - } - - @Override - public int errType() { - return 0; - } - - @Override - public int errCode() { - return 0; - } - - @Override - public FlowId id() { - final long id = baseValue + 55; - return FlowId.valueOf(id); - } - - @Override - public GroupId groupId() { - return new DefaultGroupId(3); - } - - @Override - public short appId() { - return 2; - } - - @Override - public int priority() { - return (int) (baseValue + 66); - } - - @Override - public DeviceId deviceId() { - return deviceId; - } - - @Override - public TrafficSelector selector() { - return selector; - } - - @Override - public TrafficTreatment treatment() { - return treatment; - } - - @Override - public int timeout() { - return (int) (baseValue + 77); - } - - @Override - public boolean isPermanent() { - return false; - } - - @Override - public int tableId() { - return 0; - } - - @Override - public boolean exactMatch(FlowRule rule) { - return false; - } - - @Override - public FlowRuleExtPayLoad payLoad() { - return null; - } - } - - /** - * Populates some flows used as testing data. - */ - private void setupMockFlows() { - flow2.treatment = DefaultTrafficTreatment.builder() - .add(Instructions.modL0Lambda(new IndexedLambda((short) 4))) - .add(Instructions.modL0Lambda(new IndexedLambda((short) 5))) - .setEthDst(MacAddress.BROADCAST) - .build(); - flow2.selector = DefaultTrafficSelector.builder() - .matchEthType((short) 3) - .matchIPProtocol((byte) 9) - .build(); - flow4.treatment = DefaultTrafficTreatment.builder() - .add(Instructions.modL0Lambda(new IndexedLambda((short) 6))) - .build(); - final Set flows1 = new HashSet<>(); - flows1.add(flow1); - flows1.add(flow2); - - final Set flows2 = new HashSet<>(); - flows2.add(flow3); - flows2.add(flow4); - - rules.put(deviceId1, flows1); - rules.put(deviceId2, flows2); - - expect(mockFlowService.getFlowEntries(deviceId1)) - .andReturn(rules.get(deviceId1)).anyTimes(); - expect(mockFlowService.getFlowEntries(deviceId2)) - .andReturn(rules.get(deviceId2)).anyTimes(); - } - - /** - * Sets up the global values for all the tests. - */ - @Before - public void setUpTest() { - // Mock device service - expect(mockDeviceService.getDevice(deviceId1)) - .andReturn(device1); - expect(mockDeviceService.getDevice(deviceId2)) - .andReturn(device2); - expect(mockDeviceService.getDevices()) - .andReturn(ImmutableSet.of(device1, device2)); - - // Mock Core Service - expect(mockCoreService.getAppId(anyShort())) - .andReturn(NetTestTools.APP_ID).anyTimes(); - expect(mockCoreService.registerApplication(FlowRuleCodec.REST_APP_ID)) - .andReturn(APP_ID).anyTimes(); - replay(mockCoreService); - - // Register the services needed for the test - final CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(FlowRuleService.class, mockFlowService) - .add(DeviceService.class, mockDeviceService) - .add(CodecService.class, codecService) - .add(CoreService.class, mockCoreService); - - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Cleans up and verifies the mocks. - */ - @After - public void tearDownTest() { - verify(mockFlowService); - verify(mockCoreService); - } - - /** - * Hamcrest matcher to check that a flow representation in JSON matches - * the actual flow entry. - */ - public static class FlowJsonMatcher extends TypeSafeMatcher { - private final FlowEntry flow; - private final String expectedAppId; - private String reason = ""; - - public FlowJsonMatcher(FlowEntry flowValue, String expectedAppIdValue) { - flow = flowValue; - expectedAppId = expectedAppIdValue; - } - - @Override - public boolean matchesSafely(JsonObject jsonFlow) { - // check id - final String jsonId = jsonFlow.get("id").asString(); - final String flowId = Long.toString(flow.id().value()); - if (!jsonId.equals(flowId)) { - reason = "id " + flow.id().toString(); - return false; - } - - // check application id - final String jsonAppId = jsonFlow.get("appId").asString(); - if (!jsonAppId.equals(expectedAppId)) { - reason = "appId " + Short.toString(flow.appId()); - return false; - } - - // check device id - final String jsonDeviceId = jsonFlow.get("deviceId").asString(); - if (!jsonDeviceId.equals(flow.deviceId().toString())) { - reason = "deviceId " + flow.deviceId(); - return false; - } - - // check treatment and instructions array - if (flow.treatment() != null) { - final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject(); - final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray(); - if (flow.treatment().immediate().size() != jsonInstructions.size()) { - reason = "instructions array size of " + - Integer.toString(flow.treatment().immediate().size()); - return false; - } - for (final Instruction instruction : flow.treatment().immediate()) { - boolean instructionFound = false; - for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) { - final String jsonType = - jsonInstructions.get(instructionIndex) - .asObject().get("type").asString(); - final String instructionType = instruction.type().name(); - if (jsonType.equals(instructionType)) { - instructionFound = true; - } - } - if (!instructionFound) { - reason = "instruction " + instruction.toString(); - return false; - } - } - } - - // check selector and criteria array - if (flow.selector() != null) { - final JsonObject jsonTreatment = jsonFlow.get("selector").asObject(); - final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray(); - if (flow.selector().criteria().size() != jsonCriteria.size()) { - reason = "criteria array size of " + - Integer.toString(flow.selector().criteria().size()); - return false; - } - for (final Criterion criterion : flow.selector().criteria()) { - boolean criterionFound = false; - - for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) { - final String jsonType = - jsonCriteria.get(criterionIndex) - .asObject().get("type").asString(); - final String criterionType = criterion.type().name(); - if (jsonType.equals(criterionType)) { - criterionFound = true; - } - } - if (!criterionFound) { - reason = "criterion " + criterion.toString(); - return false; - } - } - } - - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate a flow matcher. - * - * @param flow flow object we are looking for - * @return matcher - */ - private static FlowJsonMatcher matchesFlow(FlowEntry flow, String expectedAppName) { - return new FlowJsonMatcher(flow, expectedAppName); - } - - /** - * Hamcrest matcher to check that a flow is represented properly in a JSON - * array of flows. - */ - public static class FlowJsonArrayMatcher extends TypeSafeMatcher { - private final FlowEntry flow; - private String reason = ""; - - public FlowJsonArrayMatcher(FlowEntry flowValue) { - flow = flowValue; - } - - @Override - public boolean matchesSafely(JsonArray json) { - boolean flowFound = false; - - for (int jsonFlowIndex = 0; jsonFlowIndex < json.size(); - jsonFlowIndex++) { - - final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject(); - - final String flowId = Long.toString(flow.id().value()); - final String jsonFlowId = jsonFlow.get("id").asString(); - if (jsonFlowId.equals(flowId)) { - flowFound = true; - - // We found the correct flow, check attribute values - assertThat(jsonFlow, matchesFlow(flow, APP_ID.name())); - } - } - if (!flowFound) { - reason = "Flow with id " + flow.id().toString() + " not found"; - return false; - } else { - return true; - } - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate a flow array matcher. - * - * @param flow flow object we are looking for - * @return matcher - */ - private static FlowJsonArrayMatcher hasFlow(FlowEntry flow) { - return new FlowJsonArrayMatcher(flow); - } - - /** - * Tests the result of the rest api GET when there are no flows. - */ - @Test - public void testFlowsEmptyArray() { - expect(mockFlowService.getFlowEntries(deviceId1)) - .andReturn(null).anyTimes(); - expect(mockFlowService.getFlowEntries(deviceId2)) - .andReturn(null).anyTimes(); - replay(mockFlowService); - replay(mockDeviceService); - final WebResource rs = resource(); - final String response = rs.path("flows").get(String.class); - assertThat(response, is("{\"flows\":[]}")); - } - - /** - * Tests the result of the rest api GET when there are active flows. - */ - @Test - public void testFlowsPopulatedArray() { - setupMockFlows(); - replay(mockFlowService); - replay(mockDeviceService); - final WebResource rs = resource(); - final String response = rs.path("flows").get(String.class); - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("flows")); - final JsonArray jsonFlows = result.get("flows").asArray(); - assertThat(jsonFlows, notNullValue()); - assertThat(jsonFlows, hasFlow(flow1)); - assertThat(jsonFlows, hasFlow(flow2)); - assertThat(jsonFlows, hasFlow(flow3)); - assertThat(jsonFlows, hasFlow(flow4)); - } - - /** - * Tests the result of a rest api GET for a device. - */ - @Test - public void testFlowsSingleDevice() { - setupMockFlows(); - final Set flows = new HashSet<>(); - flows.add(flow5); - flows.add(flow6); - expect(mockFlowService.getFlowEntries(anyObject())) - .andReturn(flows).anyTimes(); - replay(mockFlowService); - replay(mockDeviceService); - final WebResource rs = resource(); - final String response = rs.path("flows/" + deviceId3).get(String.class); - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("flows")); - final JsonArray jsonFlows = result.get("flows").asArray(); - assertThat(jsonFlows, notNullValue()); - assertThat(jsonFlows, hasFlow(flow5)); - assertThat(jsonFlows, hasFlow(flow6)); - } - - /** - * Tests the result of a rest api GET for a device. - */ - @Test - public void testFlowsSingleDeviceWithFlowId() { - setupMockFlows(); - final Set flows = new HashSet<>(); - flows.add(flow5); - flows.add(flow6); - expect(mockFlowService.getFlowEntries(anyObject())) - .andReturn(flows).anyTimes(); - replay(mockFlowService); - replay(mockDeviceService); - final WebResource rs = resource(); - final String response = rs.path("flows/" + deviceId3 + "/" - + Long.toString(flow5.id().value())).get(String.class); - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("flows")); - final JsonArray jsonFlows = result.get("flows").asArray(); - assertThat(jsonFlows, notNullValue()); - assertThat(jsonFlows, hasFlow(flow5)); - assertThat(jsonFlows, not(hasFlow(flow6))); - } - - /** - * Tests that a fetch of a non-existent device object throws an exception. - */ - @Test - public void testBadGet() { - expect(mockFlowService.getFlowEntries(deviceId1)) - .andReturn(null).anyTimes(); - expect(mockFlowService.getFlowEntries(deviceId2)) - .andReturn(null).anyTimes(); - replay(mockFlowService); - replay(mockDeviceService); - - WebResource rs = resource(); - try { - rs.path("flows/0").get(String.class); - fail("Fetch of non-existent device did not throw an exception"); - } catch (UniformInterfaceException ex) { - assertThat(ex.getMessage(), - containsString("returned a response status of")); - } - } - - /** - * Tests creating a flow with POST. - */ - @Test - public void testPost() { - - - mockFlowService.applyFlowRules(anyObject()); - expectLastCall(); - replay(mockFlowService); - - WebResource rs = resource(); - InputStream jsonStream = FlowsResourceTest.class - .getResourceAsStream("post-flow.json"); - - ClientResponse response = rs.path("flows/of:0000000000000001") - .type(MediaType.APPLICATION_JSON_TYPE) - .post(ClientResponse.class, jsonStream); - assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); - String location = response.getLocation().getPath(); - assertThat(location, Matchers.startsWith("/flows/of:0000000000000001/")); - } - - /** - * Tests deleting a flow. - */ - @Test - public void testDelete() { - setupMockFlows(); - mockFlowService.removeFlowRules(anyObject()); - expectLastCall(); - replay(mockFlowService); - - WebResource rs = resource(); - - String location = "/flows/1/155"; - - ClientResponse deleteResponse = rs.path(location) - .type(MediaType.APPLICATION_JSON_TYPE) - .delete(ClientResponse.class); - assertThat(deleteResponse.getStatus(), - is(HttpURLConnection.HTTP_NO_CONTENT)); - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/HostResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/HostResourceTest.java deleted file mode 100644 index 5ac483d8..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/HostResourceTest.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - - -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.util.HashSet; -import java.util.Set; - -import com.sun.jersey.api.client.ClientResponse; -import org.hamcrest.Description; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeMatcher; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.packet.IpAddress; -import org.onlab.packet.MacAddress; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.net.DefaultHost; -import org.onosproject.net.DeviceId; -import org.onosproject.net.Host; -import org.onosproject.net.HostId; -import org.onosproject.net.HostLocation; -import org.onosproject.net.host.HostProviderRegistry; -import org.onosproject.net.host.HostProviderService; -import org.onosproject.net.host.HostService; -import org.onosproject.net.provider.ProviderId; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; - -import javax.ws.rs.core.MediaType; - -import static org.easymock.EasyMock.*; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.onlab.packet.MacAddress.valueOf; -import static org.onlab.packet.VlanId.vlanId; -import static org.onosproject.net.PortNumber.portNumber; - -/** - * Simple example on how to write a JAX-RS unit test using Jersey test framework. - * A base class should/will be created to provide further assistance for testing. - */ -public class HostResourceTest extends ResourceTest { - final HostService mockHostService = createMock(HostService.class); - final HostProviderRegistry mockHostProviderRegistry = createMock(HostProviderRegistry.class); - final HostProviderService mockHostProviderService = createMock(HostProviderService.class); - final HashSet hosts = new HashSet<>(); - - /** - * Initializes test mocks and environment. - */ - @Before - public void setUpTest() { - expect(mockHostService.getHosts()).andReturn(hosts).anyTimes(); - - // Register the services needed for the test - final CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(HostService.class, mockHostService) - .add(CodecService.class, codecService) - .add(HostProviderRegistry.class, mockHostProviderRegistry); - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Verifies mocks. - */ - @After - public void tearDownTest() { - verify(mockHostService); - } - - /** - * Hamcrest matcher to check that a host representation in JSON matches - * the actual host. - */ - public static class HostJsonMatcher extends TypeSafeMatcher { - private final Host host; - private String reason = ""; - - public HostJsonMatcher(Host hostValue) { - host = hostValue; - } - - @Override - public boolean matchesSafely(JsonObject jsonHost) { - // Check id - final String jsonId = jsonHost.get("id").asString(); - if (!jsonId.equals(host.id().toString())) { - reason = "id " + host.id().toString(); - return false; - } - - // Check vlan id - final String jsonVlanId = jsonHost.get("vlan").asString(); - if (!jsonVlanId.equals(host.vlan().toString())) { - reason = "vlan id " + host.vlan().toString(); - return false; - } - - // Check mac address - final String jsonMacAddress = jsonHost.get("mac").asString(); - if (!jsonMacAddress.equals(host.mac().toString())) { - reason = "mac address " + host.mac().toString(); - return false; - } - - // Check location element id - final JsonObject jsonLocation = jsonHost.get("location").asObject(); - final String jsonLocationElementId = jsonLocation.get("elementId").asString(); - if (!jsonLocationElementId.equals(host.location().elementId().toString())) { - reason = "location element id " + host.location().elementId().toString(); - return false; - } - - // Check location port number - final String jsonLocationPortNumber = jsonLocation.get("port").asString(); - if (!jsonLocationPortNumber.equals(host.location().port().toString())) { - reason = "location portNumber " + host.location().port().toString(); - return false; - } - - // Check Ip Addresses - final JsonArray jsonHostIps = jsonHost.get("ipAddresses").asArray(); - final Set expectedHostIps = host.ipAddresses(); - if (jsonHostIps.size() != expectedHostIps.size()) { - reason = "IP address arrays differ in size"; - return false; - } - - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate a host array matcher. - * - * @param host host object we are looking for - * @return matcher - */ - private static HostJsonMatcher matchesHost(Host host) { - return new HostJsonMatcher(host); - } - - /** - * Hamcrest matcher to check that a host is represented properly in a JSON - * array of hosts. - */ - public static class HostJsonArrayMatcher extends TypeSafeMatcher { - private final Host host; - private String reason = ""; - - public HostJsonArrayMatcher(Host hostValue) { - host = hostValue; - } - - @Override - public boolean matchesSafely(JsonArray json) { - boolean hostFound = false; - final int expectedAttributes = 5; - for (int jsonHostIndex = 0; jsonHostIndex < json.size(); - jsonHostIndex++) { - - final JsonObject jsonHost = json.get(jsonHostIndex).asObject(); - - if (jsonHost.names().size() != expectedAttributes) { - reason = "Found a host with the wrong number of attributes"; - return false; - } - - final String jsonHostId = jsonHost.get("id").asString(); - if (jsonHostId.equals(host.id().toString())) { - hostFound = true; - - // We found the correct host, check attribute values - assertThat(jsonHost, matchesHost(host)); - } - } - if (!hostFound) { - reason = "Host with id " + host.id().toString() + " not found"; - return false; - } else { - return true; - } - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate a host array matcher. - * - * @param host host object we are looking for - * @return matcher - */ - private static HostJsonArrayMatcher hasHost(Host host) { - return new HostJsonArrayMatcher(host); - } - - /** - * Tests the result of the rest api GET when there are no hosts. - */ - @Test - public void testHostsEmptyArray() { - replay(mockHostService); - WebResource rs = resource(); - String response = rs.path("hosts").get(String.class); - assertThat(response, is("{\"hosts\":[]}")); - } - - /** - * Tests the result of the rest api GET when hosts are defined. - */ - @Test - public void testHostsArray() { - replay(mockHostService); - final ProviderId pid = new ProviderId("of", "foo"); - final MacAddress mac1 = MacAddress.valueOf("00:00:11:00:00:01"); - final Set ips1 = ImmutableSet.of(IpAddress.valueOf("1111:1111:1111:1::")); - final Host host1 = - new DefaultHost(pid, HostId.hostId(mac1), valueOf(1), vlanId((short) 1), - new HostLocation(DeviceId.deviceId("1"), portNumber(11), 1), - ips1); - final MacAddress mac2 = MacAddress.valueOf("00:00:11:00:00:02"); - final Set ips2 = ImmutableSet.of( - IpAddress.valueOf("2222:2222:2222:1::"), - IpAddress.valueOf("2222:2222:2222:2::")); - final Host host2 = - new DefaultHost(pid, HostId.hostId(mac2), valueOf(2), vlanId((short) 2), - new HostLocation(DeviceId.deviceId("2"), portNumber(22), 2), - ips2); - hosts.add(host1); - hosts.add(host2); - WebResource rs = resource(); - String response = rs.path("hosts").get(String.class); - assertThat(response, containsString("{\"hosts\":[")); - - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("hosts")); - - final JsonArray hosts = result.get("hosts").asArray(); - assertThat(hosts, notNullValue()); - - assertThat(hosts, hasHost(host1)); - assertThat(hosts, hasHost(host2)); - } - - /** - * Tests fetch of one host by Id. - */ - @Test - public void testSingleHostByIdFetch() { - final ProviderId pid = new ProviderId("of", "foo"); - final MacAddress mac1 = MacAddress.valueOf("00:00:11:00:00:01"); - final Set ips1 = ImmutableSet.of(IpAddress.valueOf("1111:1111:1111:1::")); - final Host host1 = - new DefaultHost(pid, HostId.hostId(mac1), valueOf(1), vlanId((short) 1), - new HostLocation(DeviceId.deviceId("1"), portNumber(11), 1), - ips1); - - hosts.add(host1); - - expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1"))) - .andReturn(host1) - .anyTimes(); - replay(mockHostService); - - WebResource rs = resource(); - String response = rs.path("hosts/00:00:11:00:00:01%2F1").get(String.class); - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, matchesHost(host1)); - } - - /** - * Tests fetch of one host by mac and vlan. - */ - @Test - public void testSingleHostByMacAndVlanFetch() { - final ProviderId pid = new ProviderId("of", "foo"); - final MacAddress mac1 = MacAddress.valueOf("00:00:11:00:00:01"); - final Set ips1 = ImmutableSet.of(IpAddress.valueOf("1111:1111:1111:1::")); - final Host host1 = - new DefaultHost(pid, HostId.hostId(mac1), valueOf(1), vlanId((short) 1), - new HostLocation(DeviceId.deviceId("1"), portNumber(11), 1), - ips1); - - hosts.add(host1); - - expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1"))) - .andReturn(host1) - .anyTimes(); - replay(mockHostService); - - WebResource rs = resource(); - String response = rs.path("hosts/00:00:11:00:00:01/1").get(String.class); - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, matchesHost(host1)); - } - - /** - * Tests that a fetch of a non-existent object throws an exception. - */ - @Test - public void testBadGet() { - - expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1"))) - .andReturn(null) - .anyTimes(); - replay(mockHostService); - - WebResource rs = resource(); - try { - rs.path("hosts/00:00:11:00:00:01/1").get(String.class); - fail("Fetch of non-existent host did not throw an exception"); - } catch (UniformInterfaceException ex) { - assertThat(ex.getMessage(), - containsString("returned a response status of")); - } - } - - /** - * Tests post of a single host via JSON stream. - */ - @Test - public void testPost() { - mockHostProviderService.hostDetected(anyObject(), anyObject()); - expectLastCall(); - replay(mockHostProviderService); - - expect(mockHostProviderRegistry.register(anyObject())).andReturn(mockHostProviderService); - mockHostProviderRegistry.unregister(anyObject()); - expectLastCall(); - replay(mockHostProviderRegistry); - - replay(mockHostService); - - InputStream jsonStream = HostResourceTest.class - .getResourceAsStream("post-host.json"); - WebResource rs = resource(); - - ClientResponse response = rs.path("hosts") - .type(MediaType.APPLICATION_JSON_TYPE) - .post(ClientResponse.class, jsonStream); - assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); - String location = response.getLocation().getPath(); - assertThat(location, Matchers.startsWith("/hosts/11:22:33:44:55:66/-1")); - } -} - diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/IntentsResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/IntentsResourceTest.java deleted file mode 100644 index 33ee9317..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/IntentsResourceTest.java +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.util.Collections; -import java.util.HashSet; - -import javax.ws.rs.core.MediaType; - -import org.hamcrest.Description; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeMatcher; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.core.ApplicationId; -import org.onosproject.core.CoreService; -import org.onosproject.core.DefaultApplicationId; -import org.onosproject.core.IdGenerator; -import org.onosproject.net.NetworkResource; -import org.onosproject.net.intent.FakeIntentManager; -import org.onosproject.net.intent.Intent; -import org.onosproject.net.intent.IntentService; -import org.onosproject.net.intent.IntentState; -import org.onosproject.net.intent.Key; -import org.onosproject.net.intent.MockIdGenerator; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; - -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.onosproject.net.intent.IntentTestsMocks.MockIntent; - -/** - * Unit tests for Intents REST APIs. - */ -public class IntentsResourceTest extends ResourceTest { - final IntentService mockIntentService = createMock(IntentService.class); - final CoreService mockCoreService = createMock(CoreService.class); - final HashSet intents = new HashSet<>(); - private static final ApplicationId APP_ID = new DefaultApplicationId(1, "test"); - private IdGenerator mockGenerator; - - private class MockResource implements NetworkResource { - int id; - - MockResource(int id) { - this.id = id; - } - - @Override - public String toString() { - return "Resource " + Integer.toString(id); - } - } - - /** - * Hamcrest matcher to check that an intent representation in JSON matches - * the actual intent. - */ - public static class IntentJsonMatcher extends TypeSafeMatcher { - private final Intent intent; - private String reason = ""; - - public IntentJsonMatcher(Intent intentValue) { - intent = intentValue; - } - - @Override - public boolean matchesSafely(JsonObject jsonIntent) { - // check id - final String jsonId = jsonIntent.get("id").asString(); - if (!jsonId.equals(intent.id().toString())) { - reason = "id " + intent.id().toString(); - return false; - } - - // check application id - - final String jsonAppId = jsonIntent.get("appId").asString(); - final String appId = intent.appId().name(); - if (!jsonAppId.equals(appId)) { - reason = "appId was " + jsonAppId; - return false; - } - - // check intent type - final String jsonType = jsonIntent.get("type").asString(); - if (!jsonType.equals("MockIntent")) { - reason = "type MockIntent"; - return false; - } - - // check state field - final String jsonState = jsonIntent.get("state").asString(); - if (!jsonState.equals("INSTALLED")) { - reason = "state INSTALLED"; - return false; - } - - // check resources array - final JsonArray jsonResources = jsonIntent.get("resources").asArray(); - if (intent.resources() != null) { - if (intent.resources().size() != jsonResources.size()) { - reason = "resources array size of " + Integer.toString(intent.resources().size()); - return false; - } - for (final NetworkResource resource : intent.resources()) { - boolean resourceFound = false; - final String resourceString = resource.toString(); - for (int resourceIndex = 0; resourceIndex < jsonResources.size(); resourceIndex++) { - final JsonValue value = jsonResources.get(resourceIndex); - if (value.asString().equals(resourceString)) { - resourceFound = true; - } - } - if (!resourceFound) { - reason = "resource " + resourceString; - return false; - } - } - } else if (jsonResources.size() != 0) { - reason = "resources array empty"; - return false; - } - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate an intent matcher. - * - * @param intent intent object we are looking for - * @return matcher - */ - private static IntentJsonMatcher matchesIntent(Intent intent) { - return new IntentJsonMatcher(intent); - } - - /** - * Hamcrest matcher to check that an intent is represented properly in a JSON - * array of intents. - */ - public static class IntentJsonArrayMatcher extends TypeSafeMatcher { - private final Intent intent; - private String reason = ""; - - public IntentJsonArrayMatcher(Intent intentValue) { - intent = intentValue; - } - - @Override - public boolean matchesSafely(JsonArray json) { - boolean intentFound = false; - final int expectedAttributes = 5; - for (int jsonIntentIndex = 0; jsonIntentIndex < json.size(); - jsonIntentIndex++) { - - final JsonObject jsonIntent = json.get(jsonIntentIndex).asObject(); - - if (jsonIntent.names().size() != expectedAttributes) { - reason = "Found an intent with the wrong number of attributes"; - return false; - } - - final String jsonIntentId = jsonIntent.get("id").asString(); - if (jsonIntentId.equals(intent.id().toString())) { - intentFound = true; - - // We found the correct intent, check attribute values - assertThat(jsonIntent, matchesIntent(intent)); - } - } - if (!intentFound) { - reason = "Intent with id " + intent.id().toString() + " not found"; - return false; - } else { - return true; - } - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate an intent array matcher. - * - * @param intent intent object we are looking for - * @return matcher - */ - private static IntentJsonArrayMatcher hasIntent(Intent intent) { - return new IntentJsonArrayMatcher(intent); - } - - /** - * Initializes test mocks and environment. - */ - @Before - public void setUpTest() { - expect(mockIntentService.getIntents()).andReturn(intents).anyTimes(); - expect(mockIntentService.getIntentState(anyObject())) - .andReturn(IntentState.INSTALLED) - .anyTimes(); - // Register the services needed for the test - final CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(IntentService.class, mockIntentService) - .add(CodecService.class, codecService) - .add(CoreService.class, mockCoreService); - - BaseResource.setServiceDirectory(testDirectory); - - mockGenerator = new MockIdGenerator(); - Intent.bindIdGenerator(mockGenerator); - } - - /** - * Tears down and verifies test mocks and environment. - */ - @After - public void tearDownTest() { - verify(mockIntentService); - Intent.unbindIdGenerator(mockGenerator); - } - - /** - * Tests the result of the rest api GET when there are no intents. - */ - @Test - public void testIntentsEmptyArray() { - replay(mockIntentService); - final WebResource rs = resource(); - final String response = rs.path("intents").get(String.class); - assertThat(response, is("{\"intents\":[]}")); - } - - /** - * Tests the result of the rest api GET when intents are defined. - */ - @Test - public void testIntentsArray() { - replay(mockIntentService); - - final Intent intent1 = new MockIntent(1L, Collections.emptyList()); - final HashSet resources = new HashSet<>(); - resources.add(new MockResource(1)); - resources.add(new MockResource(2)); - resources.add(new MockResource(3)); - final Intent intent2 = new MockIntent(2L, resources); - - intents.add(intent1); - intents.add(intent2); - final WebResource rs = resource(); - final String response = rs.path("intents").get(String.class); - assertThat(response, containsString("{\"intents\":[")); - - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("intents")); - - final JsonArray jsonIntents = result.get("intents").asArray(); - assertThat(jsonIntents, notNullValue()); - - assertThat(jsonIntents, hasIntent(intent1)); - assertThat(jsonIntents, hasIntent(intent2)); - } - - /** - * Tests the result of a rest api GET for a single intent. - */ - @Test - public void testIntentsSingle() { - final HashSet resources = new HashSet<>(); - resources.add(new MockResource(1)); - resources.add(new MockResource(2)); - resources.add(new MockResource(3)); - final Intent intent = new MockIntent(3L, resources); - - intents.add(intent); - - expect(mockIntentService.getIntent(Key.of(0, APP_ID))) - .andReturn(intent) - .anyTimes(); - expect(mockIntentService.getIntent(Key.of("0", APP_ID))) - .andReturn(intent) - .anyTimes(); - expect(mockIntentService.getIntent(Key.of(0, APP_ID))) - .andReturn(intent) - .anyTimes(); - expect(mockIntentService.getIntent(Key.of("0x0", APP_ID))) - .andReturn(null) - .anyTimes(); - replay(mockIntentService); - expect(mockCoreService.getAppId(APP_ID.name())) - .andReturn(APP_ID).anyTimes(); - replay(mockCoreService); - final WebResource rs = resource(); - - // Test get using key string - final String response = rs.path("intents/" + APP_ID.name() - + "/0").get(String.class); - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, matchesIntent(intent)); - - // Test get using numeric value - final String responseNumeric = rs.path("intents/" + APP_ID.name() - + "/0x0").get(String.class); - final JsonObject resultNumeric = JsonObject.readFrom(responseNumeric); - assertThat(resultNumeric, matchesIntent(intent)); - } - - /** - * Tests that a fetch of a non-existent intent object throws an exception. - */ - @Test - public void testBadGet() { - - expect(mockIntentService.getIntent(Key.of(0, APP_ID))) - .andReturn(null) - .anyTimes(); - replay(mockIntentService); - - WebResource rs = resource(); - try { - rs.path("intents/0").get(String.class); - fail("Fetch of non-existent intent did not throw an exception"); - } catch (UniformInterfaceException ex) { - assertThat(ex.getMessage(), - containsString("returned a response status of")); - } - } - - /** - * Tests creating an intent with POST. - */ - @Test - public void testPost() { - ApplicationId testId = new DefaultApplicationId(2, "myApp"); - expect(mockCoreService.getAppId("myApp")) - .andReturn(testId); - replay(mockCoreService); - - mockIntentService.submit(anyObject()); - expectLastCall(); - replay(mockIntentService); - - InputStream jsonStream = IntentsResourceTest.class - .getResourceAsStream("post-intent.json"); - WebResource rs = resource(); - - ClientResponse response = rs.path("intents") - .type(MediaType.APPLICATION_JSON_TYPE) - .post(ClientResponse.class, jsonStream); - assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED)); - String location = response.getLocation().getPath(); - assertThat(location, Matchers.startsWith("/intents/myApp/")); - } - - /** - * Tests creating an intent with POST and illegal JSON. - */ - @Test - public void testBadPost() { - replay(mockCoreService); - replay(mockIntentService); - - String json = "this is invalid!"; - WebResource rs = resource(); - - ClientResponse response = rs.path("intents") - .type(MediaType.APPLICATION_JSON_TYPE) - .post(ClientResponse.class, json); - assertThat(response.getStatus(), is(HttpURLConnection.HTTP_BAD_REQUEST)); - } - - /** - * Tests removing an intent with DELETE. - */ - @Test - public void testRemove() { - final HashSet resources = new HashSet<>(); - resources.add(new MockResource(1)); - resources.add(new MockResource(2)); - resources.add(new MockResource(3)); - final Intent intent = new MockIntent(3L, resources); - final ApplicationId appId = new DefaultApplicationId(2, "app"); - IntentService fakeManager = new FakeIntentManager(); - - expect(mockCoreService.getAppId("app")) - .andReturn(appId).once(); - replay(mockCoreService); - - mockIntentService.withdraw(anyObject()); - expectLastCall().andDelegateTo(fakeManager).once(); - expect(mockIntentService.getIntent(Key.of(2, appId))) - .andReturn(intent) - .once(); - expect(mockIntentService.getIntent(Key.of("0x2", appId))) - .andReturn(null) - .once(); - - mockIntentService.addListener(anyObject()); - expectLastCall().andDelegateTo(fakeManager).once(); - mockIntentService.removeListener(anyObject()); - expectLastCall().andDelegateTo(fakeManager).once(); - - replay(mockIntentService); - - WebResource rs = resource(); - - ClientResponse response = rs.path("intents/app/0x2") - .type(MediaType.APPLICATION_JSON_TYPE) - .delete(ClientResponse.class); - assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT)); - } - - /** - * Tests removal of a non existent intent with DELETE. - */ - @Test - public void testBadRemove() { - final ApplicationId appId = new DefaultApplicationId(2, "app"); - - expect(mockCoreService.getAppId("app")) - .andReturn(appId).once(); - replay(mockCoreService); - - expect(mockIntentService.getIntent(Key.of(2, appId))) - .andReturn(null) - .once(); - expect(mockIntentService.getIntent(Key.of("0x2", appId))) - .andReturn(null) - .once(); - - replay(mockIntentService); - - WebResource rs = resource(); - - ClientResponse response = rs.path("intents/app/0x2") - .type(MediaType.APPLICATION_JSON_TYPE) - .delete(ClientResponse.class); - assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT)); - } - -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/LinksResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/LinksResourceTest.java deleted file mode 100644 index feff0ed0..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/LinksResourceTest.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.net.ConnectPoint; -import org.onosproject.net.DeviceId; -import org.onosproject.net.Link; -import org.onosproject.net.link.LinkService; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.WebResource; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.onosproject.net.NetTestTools.link; - -/** - * Unit tests for links REST APIs. - */ -public class LinksResourceTest extends ResourceTest { - LinkService mockLinkService; - - Link link1 = link("src1", 1, "dst1", 1); - Link link2 = link("src2", 2, "dst2", 2); - Link link3 = link("src3", 3, "dst3", 3); - - /** - * Hamcrest matcher to check that an link representation in JSON matches - * the actual link. - */ - public static class LinkJsonMatcher extends TypeSafeMatcher { - private final Link link; - private String reason = ""; - - public LinkJsonMatcher(Link linkValue) { - link = linkValue; - } - - @Override - public boolean matchesSafely(JsonObject jsonLink) { - JsonObject jsonSrc = jsonLink.get("src").asObject(); - String jsonSrcDevice = jsonSrc.get("device").asString(); - String jsonSrcPort = jsonSrc.get("port").asString(); - - JsonObject jsonDst = jsonLink.get("dst").asObject(); - String jsonDstDevice = jsonDst.get("device").asString(); - String jsonDstPort = jsonDst.get("port").asString(); - - return jsonSrcDevice.equals(link.src().deviceId().toString()) && - jsonSrcPort.equals(link.src().port().toString()) && - jsonDstDevice.equals(link.dst().deviceId().toString()) && - jsonDstPort.equals(link.dst().port().toString()); - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate an link matcher. - * - * @param link link object we are looking for - * @return matcher - */ - private static LinkJsonMatcher matchesLink(Link link) { - return new LinkJsonMatcher(link); - } - - /** - * Hamcrest matcher to check that an link is represented properly in a JSON - * array of links. - */ - private static class LinkJsonArrayMatcher extends TypeSafeMatcher { - private final Link link; - private String reason = ""; - - public LinkJsonArrayMatcher(Link linkValue) { - link = linkValue; - } - - @Override - public boolean matchesSafely(JsonArray json) { - final int expectedAttributes = 2; - - for (int jsonLinkIndex = 0; jsonLinkIndex < json.size(); - jsonLinkIndex++) { - - JsonObject jsonLink = json.get(jsonLinkIndex).asObject(); - - if (matchesLink(link).matchesSafely(jsonLink)) { - return true; - } - } - return false; - } - - @Override - public void describeTo(Description description) { - description.appendText(reason); - } - } - - /** - * Factory to allocate an link array matcher. - * - * @param link link object we are looking for - * @return matcher - */ - private static LinkJsonArrayMatcher hasLink(Link link) { - return new LinkJsonArrayMatcher(link); - } - - /** - * Initializes test mocks and environment. - */ - @Before - public void setUpTest() { - mockLinkService = createMock(LinkService.class); - - // Register the services needed for the test - CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(LinkService.class, mockLinkService) - .add(CodecService.class, codecService); - - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Tears down and verifies test mocks and environment. - */ - @After - public void tearDownTest() { - verify(mockLinkService); - } - - /** - * Tests the result of the rest api GET when there are no links. - */ - @Test - public void testLinksEmptyArray() { - expect(mockLinkService.getLinks()).andReturn(ImmutableList.of()); - replay(mockLinkService); - - WebResource rs = resource(); - String response = rs.path("links").get(String.class); - assertThat(response, is("{\"links\":[]}")); - } - - /** - * Tests the result of the rest api GET when there are links present. - */ - @Test - public void testLinks() { - expect(mockLinkService.getLinks()) - .andReturn(ImmutableList.of(link1, link2, link3)) - .anyTimes(); - - replay(mockLinkService); - - WebResource rs = resource(); - String response = rs.path("links").get(String.class); - assertThat(response, containsString("{\"links\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("links")); - - JsonArray jsonLinks = result.get("links").asArray(); - assertThat(jsonLinks, notNullValue()); - assertThat(jsonLinks.size(), is(3)); - - assertThat(jsonLinks, hasLink(link1)); - assertThat(jsonLinks, hasLink(link2)); - assertThat(jsonLinks, hasLink(link3)); - } - - /** - * Tests the result of the rest api GET of links for a specific device. - */ - @Test - public void testLinksByDevice() { - expect(mockLinkService.getDeviceLinks(isA(DeviceId.class))) - .andReturn(ImmutableSet.of(link2)) - .anyTimes(); - - replay(mockLinkService); - - WebResource rs = resource(); - String response = rs - .path("links") - .queryParam("device", "src2") - .get(String.class); - assertThat(response, containsString("{\"links\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("links")); - - JsonArray jsonLinks = result.get("links").asArray(); - assertThat(jsonLinks, notNullValue()); - assertThat(jsonLinks.size(), is(1)); - - assertThat(jsonLinks, hasLink(link2)); - } - - /** - * Tests the result of the rest api GET of links for a specific device - * and port. - */ - @Test - public void testLinksByDevicePort() { - - expect(mockLinkService.getLinks(isA(ConnectPoint.class))) - .andReturn(ImmutableSet.of(link2)) - .anyTimes(); - - replay(mockLinkService); - - WebResource rs = resource(); - String response = rs - .path("links") - .queryParam("device", "src2") - .queryParam("port", "2") - .get(String.class); - assertThat(response, containsString("{\"links\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("links")); - - JsonArray jsonLinks = result.get("links").asArray(); - assertThat(jsonLinks, notNullValue()); - assertThat(jsonLinks.size(), is(1)); - - assertThat(jsonLinks, hasLink(link2)); - } - - /** - * Tests the result of the rest api GET of links for a specific - * device, port, and direction. - */ - @Test - public void testLinksByDevicePortDirection() { - - expect(mockLinkService.getIngressLinks(isA(ConnectPoint.class))) - .andReturn(ImmutableSet.of(link2)) - .anyTimes(); - - replay(mockLinkService); - - WebResource rs = resource(); - String response = rs - .path("links") - .queryParam("device", "src2") - .queryParam("port", "2") - .queryParam("direction", "INGRESS") - .get(String.class); - assertThat(response, containsString("{\"links\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("links")); - - JsonArray jsonLinks = result.get("links").asArray(); - assertThat(jsonLinks, notNullValue()); - assertThat(jsonLinks.size(), is(1)); - - assertThat(jsonLinks, hasLink(link2)); - } - - /** - * Tests the result of the rest api GET of links for a specific - * device and direction. - */ - @Test - public void testLinksByDeviceDirection() { - - expect(mockLinkService.getDeviceIngressLinks(isA(DeviceId.class))) - .andReturn(ImmutableSet.of(link2)) - .anyTimes(); - - replay(mockLinkService); - - WebResource rs = resource(); - String response = rs - .path("links") - .queryParam("device", "src2") - .queryParam("direction", "INGRESS") - .get(String.class); - assertThat(response, containsString("{\"links\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("links")); - - JsonArray jsonLinks = result.get("links").asArray(); - assertThat(jsonLinks, notNullValue()); - assertThat(jsonLinks.size(), is(1)); - - assertThat(jsonLinks, hasLink(link2)); - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/PathsResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/PathsResourceTest.java deleted file mode 100644 index 19b5f2ad..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/PathsResourceTest.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Set; - -import org.hamcrest.Description; -import org.hamcrest.TypeSafeDiagnosingMatcher; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.net.ElementId; -import org.onosproject.net.Link; -import org.onosproject.net.Path; -import org.onosproject.net.topology.PathService; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.WebResource; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.onosproject.net.NetTestTools.createPath; -import static org.onosproject.net.NetTestTools.did; -import static org.onosproject.net.NetTestTools.hid; - -/** - * Unit tests for paths REST APIs. - */ -public class PathsResourceTest extends ResourceTest { - Path path1 = createPath("dev1", "dev2"); - Path path2 = createPath("dev2", "dev3"); - Set paths = ImmutableSet.of(path1, path2); - - final PathService mockPathService = createMock(PathService.class); - - /** - * Hamcrest matcher for a path and its JSON representation. - */ - private final class PathJsonMatcher extends TypeSafeDiagnosingMatcher { - - private final Path path; - - /** - * Creates the matcher. - * - * @param pathValue the path object to match - */ - private PathJsonMatcher(Path pathValue) { - path = pathValue; - } - - @Override - public boolean matchesSafely(JsonObject pathJson, Description description) { - - double jsonCost = pathJson.get("cost").asDouble(); - if (jsonCost != path.cost()) { - description.appendText("src device was " + jsonCost); - return false; - } - - JsonArray jsonLinks = pathJson.get("links").asArray(); - assertThat(jsonLinks.size(), is(path.links().size())); - - for (int linkIndex = 0; linkIndex < jsonLinks.size(); linkIndex++) { - Link link = path.links().get(linkIndex); - JsonObject jsonLink = jsonLinks.get(0).asObject(); - - JsonObject jsonLinkSrc = jsonLink.get("src").asObject(); - String srcDevice = jsonLinkSrc.get("device").asString(); - if (!srcDevice.equals(link.src().deviceId().toString())) { - description.appendText("src device was " + jsonLinkSrc); - return false; - } - - JsonObject jsonLinkDst = jsonLink.get("dst").asObject(); - String dstDevice = jsonLinkDst.get("device").asString(); - if (!dstDevice.equals(link.dst().deviceId().toString())) { - description.appendText("dst device was " + jsonLinkDst); - return false; - } - } - - return true; - } - - @Override - public void describeTo(Description description) { - description.appendText(path.toString()); - } - } - - /** - * Factory to allocate an connect point matcher. - * - * @param path path object we are looking for - * @return matcher - */ - private PathJsonMatcher matchesPath(Path path) { - return new PathJsonMatcher(path); - } - - /** - * Initializes test mocks and environment. - */ - @Before - public void setUpTest() { - - // Register the services needed for the test - CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(PathService.class, mockPathService) - .add(CodecService.class, codecService); - - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Tears down test mocks and environment. - */ - @After - public void tearDownTest() { - verify(mockPathService); - } - - /** - * Tests a REST path GET for the given endpoints. - * - * @param srcElement source element of the path - * @param dstElement destination element of the path - * - * @throws UnsupportedEncodingException - */ - private void runTest(ElementId srcElement, ElementId dstElement) - throws UnsupportedEncodingException { - expect(mockPathService.getPaths(srcElement, dstElement)) - .andReturn(paths) - .once(); - replay(mockPathService); - - String srcId = URLEncoder.encode(srcElement.toString(), - StandardCharsets.UTF_8.name()); - String dstId = URLEncoder.encode(dstElement.toString(), - StandardCharsets.UTF_8.name()); - - String url = "paths/" + srcId + "/" + dstId; - WebResource rs = resource(); - String response = rs.path(url).get(String.class); - assertThat(response, containsString("{\"paths\":[")); - - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("paths")); - - JsonArray jsonPaths = result.get("paths").asArray(); - assertThat(jsonPaths, notNullValue()); - assertThat(jsonPaths.size(), is(2)); - - JsonObject path1Json = jsonPaths.get(0).asObject(); - assertThat(path1Json, matchesPath(path1)); - - JsonObject path2Json = jsonPaths.get(1).asObject(); - assertThat(path2Json, matchesPath(path2)); - } - - /** - * Tests a path between two hosts. - * - * @throws UnsupportedEncodingException if UTF-8 not found - */ - @Test - public void hostToHost() throws UnsupportedEncodingException { - runTest(hid("01:23:45:67:89:AB/2"), hid("AB:89:67:45:23:01/4")); - } - - /** - * Tests a path with a host as the source and a switch as the destination. - * - * @throws UnsupportedEncodingException if UTF-8 not found - */ - @Test - public void hostToDevice() throws UnsupportedEncodingException { - runTest(hid("01:23:45:67:89:AB/2"), did("switch1")); - } - - /** - * Tests a path with a switch as the source and a host as the destination. - * - * @throws UnsupportedEncodingException if UTF-8 not found - */ - @Test - public void deviceToHost() throws UnsupportedEncodingException { - runTest(did("switch1"), hid("01:23:45:67:89:AB/2")); - } - - /** - * Tests a path between two switches. - * - * @throws UnsupportedEncodingException if UTF-8 not found - */ - @Test - public void deviceToDevice() throws UnsupportedEncodingException { - runTest(did("switch1"), did("switch2")); - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ResourceTest.java deleted file mode 100644 index d88b84a6..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/ResourceTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import java.io.IOException; -import java.net.ServerSocket; - -import com.sun.jersey.test.framework.AppDescriptor; -import com.sun.jersey.test.framework.JerseyTest; -import com.sun.jersey.test.framework.WebAppDescriptor; - -/** - * Base class for REST API tests. Performs common configuration operations. - */ -public class ResourceTest extends JerseyTest { - - /** - * Assigns an available port for the test. - * - * @param defaultPort If a port cannot be determined, this one is used. - * @return free port - */ - @Override - public int getPort(int defaultPort) { - try { - ServerSocket socket = new ServerSocket(0); - socket.setReuseAddress(true); - int port = socket.getLocalPort(); - socket.close(); - return port; - } catch (IOException ioe) { - return defaultPort; - } - } - - @Override - public AppDescriptor configure() { - return new WebAppDescriptor.Builder("org.onosproject.rest").build(); - } - -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/StatisticsResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/StatisticsResourceTest.java deleted file mode 100644 index af64224d..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/StatisticsResourceTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import java.util.HashMap; -import java.util.stream.IntStream; - -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.net.Link; -import org.onosproject.net.link.LinkService; -import org.onosproject.net.statistic.DefaultLoad; -import org.onosproject.net.statistic.StatisticService; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.WebResource; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.onosproject.net.NetTestTools.connectPoint; -import static org.onosproject.net.NetTestTools.link; - -/** - * Unit tests for statistics REST APIs. - */ -public class StatisticsResourceTest extends ResourceTest { - - Link link1 = link("src1", 1, "dst1", 1); - Link link2 = link("src2", 2, "dst2", 2); - Link link3 = link("src3", 3, "dst3", 3); - - LinkService mockLinkService; - StatisticService mockStatisticService; - - /** - * Initializes test mocks and environment. - */ - @Before - public void setUpTest() { - mockLinkService = createMock(LinkService.class); - expect(mockLinkService.getLinks()) - .andReturn(ImmutableList.of(link1, link2, link3)); - expect(mockLinkService.getLinks(connectPoint("0000000000000001", 2))) - .andReturn(ImmutableSet.of(link3)); - - mockStatisticService = createMock(StatisticService.class); - expect(mockStatisticService.load(link1)) - .andReturn(new DefaultLoad(2, 1, 1)); - expect(mockStatisticService.load(link2)) - .andReturn(new DefaultLoad(22, 11, 1)); - expect(mockStatisticService.load(link3)) - .andReturn(new DefaultLoad(222, 111, 1)); - - replay(mockLinkService, mockStatisticService); - - // Register the services needed for the test - CodecManager codecService = new CodecManager(); - codecService.activate(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(LinkService.class, mockLinkService) - .add(StatisticService.class, mockStatisticService) - .add(CodecService.class, codecService); - - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Checks that the values in a JSON representation of a Load are - * correct. - * - * @param load JSON for the Loan object - * @param rate expected vale fo rate - * @param latest expected value for latest - * @param valid expected value for valid flag - * @param device expected device ID - */ - private void checkValues(JsonObject load, int rate, int latest, - boolean valid, String device) { - assertThat(load, notNullValue()); - assertThat(load.get("rate").asInt(), is(rate)); - assertThat(load.get("latest").asInt(), is(latest)); - assertThat(load.get("valid").asBoolean(), is(valid)); - assertThat(load.get("time").asLong(), - lessThanOrEqualTo((System.currentTimeMillis()))); - assertThat(load.get("link").asString(), - containsString("device=of:" + device)); - } - - /** - * Tests GET of a single Load statistics object. - */ - @Test - public void testSingleLoadGet() { - final WebResource rs = resource(); - final String response = rs.path("statistics/flows/link") - .queryParam("device", "of:0000000000000001") - .queryParam("port", "2") - .get(String.class); - - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("loads")); - - final JsonArray jsonLoads = result.get("loads").asArray(); - assertThat(jsonLoads, notNullValue()); - assertThat(jsonLoads.size(), is(1)); - - JsonObject load1 = jsonLoads.get(0).asObject(); - checkValues(load1, 111, 222, true, "src3"); - } - - /** - * Tests GET of all Load statistics objects. - */ - @Test - public void testLoadsGet() { - final WebResource rs = resource(); - final String response = rs.path("statistics/flows/link/").get(String.class); - - final JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - assertThat(result.names().get(0), is("loads")); - - final JsonArray jsonLoads = result.get("loads").asArray(); - assertThat(jsonLoads, notNullValue()); - assertThat(jsonLoads.size(), is(3)); - - // Hash the loads by the current field to allow easy lookup if the - // order changes. - HashMap currentMap = new HashMap<>(); - IntStream.range(0, jsonLoads.size()) - .forEach(index -> currentMap.put( - jsonLoads.get(index).asObject().get("latest").asInt(), - jsonLoads.get(index).asObject())); - - JsonObject load1 = currentMap.get(2); - checkValues(load1, 1, 2, true, "src1"); - - JsonObject load2 = currentMap.get(22); - checkValues(load2, 11, 22, true, "src2"); - - JsonObject load3 = currentMap.get(222); - checkValues(load3, 111, 222, true, "src3"); - - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/TopologyResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/TopologyResourceTest.java deleted file mode 100644 index da5f9690..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/TopologyResourceTest.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest; - -import java.util.Set; - -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.codec.CodecService; -import org.onosproject.codec.impl.CodecManager; -import org.onosproject.net.ConnectPoint; -import org.onosproject.net.DeviceId; -import org.onosproject.net.Link; -import org.onosproject.net.provider.ProviderId; -import org.onosproject.net.topology.ClusterId; -import org.onosproject.net.topology.DefaultTopologyCluster; -import org.onosproject.net.topology.DefaultTopologyVertex; -import org.onosproject.net.topology.Topology; -import org.onosproject.net.topology.TopologyCluster; -import org.onosproject.net.topology.TopologyService; -import org.onosproject.net.topology.TopologyServiceAdapter; - -import com.eclipsesource.json.JsonArray; -import com.eclipsesource.json.JsonObject; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.WebResource; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.onosproject.net.NetTestTools.did; -import static org.onosproject.net.NetTestTools.link; - -/** - * Unit tests for Topology REST APIs. - */ -public class TopologyResourceTest extends ResourceTest { - - private static class MockTopology implements Topology { - @Override - public long time() { - return 11111L; - } - - @Override - public long creationTime() { - return 22222L; - } - - @Override - public long computeCost() { - return 0; - } - - @Override - public int clusterCount() { - return 2; - } - - @Override - public int deviceCount() { - return 6; - } - - @Override - public int linkCount() { - return 4; - } - - @Override - public ProviderId providerId() { - return ProviderId.NONE; - } - } - - private static class MockTopologyService extends TopologyServiceAdapter { - final DefaultTopologyVertex root = new DefaultTopologyVertex(did("rootnode")); - final Topology topology = new MockTopology(); - final TopologyCluster cluster1 = - new DefaultTopologyCluster(ClusterId.clusterId(0), - 2, 1, root); - final TopologyCluster cluster2 = - new DefaultTopologyCluster(ClusterId.clusterId(1), - 4, 3, root); - - @Override - public Topology currentTopology() { - return topology; - } - - @Override - public Set getClusters(Topology topology) { - return ImmutableSet.of(cluster1, cluster2); - } - - @Override - public TopologyCluster getCluster(Topology topology, ClusterId clusterId) { - return cluster1; - } - - @Override - public Set getClusterDevices(Topology topology, TopologyCluster cluster) { - DeviceId device1 = did("dev1"); - DeviceId device2 = did("dev2"); - - return ImmutableSet.of(device1, device2); - } - - @Override - public Set getClusterLinks(Topology topology, TopologyCluster cluster) { - Link link1 = link("src1", 1, "dst1", 1); - Link link2 = link("src2", 1, "dst2", 1); - Link link3 = link("src3", 1, "dst3", 1); - return ImmutableSet.of(link1, link2, link3); - } - - @Override - public boolean isInfrastructure(Topology topology, ConnectPoint connectPoint) { - return connectPoint.elementId().toString().equals("dev2"); - } - - @Override - public boolean isBroadcastPoint(Topology topology, ConnectPoint connectPoint) { - return connectPoint.elementId().toString().equals("dev1"); - } - - } - - /** - * Initializes the test harness. - */ - @Before - public void setUpTest() { - TopologyService topologyService = new MockTopologyService(); - CodecManager codecService = new CodecManager(); - codecService.activate(); - - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(TopologyService.class, topologyService) - .add(CodecService.class, codecService); - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Tests the topology overview. - */ - @Test - public void getTopology() { - WebResource rs = resource(); - String response = rs.path("topology").get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(4)); - - assertThat(result.get("time").asLong(), is(11111L)); - assertThat(result.get("clusters").asLong(), is(2L)); - assertThat(result.get("devices").asLong(), is(6L)); - assertThat(result.get("links").asLong(), is(4L)); - } - - /** - * Tests the clusters overview. - */ - @Test - public void getTopologyClusters() { - WebResource rs = resource(); - String response = rs.path("topology/clusters").get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.names(), hasSize(1)); - JsonArray clusters = result.get("clusters").asArray(); - assertThat(clusters, notNullValue()); - assertThat(clusters.size(), is(2)); - } - - /** - * Tests an individual cluster overview. - */ - @Test - public void getCluster() { - WebResource rs = resource(); - String response = rs.path("topology/clusters/0").get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.get("id").asLong(), is(0L)); - assertThat(result.get("deviceCount").asLong(), is(2L)); - assertThat(result.get("linkCount").asLong(), is(1L)); - assertThat(result.get("root").asString(), containsString("rootnode")); - - assertThat(result.names(), hasSize(4)); - } - - /** - * Tests an individual cluster's devices list. - */ - @Test - public void getClusterDevices() { - WebResource rs = resource(); - String response = rs.path("topology/clusters/0/devices").get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - JsonArray devices = result.get("devices").asArray(); - assertThat(devices.size(), is(2)); - - assertThat(devices.get(0).asString(), is("of:dev1")); - assertThat(devices.get(1).asString(), is("of:dev2")); - } - - /** - * Tests an individual cluster's links list. - */ - @Test - public void getClusterLinks() { - WebResource rs = resource(); - String response = rs.path("topology/clusters/1/links").get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - JsonArray links = result.get("links").asArray(); - assertThat(links.size(), is(3)); - - JsonObject link0 = links.get(0).asObject(); - JsonObject src0 = link0.get("src").asObject(); - String device0 = src0.get("device").asString(); - assertThat(device0, is("of:src1")); - - JsonObject link2 = links.get(2).asObject(); - JsonObject src2 = link2.get("src").asObject(); - String device2 = src2.get("device").asString(); - assertThat(device2, is("of:src3")); - } - - /** - * Tests a broadcast query. - */ - @Test - public void getBroadcast() { - WebResource rs = resource(); - String response = rs.path("topology/broadcast/dev1:1").get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.get("broadcast").asBoolean(), is(true)); - } - - /** - * Tests an infrastructure query. - */ - @Test - public void getInfrastructure() { - WebResource rs = resource(); - String response = rs.path("topology/infrastructure/dev2:1").get(String.class); - JsonObject result = JsonObject.readFrom(response); - assertThat(result, notNullValue()); - - assertThat(result.get("infrastructure").asBoolean(), is(true)); - } -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/exceptions/ExceptionMapperTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/exceptions/ExceptionMapperTest.java deleted file mode 100644 index 779966a2..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/exceptions/ExceptionMapperTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest.exceptions; - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Set of tests for the various exception mappers. - */ -public class ExceptionMapperTest { - - @Test - public void emptyMessage() { - RuntimeException exception = new NullPointerException(); - ServerErrorMapper mapper = new ServerErrorMapper(); - Object response = mapper.toResponse(exception).getEntity(); - assertTrue("incorrect response", - response.toString().contains("ExceptionMapperTest.emptyMessage(")); - } -} \ No newline at end of file diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java deleted file mode 100644 index 2b341af2..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.rest.resources; - -import java.net.HttpURLConnection; -import java.util.HashSet; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.onlab.osgi.ServiceDirectory; -import org.onlab.osgi.TestServiceDirectory; -import org.onlab.rest.BaseResource; -import org.onosproject.net.DefaultDevice; -import org.onosproject.net.Device; -import org.onosproject.net.Link; -import org.onosproject.net.config.Config; -import org.onosproject.net.config.NetworkConfigService; -import org.onosproject.net.config.NetworkConfigServiceAdapter; -import org.onosproject.net.config.SubjectFactory; -import org.onosproject.rest.ResourceTest; - -import com.eclipsesource.json.JsonObject; -import com.eclipsesource.json.JsonValue; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.ImmutableSet; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.replay; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.fail; - -/** - * Unit tests for network config web resource. - */ -public class NetworkConfigWebResourceTest extends ResourceTest { - - MockNetworkConfigService mockNetworkConfigService; - - public class MockDeviceConfig extends Config { - - final String field1Value; - final String field2Value; - - MockDeviceConfig(String value1, String value2) { - field1Value = value1; - field2Value = value2; - } - - @Override - public String key() { - return "basic"; - } - - @Override - public JsonNode node() { - return new ObjectMapper() - .createObjectNode() - .put("field1", field1Value) - .put("field2", field2Value); - } - } - - /** - * Mock config factory for devices. - */ - private final SubjectFactory mockDevicesSubjectFactory = - new SubjectFactory(Device.class, "devices") { - @Override - public Device createSubject(String subjectKey) { - DefaultDevice device = createMock(DefaultDevice.class); - replay(device); - return device; - } - - @Override - public Class subjectClass() { - return Device.class; - } - }; - - /** - * Mock config factory for links. - */ - private final SubjectFactory mockLinksSubjectFactory = - new SubjectFactory(Link.class, "links") { - @Override - public Link createSubject(String subjectKey) { - return null; - } - - @Override - public Class subjectClass() { - return Link.class; - } - }; - - /** - * Mocked config service. - */ - class MockNetworkConfigService extends NetworkConfigServiceAdapter { - - Set devicesSubjects = new HashSet<>(); - Set devicesConfigs = new HashSet<>(); - Set linksSubjects = new HashSet(); - Set linksConfigs = new HashSet<>(); - - @Override - public Set getSubjectClasses() { - return ImmutableSet.of(Device.class, Link.class); - } - - @Override - public SubjectFactory getSubjectFactory(Class subjectClass) { - if (subjectClass == Device.class) { - return mockDevicesSubjectFactory; - } else if (subjectClass == Link.class) { - return mockLinksSubjectFactory; - } - return null; - } - - @Override - public SubjectFactory getSubjectFactory(String subjectClassKey) { - if (subjectClassKey.equals("devices")) { - return mockDevicesSubjectFactory; - } else if (subjectClassKey.equals("links")) { - return mockLinksSubjectFactory; - } - return null; - } - - @SuppressWarnings("unchecked") - @Override - public Set getSubjects(Class subjectClass) { - if (subjectClass == Device.class) { - return devicesSubjects; - } else if (subjectClass == Link.class) { - return linksSubjects; - } - return null; - } - - @SuppressWarnings("unchecked") - @Override - public Set> getConfigs(S subject) { - if (subject instanceof Device || subject.toString().contains("device")) { - return devicesConfigs; - } else if (subject.toString().contains("link")) { - return linksConfigs; - } - return null; - } - - @SuppressWarnings("unchecked") - @Override - public > C getConfig(S subject, Class configClass) { - - if (configClass == MockDeviceConfig.class) { - return (C) devicesConfigs.toArray()[0]; - } - return null; - } - - @Override - public Class getConfigClass(String subjectClassKey, String configKey) { - return MockDeviceConfig.class; - } - } - - /** - * Sets up mocked config service. - */ - @Before - public void setUp() { - mockNetworkConfigService = new MockNetworkConfigService(); - ServiceDirectory testDirectory = - new TestServiceDirectory() - .add(NetworkConfigService.class, mockNetworkConfigService); - BaseResource.setServiceDirectory(testDirectory); - } - - /** - * Sets up test config data. - */ - @SuppressWarnings("unchecked") - public void setUpConfigData() { - mockNetworkConfigService.devicesSubjects.add("device1"); - mockNetworkConfigService.devicesConfigs.add(new MockDeviceConfig("v1", "v2")); - } - - /** - * Tests the result of the rest api GET when there are no configs. - */ - @Test - public void testEmptyConfigs() { - final WebResource rs = resource(); - final String response = rs.path("network/configuration").get(String.class); - - assertThat(response, containsString("\"devices\":{}")); - assertThat(response, containsString("\"links\":{}")); - } - - /** - * Tests the result of the rest api GET for a single subject with no configs. - */ - @Test - public void testEmptyConfig() { - final WebResource rs = resource(); - final String response = rs.path("network/configuration/devices").get(String.class); - - assertThat(response, is("{}")); - } - - /** - * Tests the result of the rest api GET for a single subject that - * is undefined. - */ - @Test - public void testNonExistentConfig() { - final WebResource rs = resource(); - - try { - final String response = rs.path("network/configuration/nosuchkey").get(String.class); - fail("GET of non-existent key does not produce an exception " + response); - } catch (UniformInterfaceException e) { - assertThat(e.getResponse().getStatus(), is(HttpURLConnection.HTTP_NOT_FOUND)); - } - } - - private void checkBasicAttributes(JsonValue basic) { - Assert.assertThat(basic.asObject().get("field1").asString(), is("v1")); - Assert.assertThat(basic.asObject().get("field2").asString(), is("v2")); - } - - /** - * Tests the result of the rest api GET when there is a config. - */ - @Test - - public void testConfigs() { - setUpConfigData(); - final WebResource rs = resource(); - final String response = rs.path("network/configuration").get(String.class); - - final JsonObject result = JsonObject.readFrom(response); - Assert.assertThat(result, notNullValue()); - - Assert.assertThat(result.names(), hasSize(2)); - - JsonValue devices = result.get("devices"); - Assert.assertThat(devices, notNullValue()); - - JsonValue device1 = devices.asObject().get("device1"); - Assert.assertThat(device1, notNullValue()); - - JsonValue basic = device1.asObject().get("basic"); - Assert.assertThat(basic, notNullValue()); - - checkBasicAttributes(basic); - } - - /** - * Tests the result of the rest api single subject key GET when - * there is a config. - */ - @Test - public void testSingleSubjectKeyConfig() { - setUpConfigData(); - final WebResource rs = resource(); - final String response = rs.path("network/configuration/devices").get(String.class); - - final JsonObject result = JsonObject.readFrom(response); - Assert.assertThat(result, notNullValue()); - - Assert.assertThat(result.names(), hasSize(1)); - - JsonValue device1 = result.asObject().get("device1"); - Assert.assertThat(device1, notNullValue()); - - JsonValue basic = device1.asObject().get("basic"); - Assert.assertThat(basic, notNullValue()); - - checkBasicAttributes(basic); - } - - /** - * Tests the result of the rest api single subject GET when - * there is a config. - */ - @Test - public void testSingleSubjectConfig() { - setUpConfigData(); - final WebResource rs = resource(); - final String response = - rs.path("network/configuration/devices/device1") - .get(String.class); - - final JsonObject result = JsonObject.readFrom(response); - Assert.assertThat(result, notNullValue()); - - Assert.assertThat(result.names(), hasSize(1)); - - JsonValue basic = result.asObject().get("basic"); - Assert.assertThat(basic, notNullValue()); - - checkBasicAttributes(basic); - } - - /** - * Tests the result of the rest api single subject single config GET when - * there is a config. - */ - @Test - public void testSingleSubjectSingleConfig() { - setUpConfigData(); - final WebResource rs = resource(); - final String response = - rs.path("network/configuration/devices/device1/basic") - .get(String.class); - - final JsonObject result = JsonObject.readFrom(response); - Assert.assertThat(result, notNullValue()); - - Assert.assertThat(result.names(), hasSize(2)); - - checkBasicAttributes(result); - } - - // TODO: Add test for DELETE and POST -} diff --git a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/topo.json b/framework/src/onos/web/api/src/test/java/org/onosproject/rest/topo.json deleted file mode 100644 index cdef9768..00000000 --- a/framework/src/onos/web/api/src/test/java/org/onosproject/rest/topo.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "devices" : [ - { - "uri": "of:00000000000001", "type": "ROADM", "mfr": "Foo, Inc.", "hw": "Alpha", "sw": "1.2.3", - "serial": "ab321", "mac": "00000000000001", "annotations": {"foo": "bar"}, - "ports": [] - }, - { - "uri": "of:00000000000002", "type": "ROADM", "mfr": "Foo, Inc.", "hw": "Alpha", "sw": "1.2.3", - "serial": "ab456", "mac": "00000000000002", "annotations": {"foo": "bar"}, - "ports": [] - } - ], - - "links" : [ - { "src": "of:00000000000001/1", "dst": "of:00000000000002/1", "type": "OPTICAL" }, - { "src": "of:00000000000002/1", "dst": "of:00000000000001/1", "type": "OPTICAL" } - ] -} \ No newline at end of file -- cgit 1.2.3-korg