From 1aadd2b171094456197762019075a26888afa893 Mon Sep 17 00:00:00 2001 From: megala21 Date: Sun, 21 May 2017 01:07:10 +0530 Subject: [PATCH 1/3] Adding initial test cases for virtual fire alarm --- .../iot/integration/common/Constants.java | 23 ++- .../extensions/CustomTestServerManager.java | 7 +- .../enrollment/AndroidSenseEnrollment.java | 3 +- .../samples/MobileQSGTestCase.java | 5 +- .../samples/VirtualFireAlarmTestCase.java | 157 ++++++++++++++++++ .../iot/integration/user/UserManagement.java | 43 ++++- ...irtual-fire-alarm-enrollment-payloads.json | 14 ++ .../src/test/resources/testng.xml | 136 ++++++++------- 8 files changed, 318 insertions(+), 70 deletions(-) create mode 100644 modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java create mode 100644 modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json diff --git a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java index 056db2eb..c5e4a70f 100644 --- a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java +++ b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java @@ -28,6 +28,7 @@ public final class Constants { public static final String DEVICE_IMEI = "123123123"; public static final String AUTOMATION_CONTEXT = "IOT"; public static final String APPLICATION_JSON = "application/json"; + public static final String APPLICATION_ZIP = "application/zip"; public static final String APPLICATION_URL_ENCODED = "application/x-www-form-urlencoded"; public static final String OAUTH_CLIENT_ID = "client_id"; public static final String OAUTH_CLIENT_SECRET = "client_secret"; @@ -89,7 +90,8 @@ public final class Constants { + "perm:ios:location perm:ios:notification perm:ios:airplay perm:ios:caldav perm:ios:cal-subscription " + "perm:ios:passcode-policy perm:ios:webclip perm:ios:vpn perm:ios:per-app-vpn perm:ios:app-to-per-app-vpn " + "perm:ios:app-lock perm:ios:clear-passcode perm:ios:remove-profile perm:ios:get-restrictions " - + "perm:ios:wipe-data perm:admin perm:android:applications perm:devicetype:deployment perm:android-sense:enroll"; + + "perm:ios:wipe-data perm:admin perm:android:applications perm:devicetype:deployment " + + "perm:android-sense:enroll perm:firealarm:enroll"; public static final String OAUTH_TOKEN_PAYLOAD = "username=admin&password=admin" + MULTI_TENANT_OAUTH_TOKEN_PAYLOAD; @@ -114,11 +116,11 @@ public final class Constants { + "perm:device-types:features perm:device-types:types perm:devices:applications " + "perm:devices:compliance-data perm:devices:delete perm:devices:details perm:devices:effective-policy " + "perm:devices:features perm:devices:operations perm:devices:search perm:devices:update " - + "perm:devices:view perm:devicetype:deployment perm:get-activity perm:groups:add perm:groups:assign " - + "perm:groups:count perm:groups:device perm:groups:devices perm:groups:devices-add perm:groups:devices-count " - + "perm:groups:devices-remove perm:groups:groups perm:groups:groups-view perm:groups:remove " - + "perm:groups:roles perm:groups:share perm:groups:update perm:manage-configuration " - + "perm:notifications:mark-checked perm:notifications:view perm:policies:activate " + + "perm:devices:view perm:devicetype:deployment perm:firealarm:enroll perm:get-activity " + + "perm:groups:add perm:groups:assign perm:groups:count perm:groups:device perm:groups:devices " + + "perm:groups:devices-add perm:groups:devices-count perm:groups:devices-remove perm:groups:groups " + + "perm:groups:groups-view perm:groups:remove perm:groups:roles perm:groups:share perm:groups:update " + + "perm:manage-configuration perm:notifications:mark-checked perm:notifications:view perm:policies:activate " + "perm:policies:changes perm:policies:deactivate perm:policies:get-details perm:policies:get-policy-details " + "perm:policies:manage perm:policies:priorities perm:policies:remove perm:policies:update perm:roles:add" + " perm:roles:add-users perm:roles:create-combined-role perm:roles:delete perm:roles:details " @@ -442,4 +444,13 @@ public final class Constants { throw new AssertionError(); } } + + public static final class VirtualFireAlarmConstants { + public static final String ENROLLMENT_ENDPOINT = "/virtual_firealarm/1.0.0/device/download"; + public static final String STATS_ENDPOINT = "/virtual_firealarm/1.0.0/device/stats"; + public static final String PAYLOAD_FILE = "virtual-fire-alarm-enrollment-payloads.json"; + public static final String ANALYTICS_ARTIFACTS_DEPLOYMENT_ENDPOINT = + "/api/device-mgt/v1.0/admin/devicetype/1.0.0/deploy/virtual_firealarm"; + + } } diff --git a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/extensions/CustomTestServerManager.java b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/extensions/CustomTestServerManager.java index b6e858c6..44e038a6 100644 --- a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/extensions/CustomTestServerManager.java +++ b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/extensions/CustomTestServerManager.java @@ -99,7 +99,7 @@ public class CustomTestServerManager { * Carbon server */ public synchronized String startServer(String server) - throws AutomationFrameworkException, IOException, XPathExpressionException { + throws AutomationFrameworkException, IOException, XPathExpressionException, InterruptedException { if (carbonHome == null) { if (carbonZip == null) { carbonZip = System.getProperty(FrameworkConstants.SYSTEM_PROPERTY_CARBON_ZIP_LOCATION); @@ -114,6 +114,10 @@ public class CustomTestServerManager { } else { carbonHome = extractedDir; } + // Deploy the plugins. + String[] cmdArray = new String[] { "mvn", "clean", "install", "-f", "plugins-deployer.xml"}; + Runtime.getRuntime().exec(cmdArray, null, new File(carbonHome + File.separator + "plugins")); + Thread.sleep(15000); } else if (server.equalsIgnoreCase("analytics") || server.equalsIgnoreCase("broker")) { if (extractedDir == null) { carbonHome = carbonServer.setUpCarbonHome(carbonZip) + File.separator + "wso2" + File.separator + server; @@ -131,6 +135,7 @@ public class CustomTestServerManager { } else { this.portOffset = 0; } + carbonServer.startServerUsingCarbonHome(carbonHome, commandMap); return carbonHome; } diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidSenseEnrollment.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidSenseEnrollment.java index 1c35f4f4..29ebd764 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidSenseEnrollment.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidSenseEnrollment.java @@ -96,7 +96,8 @@ public class AndroidSenseEnrollment extends TestBase { } - @Test(description = "Test an Android sense device data publishing.", dependsOnMethods = {"testEnrollment"} ) + @Test(description = "Test an Android sense device data publishing.", dependsOnMethods = {"testEnrollment"}, + groups = {"androidSense"}) public void testEventPublishing() throws Exception { String DEVICE_TYPE = "android_sense"; String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + DEVICE_ID + "/data"; diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/MobileQSGTestCase.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/MobileQSGTestCase.java index 085abc9e..0ea78ebc 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/MobileQSGTestCase.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/MobileQSGTestCase.java @@ -41,11 +41,9 @@ public class MobileQSGTestCase extends TestBase { private String username1; private String username2; - @BeforeClass(alwaysRun = true, groups = { Constants.UserManagement.USER_MANAGEMENT_GROUP}) + @BeforeClass(alwaysRun = true) public void initTest() throws Exception { super.init(TestUserMode.SUPER_TENANT_ADMIN); - backendHTTPSURL = automationContext.getContextUrls().getWebAppURLHttps(); - this.client = new RestClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString); username1 = "alex"; username2 = "chris"; } @@ -59,6 +57,7 @@ public class MobileQSGTestCase extends TestBase { Runtime.getRuntime().exec(cmdArray, null, scriptFile); // Allow some time to finish its execution Thread.sleep(10000); + this.client = new RestClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString); } @Test(description = "This test case tests whether user and roles are created as expected", dependsOnMethods = diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java new file mode 100644 index 00000000..232a90f6 --- /dev/null +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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.wso2.iot.integration.samples; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import junit.framework.Assert; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; +import org.wso2.iot.integration.common.Constants; +import org.wso2.iot.integration.common.PayloadGenerator; +import org.wso2.iot.integration.common.RestClient; +import org.wso2.iot.integration.common.TestBase; + +/** + * This class tests the functionality of the virtual fire alarm. + */ +public class VirtualFireAlarmTestCase extends TestBase { + private static Log log = LogFactory.getLog(VirtualFireAlarmTestCase.class); + public static String deviceId1; + public static String deviceId2; + public static long currentTime; + + @Factory(dataProvider = "userModeProvider") + public VirtualFireAlarmTestCase(TestUserMode userMode) { + this.userMode = userMode; + } + + @BeforeClass(alwaysRun = true) + public void initTest() throws Exception { + super.init(userMode);; + RestClient client = new RestClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString); + if (userMode == TestUserMode.TENANT_ADMIN) { + HttpResponse response = client + .post(Constants.VirtualFireAlarmConstants.ANALYTICS_ARTIFACTS_DEPLOYMENT_ENDPOINT, ""); + Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); + // Time for deploying the carbon apps + Thread.sleep(30000); + } + } + + @Test(description = "This test case tests the virtual fire alarm enrollment") + public void testEnrollment() throws Exception { + RestClient client = new RestClient(backendHTTPSURL, Constants.APPLICATION_ZIP, accessTokenString); + // Enroll an advanced agent and check whether that enrollment succeeds without issues. + HttpResponse response = client.get(Constants.VirtualFireAlarmConstants.ENROLLMENT_ENDPOINT + + "?deviceName=advanced&sketchType=virtual_firealarm_advanced"); + Assert.assertEquals("Advance fire alarm advance agent enrollment failed", HttpStatus.SC_OK, + response.getResponseCode()); + + // Enroll an simple agent and check whether that enrollment succeeds without issues. + response = client.get(Constants.VirtualFireAlarmConstants.ENROLLMENT_ENDPOINT + + "?deviceName=simple&sketchType=virtual_firealarm"); + Assert.assertEquals("Advance fire alarm advance agent enrollment failed", HttpStatus.SC_OK, + response.getResponseCode()); + + response = client.get(Constants.MobileDeviceManagement.GET_DEVICE_COUNT_ENDPOINT + "?type=virtual_firealarm"); + JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonObject().getAsJsonArray("devices"); + Assert.assertEquals("Virtual fire alarm enrollment failed ", 2, jsonArray.size()); + + deviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); + deviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); + } + + @Test(description = "Test whether the publishing to a mqtt broker works fine without exceptions", dependsOnMethods = + {"testEnrollment"} ) + public void testEventPublishing() throws Exception { + String DEVICE_TYPE = "virtual_firealarm"; + + // Publishing message as a device with simple agent (device 1) + String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId1 + + "/temperature"; + int qos = 2; + String broker = "tcp://localhost:1886"; + String clientId = deviceId1 + ":" + DEVICE_TYPE; + MemoryPersistence persistence = new MemoryPersistence(); + MqttClient sampleClient = new MqttClient(broker, clientId, persistence); + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setUserName(accessToken); + connOpts.setPassword("".toCharArray()); + connOpts.setKeepAliveInterval(120); + connOpts.setCleanSession(true); + log.info("Connecting to broker: " + broker); + sampleClient.connect(connOpts); + log.info("Connected"); + JsonObject fireAlarmPayload = PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants + .PAYLOAD_FILE, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION); + JsonObject eventPayload = fireAlarmPayload.getAsJsonObject("event"); + JsonObject metaDataPayload = eventPayload.getAsJsonObject("metaData"); + metaDataPayload.addProperty("deviceId", deviceId1); + eventPayload.add("metaData", metaDataPayload); + fireAlarmPayload.add("event", eventPayload); + MqttMessage message = new MqttMessage(fireAlarmPayload.toString().getBytes()); + message.setQos(qos); + sampleClient.publish(topic, message); + log.info("Message is published to Mqtt Client"); + sampleClient.disconnect(); + log.info("Mqtt Client is Disconnected"); + + // Publishing message as a device with simple agent (device 2) + topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId2 + + "/temperature"; + clientId = deviceId2 + ":" + DEVICE_TYPE; + persistence = new MemoryPersistence(); + sampleClient = new MqttClient(broker, clientId, persistence); + connOpts = new MqttConnectOptions(); + connOpts.setUserName(accessToken); + connOpts.setPassword("".toCharArray()); + connOpts.setKeepAliveInterval(120); + connOpts.setCleanSession(true); + log.info("Connecting to broker: " + broker); + sampleClient.connect(connOpts); + log.info("Connected"); + + fireAlarmPayload = PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants + .PAYLOAD_FILE, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION); + eventPayload = fireAlarmPayload.getAsJsonObject("event"); + metaDataPayload = eventPayload.getAsJsonObject("metaData"); + metaDataPayload.addProperty("deviceId", deviceId2); + eventPayload.add("metaData", metaDataPayload); + fireAlarmPayload.add("event", eventPayload); + message = new MqttMessage(fireAlarmPayload.toString().getBytes()); + message.setQos(qos); + sampleClient.publish(topic, message); + log.info("Message is published to Mqtt Client"); + sampleClient.disconnect(); + log.info("Mqtt Client is Disconnected"); + currentTime = System.currentTimeMillis(); + } +} diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java index a7730f6e..d92f6733 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java @@ -33,6 +33,12 @@ import org.wso2.iot.integration.common.Constants; import org.wso2.iot.integration.common.PayloadGenerator; import org.wso2.iot.integration.common.RestClient; import org.wso2.iot.integration.common.TestBase; +import org.wso2.iot.integration.samples.VirtualFireAlarmTestCase; + +import java.sql.Timestamp; + +import static org.wso2.iot.integration.samples.VirtualFireAlarmTestCase.deviceId1; +import static org.wso2.iot.integration.samples.VirtualFireAlarmTestCase.deviceId2; /** * This class contains integration tests for user management backend services. @@ -164,8 +170,43 @@ public class UserManagement extends TestBase { Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode()); } + // Test case related to virtual fire alarm added here as the batch cron runs for every 5 minutes and rather than + // waiting for that we can check them in a latter test cases + @Test(description = "Test whether data that is published is stored in analytics event table", dependsOnMethods = + {"testRemoveUser"} ) + public void testBatchDataPersistence() throws Exception { + long MilliSecondDifference = System.currentTimeMillis() - VirtualFireAlarmTestCase.currentTime; + if (MilliSecondDifference < 300000) { + Thread.sleep(300000 - MilliSecondDifference); + } + Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 7200000); + String url = Constants.VirtualFireAlarmConstants.STATS_ENDPOINT + "/" + deviceId1; + url += "?from=" + (VirtualFireAlarmTestCase.currentTime - 300000)/1000 + "&to=" + System.currentTimeMillis() + /1000; + HttpResponse response = client.get(url); + JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray(); + Assert.assertEquals( + "Published event for the device with the id " + deviceId1 + " is not inserted to " + + "analytics table", HttpStatus.SC_OK, response.getResponseCode()); + Assert.assertEquals( + "Published event for the device with the id " + deviceId1 + " is not inserted to analytics table", 1, + jsonArray.size()); + + url = Constants.VirtualFireAlarmConstants.STATS_ENDPOINT + "/" + deviceId2; + url += "?from=" + (VirtualFireAlarmTestCase.currentTime - 300000)/1000 + "&to=" + System.currentTimeMillis() + /1000; + response = client.get(url); + jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray(); + Assert.assertEquals( + "Published event for the device with the id " + deviceId2 + " is not inserted to " + + "analytics table", HttpStatus.SC_OK, response.getResponseCode()); + Assert.assertEquals( + "Published event for the device with the id " + deviceId2 + " is not inserted to analytics table", 1, + jsonArray.size()); + } + @Test(description = "Test whether the API that is used to change the password works as expected.", - dependsOnMethods = {"testRemoveUser"}) + dependsOnMethods = {"testBatchDataPersistence"}) public void testChangePassword() throws Exception { String url = Constants.UserManagement.USER_ENDPOINT + "/credentials"; HttpResponse response = client.put(url, PayloadGenerator diff --git a/modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json b/modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json new file mode 100644 index 00000000..b90369ae --- /dev/null +++ b/modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json @@ -0,0 +1,14 @@ +{ + "PUBLISH_DATA": { + "event": { + "metaData": { + "owner": "admin", + "deviceId": "AS101", + "time": 1494315475 + }, + "payloadData": { + "temperature": 30 + } + } + } +} \ No newline at end of file diff --git a/modules/integration/tests-integration/src/test/resources/testng.xml b/modules/integration/tests-integration/src/test/resources/testng.xml index cb203e09..60f425a0 100644 --- a/modules/integration/tests-integration/src/test/resources/testng.xml +++ b/modules/integration/tests-integration/src/test/resources/testng.xml @@ -28,80 +28,100 @@ - + - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From ee94b8ce8fc54eecfb31d701e5601724030ea41e Mon Sep 17 00:00:00 2001 From: megala21 Date: Tue, 23 May 2017 01:42:11 +0530 Subject: [PATCH 2/3] Adding initial cut virtual fire-alarm policy publish scenario --- .../tests-common/integration-common/pom.xml | 4 ++ .../iot/integration/common/Constants.java | 3 + .../common/MqttSubscriberClient.java | 57 ++++++++++++++++++ .../samples/VirtualFireAlarmTestCase.java | 60 ++++++++++++++++--- ...irtual-fire-alarm-enrollment-payloads.json | 16 +++++ pom.xml | 4 +- 6 files changed, 134 insertions(+), 10 deletions(-) create mode 100644 modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java diff --git a/modules/integration/tests-common/integration-common/pom.xml b/modules/integration/tests-common/integration-common/pom.xml index 2270613b..12c927cb 100644 --- a/modules/integration/tests-common/integration-common/pom.xml +++ b/modules/integration/tests-common/integration-common/pom.xml @@ -140,6 +140,10 @@ org.wso2.carbon.integration.common.utils compile + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + diff --git a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java index c5e4a70f..824e2c7d 100644 --- a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java +++ b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/Constants.java @@ -451,6 +451,9 @@ public final class Constants { public static final String PAYLOAD_FILE = "virtual-fire-alarm-enrollment-payloads.json"; public static final String ANALYTICS_ARTIFACTS_DEPLOYMENT_ENDPOINT = "/api/device-mgt/v1.0/admin/devicetype/1.0.0/deploy/virtual_firealarm"; + public static final String POLICY_DATA = "POLICY_DATA"; + public static final String ACTIVATE_POLICY_ENDPOINT = "/api/device-mgt/v1.0/policies/activate-policy"; + public static final String APPLY_CHANGES_ENDPOINT = "/api/device-mgt/v1.0/policies/apply-changes"; } } diff --git a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java new file mode 100644 index 00000000..cb8c2b6d --- /dev/null +++ b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java @@ -0,0 +1,57 @@ +package org.wso2.iot.integration.common; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.*; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; + +import java.util.ArrayList; + +/** + * This is a mqtt subscriber client to receive . + */ +public class MqttSubscriberClient implements MqttCallback { + private static Log log = LogFactory.getLog(MqttSubscriberClient.class); + private ArrayList mqttMessages; + + @Override + public void connectionLost(Throwable throwable) { + // Not implemented + } + + @Override + public void messageArrived(String s, MqttMessage mqttMessage) throws Exception { + mqttMessages.add(mqttMessage); + } + + @Override + public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { + // Not implemented + } + + /** + * + * @param serverAddress Mqtt broker address + * @param clientId Client ID + * @param topicName Topic Name + * @throws MqttException Mqtt Exception + */ + public MqttSubscriberClient(String serverAddress, String clientId, String topicName, String accessToken) throws + MqttException { + mqttMessages = new ArrayList<>(); + MemoryPersistence persistence = new MemoryPersistence(); + MqttClient client = new MqttClient(serverAddress, clientId, persistence); + MqttConnectOptions connectOptions = new MqttConnectOptions(); + client.setCallback(this); + connectOptions.setUserName(accessToken); + connectOptions.setPassword("".toCharArray()); + connectOptions.setCleanSession(true); + client.connect(connectOptions); + client.subscribe(topicName); + } + + public ArrayList getMqttMessages() { + return mqttMessages; + } + +} diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java index 232a90f6..e0852e58 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/samples/VirtualFireAlarmTestCase.java @@ -21,6 +21,7 @@ package org.wso2.iot.integration.samples; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; import junit.framework.Assert; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; @@ -35,10 +36,13 @@ import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import org.wso2.iot.integration.common.Constants; +import org.wso2.iot.integration.common.MqttSubscriberClient; import org.wso2.iot.integration.common.PayloadGenerator; import org.wso2.iot.integration.common.RestClient; import org.wso2.iot.integration.common.TestBase; +import java.util.ArrayList; + /** * This class tests the functionality of the virtual fire alarm. */ @@ -46,7 +50,12 @@ public class VirtualFireAlarmTestCase extends TestBase { private static Log log = LogFactory.getLog(VirtualFireAlarmTestCase.class); public static String deviceId1; public static String deviceId2; + public static String tenantDeviceId1; + public static String tenantDeviceId2; public static long currentTime; + private String broker = "tcp://localhost:1886"; + private String DEVICE_TYPE = "virtual_firealarm"; + private RestClient restClient; @Factory(dataProvider = "userModeProvider") public VirtualFireAlarmTestCase(TestUserMode userMode) { @@ -55,10 +64,10 @@ public class VirtualFireAlarmTestCase extends TestBase { @BeforeClass(alwaysRun = true) public void initTest() throws Exception { - super.init(userMode);; - RestClient client = new RestClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString); + super.init(userMode); + restClient = new RestClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString); if (userMode == TestUserMode.TENANT_ADMIN) { - HttpResponse response = client + HttpResponse response = restClient .post(Constants.VirtualFireAlarmConstants.ANALYTICS_ARTIFACTS_DEPLOYMENT_ENDPOINT, ""); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); // Time for deploying the carbon apps @@ -85,20 +94,24 @@ public class VirtualFireAlarmTestCase extends TestBase { JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonObject().getAsJsonArray("devices"); Assert.assertEquals("Virtual fire alarm enrollment failed ", 2, jsonArray.size()); - deviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); - deviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); + if (userMode != TestUserMode.TENANT_ADMIN) { + deviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); + deviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); + } else { + tenantDeviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); + tenantDeviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString(); + } } @Test(description = "Test whether the publishing to a mqtt broker works fine without exceptions", dependsOnMethods = {"testEnrollment"} ) public void testEventPublishing() throws Exception { - String DEVICE_TYPE = "virtual_firealarm"; - + String deviceId1 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId1 : VirtualFireAlarmTestCase.deviceId1; + String deviceId2 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2; // Publishing message as a device with simple agent (device 1) String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId1 + "/temperature"; int qos = 2; - String broker = "tcp://localhost:1886"; String clientId = deviceId1 + ":" + DEVICE_TYPE; MemoryPersistence persistence = new MemoryPersistence(); MqttClient sampleClient = new MqttClient(broker, clientId, persistence); @@ -154,4 +167,35 @@ public class VirtualFireAlarmTestCase extends TestBase { log.info("Mqtt Client is Disconnected"); currentTime = System.currentTimeMillis(); } + + @Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = + {"testEnrollment"} ) + public void testPolicyPublishing() throws Exception { + String deviceId2 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2; + String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId2 + "/#"; + String clientId = deviceId2 + ":" + DEVICE_TYPE; + HttpResponse response = restClient.post("/api/device-mgt/v1.0/policies", PayloadGenerator + .getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, + Constants.VirtualFireAlarmConstants.POLICY_DATA).toString()); + Assert.assertEquals("Policy creation for virtual fire alarm failed", HttpStatus.SC_CREATED, + response.getResponseCode()); + JsonObject jsonObject = new JsonParser().parse(response.getData()).getAsJsonObject(); + String policyId = jsonObject.getAsJsonPrimitive("id").getAsString(); + JsonArray jsonArray = new JsonArray(); + jsonArray.add(new JsonPrimitive(policyId)); + response = restClient.post(Constants.VirtualFireAlarmConstants.ACTIVATE_POLICY_ENDPOINT, + jsonArray.toString()); + Assert.assertEquals("Policy activation for virtual fire alarm failed", HttpStatus.SC_OK, + response.getResponseCode()); + MqttSubscriberClient mqttSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken); + response = restClient.put(Constants.VirtualFireAlarmConstants.APPLY_CHANGES_ENDPOINT, ""); + Assert.assertEquals("Applying changes to policy for virtual fire alarm failed", HttpStatus.SC_OK, + response.getResponseCode()); + // Allow some time for message delivery + Thread.sleep(20000); + ArrayList mqttMessages = mqttSubscriberClient.getMqttMessages(); + Assert.assertEquals("Policy published message is not received by the mqtt listener. ", 1, mqttMessages.size()); + + + } } diff --git a/modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json b/modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json index b90369ae..58b14913 100644 --- a/modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json +++ b/modules/integration/tests-integration/src/test/resources/payloads/virtual-fire-alarm-enrollment-payloads.json @@ -10,5 +10,21 @@ "temperature": 30 } } + }, + "POLICY_DATA" : { + "policyName":"testpolicy", + "description":"","compliance":"enforce","ownershipType":null,"active":true, + "profile":{ + "profileName":"dvdv", + "deviceType":"virtual_firealarm", + "profileFeaturesList":[{ + "featureCode":"CONFIG", + "deviceType":"virtual_firealarm", + "content":{ + "policyDefinition":"define stream fireAlarmEventStream (deviceID string, temp int);\nfrom fireAlarmEventStream#window.time(30 sec)\nselect deviceID, max(temp) as maxValue\ngroup by deviceID\ninsert into analyzeStream for expired-events;\nfrom analyzeStream[maxValue > 50]\nselect maxValue\ninsert into bulbOnStream;\nfrom fireAlarmEventStream[temp < 50]\nselect deviceID, temp\ninsert into bulbOffStream;" + } + }] + }, + "roles":["ANY"] } } \ No newline at end of file diff --git a/pom.xml b/pom.xml index 13177a1b..643baf36 100644 --- a/pom.xml +++ b/pom.xml @@ -1512,7 +1512,7 @@ - 2.0.65 + 2.0.68 [2.0.0, 3.0.0) @@ -1520,7 +1520,7 @@ - 3.0.35 + 3.0.36 6.1.80 From 976bdb229272a785d518feb8db05a95139748c71 Mon Sep 17 00:00:00 2001 From: megala21 Date: Tue, 23 May 2017 12:03:05 +0530 Subject: [PATCH 3/3] Fixing issues --- .../common/MqttSubscriberClient.java | 29 ++++++- .../iot/integration/user/UserManagement.java | 12 +-- .../src/test/resources/testng.xml | 78 +------------------ 3 files changed, 32 insertions(+), 87 deletions(-) diff --git a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java index cb8c2b6d..7df49ded 100644 --- a/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java +++ b/modules/integration/tests-common/integration-common/src/main/java/org/wso2/iot/integration/common/MqttSubscriberClient.java @@ -1,8 +1,29 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you 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.wso2.iot.integration.common; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.paho.client.mqttv3.*; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.util.ArrayList; @@ -11,7 +32,6 @@ import java.util.ArrayList; * This is a mqtt subscriber client to receive . */ public class MqttSubscriberClient implements MqttCallback { - private static Log log = LogFactory.getLog(MqttSubscriberClient.class); private ArrayList mqttMessages; @Override @@ -46,6 +66,7 @@ public class MqttSubscriberClient implements MqttCallback { connectOptions.setUserName(accessToken); connectOptions.setPassword("".toCharArray()); connectOptions.setCleanSession(true); + connectOptions.setKeepAliveInterval(300); client.connect(connectOptions); client.subscribe(topicName); } diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java index d92f6733..53d672a7 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/user/UserManagement.java @@ -34,11 +34,7 @@ import org.wso2.iot.integration.common.PayloadGenerator; import org.wso2.iot.integration.common.RestClient; import org.wso2.iot.integration.common.TestBase; import org.wso2.iot.integration.samples.VirtualFireAlarmTestCase; - -import java.sql.Timestamp; - -import static org.wso2.iot.integration.samples.VirtualFireAlarmTestCase.deviceId1; -import static org.wso2.iot.integration.samples.VirtualFireAlarmTestCase.deviceId2; +import static org.wso2.iot.integration.samples.VirtualFireAlarmTestCase.*; /** * This class contains integration tests for user management backend services. @@ -175,11 +171,15 @@ public class UserManagement extends TestBase { @Test(description = "Test whether data that is published is stored in analytics event table", dependsOnMethods = {"testRemoveUser"} ) public void testBatchDataPersistence() throws Exception { + String deviceId1 = + this.userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId1 : VirtualFireAlarmTestCase.deviceId1; + String deviceId2 = + this.userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2; + long MilliSecondDifference = System.currentTimeMillis() - VirtualFireAlarmTestCase.currentTime; if (MilliSecondDifference < 300000) { Thread.sleep(300000 - MilliSecondDifference); } - Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 7200000); String url = Constants.VirtualFireAlarmConstants.STATS_ENDPOINT + "/" + deviceId1; url += "?from=" + (VirtualFireAlarmTestCase.currentTime - 300000)/1000 + "&to=" + System.currentTimeMillis() /1000; diff --git a/modules/integration/tests-integration/src/test/resources/testng.xml b/modules/integration/tests-integration/src/test/resources/testng.xml index 60f425a0..2c08cfc8 100644 --- a/modules/integration/tests-integration/src/test/resources/testng.xml +++ b/modules/integration/tests-integration/src/test/resources/testng.xml @@ -33,6 +33,7 @@ + @@ -41,87 +42,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -