diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts new file mode 100644 index 0000000000..436c27c0f4 --- /dev/null +++ b/buildSrc/settings.gradle.kts @@ -0,0 +1,9 @@ +pluginManagement { + plugins { + id("de.fayard.refreshVersions") version "0.40.1" + } +} + +plugins { + id("de.fayard.refreshVersions") +} diff --git a/buildSrc/src/main/kotlin/org.openbase.bco.gradle.kts b/buildSrc/src/main/kotlin/org.openbase.bco.gradle.kts index 52ea58fa58..bd416f5ced 100644 --- a/buildSrc/src/main/kotlin/org.openbase.bco.gradle.kts +++ b/buildSrc/src/main/kotlin/org.openbase.bco.gradle.kts @@ -33,6 +33,7 @@ dependencies { implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.10") api("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.10") implementation("org.jetbrains.kotlin:kotlin-script-runtime:1.5.21") + testImplementation("org.junit.jupiter:junit-jupiter:[5.8,5.9-alpha)") testImplementation ("org.junit.jupiter:junit-jupiter-api:[5.8,5.9-alpha)") testRuntimeOnly ("org.junit.jupiter:junit-jupiter-engine:[5.8,5.9-alpha)") } @@ -47,6 +48,10 @@ tasks.withType { tasks.withType { useJUnitPlatform() maxParallelForks = 1 + logging.captureStandardOutput(LogLevel.WARN) + maxHeapSize = "7G" + failFast = true + setForkEvery(1) } publishing { diff --git a/lib/jul b/lib/jul index 99278e9fca..d266c87ffa 160000 --- a/lib/jul +++ b/lib/jul @@ -1 +1 @@ -Subproject commit 99278e9fcadfe82c324b590a1881f9d86b1f9502 +Subproject commit d266c87ffa26cc969a667099ae1e415ff70daf74 diff --git a/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/service/ServiceStateTraitMapperFactoryTest.java b/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/service/ServiceStateTraitMapperFactoryTest.java index 71e1e2c738..ff02a8c4ed 100644 --- a/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/service/ServiceStateTraitMapperFactoryTest.java +++ b/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/service/ServiceStateTraitMapperFactoryTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,9 +40,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; - -import static junit.framework.TestCase.assertEquals; /** * @author Tamino Huxohl @@ -51,14 +49,14 @@ public class ServiceStateTraitMapperFactoryTest extends MqttIntegrationTest { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceStateTraitMapperFactoryTest.class); @BeforeEach - public void setUp() throws Exception { + public void setupTest() throws Exception { MockRegistryHolder.newMockRegistry(); Registries.getTemplateRegistry(true); } @AfterEach - public void tearDown() { + public void tearDownTest() { MockRegistryHolder.shutdownMockRegistry(); } @@ -89,7 +87,7 @@ public void testMapperAvailability() { LOGGER.error(entry.getValue().getMessage()); } - assertEquals("Could not create every needed mapping", 0, mapperExceptionMap.size()); + assertEquals(0, mapperExceptionMap.size(), "Could not create every needed mapping"); } } diff --git a/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/unit/UnitTypeMappingTest.java b/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/unit/UnitTypeMappingTest.java index 08ba1b6ba7..49e866f0f0 100644 --- a/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/unit/UnitTypeMappingTest.java +++ b/module/app/cloudconnector/src/test/java/org/openbase/bco/app/cloudconnector/mapping/unit/UnitTypeMappingTest.java @@ -22,12 +22,15 @@ * #L% */ + + +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; -import static org.junit.Assert.assertEquals; + /** * @author Tamino Huxohl @@ -49,8 +52,10 @@ public void testUnitTypeValidity() throws IllegalArgumentException { final UnitType unitType = UnitType.valueOf(unitTypeName); - assertEquals("UnitTypeMapping[" + unitTypeMapping.name() + "] does not match unitType[" + unitType.name() + "]", - unitTypeMapping.getUnitType(), unitType); + Assertions.assertEquals(unitTypeMapping.getUnitType(), + unitType, + "UnitTypeMapping[" + unitTypeMapping.name() + "] does not match unitType[" + unitType.name() + "]" + ); } } } diff --git a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/AbsenceEnergySavingAgentTest.java b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/AbsenceEnergySavingAgentTest.java index bdb850e70b..dd330dee92 100644 --- a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/AbsenceEnergySavingAgentTest.java +++ b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/AbsenceEnergySavingAgentTest.java @@ -21,8 +21,9 @@ * . * #L% */ -import static org.junit.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.app.test.agent.AbstractBCOAgentManagerTest; @@ -112,10 +113,10 @@ public void testAbsenceEnergySavingAgent() throws Exception { locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.ON); colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.ON); - assertEquals("MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION", MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT.", PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue()); - assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched to OFF", PowerState.State.ON, locationRemote.getPowerState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to OFF", PowerState.State.ON, colorableLightRemote.getPowerState().getValue()); + assertEquals(MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue(), "MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION"); + assertEquals(PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue(), "PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT."); + assertEquals(PowerState.State.ON, locationRemote.getPowerState().getValue(), "PowerState of Location[" + locationRemote.getLabel() + "] has not switched to OFF"); + assertEquals(PowerState.State.ON, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to OFF"); // test if on no motion the lights are turned off motionDetectorController.applyServiceState(NO_MOTION, ServiceType.MOTION_STATE_SERVICE); @@ -124,9 +125,9 @@ public void testAbsenceEnergySavingAgent() throws Exception { colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.OFF); //locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); - assertEquals("MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION", MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT.", PresenceState.State.ABSENT, locationRemote.getPresenceState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to OFF", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); + assertEquals(MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue(), "MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION"); + assertEquals(PresenceState.State.ABSENT, locationRemote.getPresenceState().getValue(), "PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT."); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to OFF"); //assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched to OFF", PowerState.State.OFF, locationRemote.getPowerState().getValue()); // test if the lights stay off on new motion @@ -136,9 +137,9 @@ public void testAbsenceEnergySavingAgent() throws Exception { colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.OFF); //locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); - assertEquals("MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to MOTION", MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to PRESENT.", PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has changes without intention", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); + assertEquals(MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue(), "MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to MOTION"); + assertEquals(PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue(), "PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to PRESENT."); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has changes without intention"); //assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has changes without intention", PowerState.State.OFF, locationRemote.getPowerState().getValue()); } diff --git a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/FireAlarmAgentTest.java b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/FireAlarmAgentTest.java index 991f31d4aa..4bb3490714 100644 --- a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/FireAlarmAgentTest.java +++ b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/FireAlarmAgentTest.java @@ -21,6 +21,9 @@ * . * #L% */ + +import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.app.test.agent.AbstractBCOAgentManagerTest; @@ -46,7 +49,7 @@ import org.openbase.type.domotic.unit.dal.SmokeDetectorDataType.SmokeDetectorData; import org.openbase.type.domotic.unit.location.LocationDataType.LocationData; -import static org.junit.Assert.assertEquals; + public class FireAlarmAgentTest extends AbstractBCOAgentManagerTest { @@ -92,10 +95,10 @@ public void testFireAlarmAgent() throws Exception { locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.OFF); - assertEquals("Initial SmokeAlarmState of SmokeDetector[" + smokeDetectorRemote.getLabel() + "] is not NO_ALARM", AlarmState.State.NO_ALARM, smokeDetectorRemote.getSmokeAlarmState().getValue()); - assertEquals("Initial OpeningRatio of Blindstate of Rollershutter[" + rollerShutterRemote.getLabel() + "] is not 0.0", 0d, rollerShutterRemote.getBlindState().getOpeningRatio(), 0.001); - assertEquals("Initial PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] is not OFF", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("Initial PowerState of Location[" + locationRemote.getLabel() + "] is not OFF", PowerState.State.OFF, locationRemote.getPowerState().getValue()); + assertEquals(AlarmState.State.NO_ALARM, smokeDetectorRemote.getSmokeAlarmState().getValue(), "Initial SmokeAlarmState of SmokeDetector[" + smokeDetectorRemote.getLabel() + "] is not NO_ALARM"); + assertEquals(0d, rollerShutterRemote.getBlindState().getOpeningRatio(), 0.001, "Initial OpeningRatio of Blindstate of Rollershutter[" + rollerShutterRemote.getLabel() + "] is not 0.0"); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "Initial PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] is not OFF"); + assertEquals(PowerState.State.OFF, locationRemote.getPowerState().getValue(), "Initial PowerState of Location[" + locationRemote.getLabel() + "] is not OFF"); // test if on alarm the lights are turned on smokeDetectorController.applyServiceState(ALARM, ServiceType.SMOKE_ALARM_STATE_SERVICE); @@ -105,11 +108,11 @@ public void testFireAlarmAgent() throws Exception { rollerShutterStateAwaiter.waitForState((RollerShutterData data) -> data.getBlindState().getOpeningRatio() == 1.0d && data.getBlindState().getValue() == State.UP); locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.ON); - assertEquals("SmokeAlarmState of SmokeDetector[" + smokeDetectorRemote.getLabel() + "] has not switched to ALARM", AlarmState.State.ALARM, smokeDetectorRemote.getSmokeAlarmState().getValue()); - assertEquals("OpeningRatio of Blindstate of Rollershutter[" + rollerShutterRemote.getLabel() + "] has not switched to 100", 1.0d, rollerShutterRemote.getBlindState().getOpeningRatio(), 0.001); - assertEquals("SmokeAlarmState of Location[" + locationRemote.getLabel() + "] has not switched to ALARM.", AlarmState.State.ALARM, locationRemote.getSmokeAlarmState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to ON", PowerState.State.ON, colorableLightRemote.getPowerState().getValue()); - assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched to ON", PowerState.State.ON, locationRemote.getPowerState().getValue()); + assertEquals(AlarmState.State.ALARM, smokeDetectorRemote.getSmokeAlarmState().getValue(), "SmokeAlarmState of SmokeDetector[" + smokeDetectorRemote.getLabel() + "] has not switched to ALARM"); + assertEquals(1.0d, rollerShutterRemote.getBlindState().getOpeningRatio(), 0.001, "OpeningRatio of Blindstate of Rollershutter[" + rollerShutterRemote.getLabel() + "] has not switched to 100"); + assertEquals(AlarmState.State.ALARM, locationRemote.getSmokeAlarmState().getValue(), "SmokeAlarmState of Location[" + locationRemote.getLabel() + "] has not switched to ALARM."); + assertEquals(PowerState.State.ON, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to ON"); + assertEquals(PowerState.State.ON, locationRemote.getPowerState().getValue(), "PowerState of Location[" + locationRemote.getLabel() + "] has not switched to ON"); } @Override diff --git a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/HeaterEnergySavingAgentTest.java b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/HeaterEnergySavingAgentTest.java index ec2320c7fe..ed6ef97f48 100644 --- a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/HeaterEnergySavingAgentTest.java +++ b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/HeaterEnergySavingAgentTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Timeout; import org.openbase.app.test.agent.AbstractBCOAgentManagerTest; import org.junit.jupiter.api.Test; @@ -49,7 +50,7 @@ import org.openbase.type.domotic.unit.dal.TemperatureControllerDataType.TemperatureControllerData; import org.openbase.type.domotic.unit.location.LocationDataType.LocationData; -import static org.junit.Assert.assertEquals; + /** * * @author Timo @@ -80,8 +81,8 @@ public void testHeaterEnergySavingAgent() throws Exception { TemperatureControllerController temperatureController = (TemperatureControllerController) deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(temperatureControllerRemote.getId()); // validate remote controller match - assertEquals("Controller and remote are not compatible to each other!", reedContactController.getId(), reedContactRemote.getId()); - assertEquals("Reed contact is not connected to window.", connectionRemote.getConfig().getConnectionConfig().getUnitIdList().contains(reedContactRemote.getId()), true); + assertEquals(reedContactController.getId(), reedContactRemote.getId(), "Controller and remote are not compatible to each other!"); + assertEquals(connectionRemote.getConfig().getConnectionConfig().getUnitIdList().contains(reedContactRemote.getId()), true, "Reed contact is not connected to window."); UnitStateAwaiter reedContactStateAwaiter = new UnitStateAwaiter<>(reedContactRemote); UnitStateAwaiter connectionStateAwaiter = new UnitStateAwaiter<>(connectionRemote); @@ -97,10 +98,10 @@ public void testHeaterEnergySavingAgent() throws Exception { temperatureControllerStateAwaiter.waitForState((TemperatureControllerData data) -> data.getTargetTemperatureState().getTemperature() == 21.0); locationStateAwaiter.waitForState((LocationData data) -> data.getTargetTemperatureState().getTemperature() == 21.0); - assertEquals("Initial ContactState of ReedContact[" + reedContactRemote.getLabel() + "] is not CLOSED", ContactState.State.CLOSED, reedContactRemote.getContactState().getValue()); - assertEquals("Initial ContactState of Connection[" + connectionRemote.getLabel() + "] is not CLOSED", WindowState.State.CLOSED, connectionRemote.getWindowState().getValue()); - assertEquals("Initial TargetTemperature of TemperatureController[" + temperatureControllerRemote.getLabel() + "] is not 21.0", 21.0, temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 1.0); - assertEquals("Initial TargetTemperature of location[" + locationRemote.getLabel() + "] is not 21.0", 21.0, locationRemote.getTargetTemperatureState().getTemperature(), 1.0); + assertEquals(ContactState.State.CLOSED, reedContactRemote.getContactState().getValue(), "Initial ContactState of ReedContact[" + reedContactRemote.getLabel() + "] is not CLOSED"); + assertEquals(WindowState.State.CLOSED, connectionRemote.getWindowState().getValue(), "Initial ContactState of Connection[" + connectionRemote.getLabel() + "] is not CLOSED"); + assertEquals(21.0, temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 1.0, "Initial TargetTemperature of TemperatureController[" + temperatureControllerRemote.getLabel() + "] is not 21.0"); + assertEquals(21.0, locationRemote.getTargetTemperatureState().getTemperature(), 1.0, "Initial TargetTemperature of location[" + locationRemote.getLabel() + "] is not 21.0"); // test if on open reed sensor target temperature is set to 13.0 reedContactController.applyServiceState(States.Contact.OPEN, ServiceType.CONTACT_STATE_SERVICE); @@ -109,10 +110,10 @@ public void testHeaterEnergySavingAgent() throws Exception { temperatureControllerStateAwaiter.waitForState((TemperatureControllerData data) -> data.getTargetTemperatureState().getTemperature() == 13.0); locationStateAwaiter.waitForState((LocationData data) -> data.getTargetTemperatureState().getTemperature() == 13.0); - assertEquals("ContactState of ReedContact[" + reedContactRemote.getLabel() + "] has not switched to OPEN", ContactState.State.OPEN, reedContactRemote.getContactState().getValue()); - assertEquals("ContactState of Connection[" + connectionRemote.getLabel() + "] has not switched to OPEN", WindowState.State.OPEN, connectionRemote.getWindowState().getValue()); - assertEquals("TargetTemperature of TemperatureController[" + temperatureControllerRemote.getLabel() + "] has not switched to 13.0", 13.0, temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 1.0); - assertEquals("TargetTemperature of location[" + locationRemote.getLabel() + "] has not switched to 13.0", 13.0, locationRemote.getTargetTemperatureState().getTemperature(), 1.0); + assertEquals(ContactState.State.OPEN, reedContactRemote.getContactState().getValue(), "ContactState of ReedContact[" + reedContactRemote.getLabel() + "] has not switched to OPEN"); + assertEquals(WindowState.State.OPEN, connectionRemote.getWindowState().getValue(), "ContactState of Connection[" + connectionRemote.getLabel() + "] has not switched to OPEN"); + assertEquals(13.0, temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 1.0, "TargetTemperature of TemperatureController[" + temperatureControllerRemote.getLabel() + "] has not switched to 13.0"); + assertEquals(13.0, locationRemote.getTargetTemperatureState().getTemperature(), 1.0, "TargetTemperature of location[" + locationRemote.getLabel() + "] has not switched to 13.0"); // Obsoled as functionality of HeaterEnergySavingAgent was reduced // // test if on closed reedsensor target temperature is set back to 21.0 diff --git a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/IlluminationLightSavingAgentTest.java b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/IlluminationLightSavingAgentTest.java index 3d89b9eee2..f568755ab9 100644 --- a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/IlluminationLightSavingAgentTest.java +++ b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/IlluminationLightSavingAgentTest.java @@ -22,8 +22,10 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; + import org.openbase.app.test.agent.AbstractBCOAgentManagerTest; import org.openbase.bco.dal.lib.layer.service.operation.PowerStateOperationService; import org.openbase.bco.dal.lib.layer.service.provider.IlluminanceStateProviderService; @@ -53,8 +55,6 @@ import org.openbase.type.domotic.unit.dal.LightSensorDataType.LightSensorData; import org.openbase.type.domotic.unit.location.LocationDataType.LocationData; -import static org.junit.Assert.assertEquals; - /** * * @author Timo * Michalski @@ -134,10 +134,10 @@ public void testIlluminationLightSavingAgent() throws Exception { LOGGER.info("WaitFor ColorableLight power update"); colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.ON); - assertEquals("Initial Illuminance of LightSensor[" + lightSensorRemote.getLabel() + "] is not 5000", 5000.0, lightSensorRemote.getIlluminanceState().getIlluminance(), 1); - assertEquals("Initial Illuminance of Location[" + locationRemote.getLabel() + "] is not 5000", 5000.0, locationRemote.getIlluminanceState().getIlluminance(), 1); - assertEquals("Initial PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] is not ON", PowerState.State.ON, colorableLightRemote.getPowerState().getValue()); - assertEquals("Initial PowerState of Location[" + locationRemote.getLabel() + "] is not ON", PowerState.State.ON, locationRemote.getPowerState().getValue()); + assertEquals(5000.0, lightSensorRemote.getIlluminanceState().getIlluminance(), 1, "Initial Illuminance of LightSensor[" + lightSensorRemote.getLabel() + "] is not 5000"); + assertEquals(5000.0, locationRemote.getIlluminanceState().getIlluminance(), 1, "Initial Illuminance of Location[" + locationRemote.getLabel() + "] is not 5000"); + assertEquals(PowerState.State.ON, colorableLightRemote.getPowerState().getValue(), "Initial PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] is not ON"); + assertEquals(PowerState.State.ON, locationRemote.getPowerState().getValue(), "Initial PowerState of Location[" + locationRemote.getLabel() + "] is not ON"); // test if on high illuminance lights get switched off lightSensorController.applyServiceState(IlluminanceState.newBuilder().setIlluminance(7000.0).build(), ServiceType.ILLUMINANCE_STATE_SERVICE); @@ -150,9 +150,9 @@ public void testIlluminationLightSavingAgent() throws Exception { // LOGGER.info("WaitFor Location power update"); // locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); - assertEquals("Initial Illuminance of LightSensor[" + lightSensorRemote.getLabel() + "] is not 7000", 7000.0, lightSensorRemote.getIlluminanceState().getIlluminance(), 1); - assertEquals("Initial Illuminance of Location[" + locationRemote.getLabel() + "] is not 7000", 7000.0, locationRemote.getIlluminanceState().getIlluminance(), 1); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to OFF", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); + assertEquals(7000.0, lightSensorRemote.getIlluminanceState().getIlluminance(), 1, "Initial Illuminance of LightSensor[" + lightSensorRemote.getLabel() + "] is not 7000"); + assertEquals(7000.0, locationRemote.getIlluminanceState().getIlluminance(), 1, "Initial Illuminance of Location[" + locationRemote.getLabel() + "] is not 7000"); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to OFF"); //assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched to OFF", PowerState.State.OFF, locationRemote.getPowerState().getValue()); // Not Part of this agent, is it? As it is just cancelling its action and is not responsible for behavior afterwards. @@ -167,9 +167,9 @@ public void testIlluminationLightSavingAgent() throws Exception { // LOGGER.info("WaitFor Location power update"); // locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); - assertEquals("Initial Illuminance of LightSensor[" + lightSensorRemote.getLabel() + "] is not 2000", 2000.0, lightSensorRemote.getIlluminanceState().getIlluminance(), 1); - assertEquals("Initial Illuminance of Location[" + locationRemote.getLabel() + "] is not 2000", 2000.0, locationRemote.getIlluminanceState().getIlluminance(), 1); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has changes without intention", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); + assertEquals(2000.0, lightSensorRemote.getIlluminanceState().getIlluminance(), 1, "Initial Illuminance of LightSensor[" + lightSensorRemote.getLabel() + "] is not 2000"); + assertEquals(2000.0, locationRemote.getIlluminanceState().getIlluminance(), 1, "Initial Illuminance of Location[" + locationRemote.getLabel() + "] is not 2000"); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has changes without intention"); //assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has changes without intention", PowerState.State.OFF, locationRemote.getPowerState().getValue()); } diff --git a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PowerStateSynchroniserAgentTest.java b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PowerStateSynchroniserAgentTest.java index 53a5cf1bbd..1a7c37bbe1 100644 --- a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PowerStateSynchroniserAgentTest.java +++ b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PowerStateSynchroniserAgentTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.app.test.agent.AbstractBCOAgentManagerTest; @@ -52,8 +53,6 @@ import org.openbase.type.vision.HSBColorType.HSBColor; import org.slf4j.LoggerFactory; -import static org.junit.Assert.assertEquals; - /** * * @author Tamino Huxohl */ @@ -97,8 +96,8 @@ public void testPowerStateSyncAgent() throws Exception { LOGGER.info("Turn off targets"); waitForExecution(colorableLightRemote.setPowerState(State.OFF)); waitForExecution(powerSwitchRemote.setPowerState(State.OFF)); - assertEquals("Target 1 has not turned off", State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("Target 2 has not turned off", State.OFF, powerSwitchRemote.getPowerState().getValue()); + assertEquals(State.OFF, colorableLightRemote.getPowerState().getValue(), "Target 1 has not turned off"); + assertEquals(State.OFF, powerSwitchRemote.getPowerState().getValue(), "Target 2 has not turned off"); colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.OFF, STATE_AWAIT_TIMEOUT); powerSwitchStateAwaiter.waitForState((PowerSwitchData data) -> data.getPowerState().getValue() == PowerState.State.OFF, STATE_AWAIT_TIMEOUT); // TODO: also validate that the executing action has expected settings: @@ -160,8 +159,8 @@ public void update(DataProvider source, PowerSwitchData data) t waitForExecution(powerSwitchRemote.setPowerState(State.ON)); // TODO: in a real test scenario the other target would turn on as well -> should the agent request its state as well? // this could get pretty messy: imagine a scene turning on all targets at once... - assertEquals("Target 1 did not stay off", State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("Target 2 has not turned on", State.ON, powerSwitchRemote.getPowerState().getValue()); + assertEquals(State.OFF, colorableLightRemote.getPowerState().getValue(), "Target 1 did not stay off"); + assertEquals(State.ON, powerSwitchRemote.getPowerState().getValue(), "Target 2 has not turned on"); dimmerStateAwaiter.waitForState((DimmerData data) -> data.getPowerState().getValue() == PowerState.State.ON); // TODO: validate that according flags are set by the agent @@ -171,35 +170,35 @@ public void update(DataProvider source, PowerSwitchData data) t System.out.println("\n\n\n"); // validate received requested states - assertEquals("Received at least one unknown requested state!", false, deliveredUnknownRequestedState[0]); + assertEquals(false, deliveredUnknownRequestedState[0], "Received at least one unknown requested state!"); // turn target off which should make the agent turn off the source LOGGER.info("Turn all targets off"); waitForExecution(powerSwitchRemote.setPowerState(State.OFF)); - assertEquals("Target 1 did not stay off", State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("Target 2 has not turned off", State.OFF, powerSwitchRemote.getPowerState().getValue()); + assertEquals(State.OFF, colorableLightRemote.getPowerState().getValue(), "Target 1 did not stay off"); + assertEquals(State.OFF, powerSwitchRemote.getPowerState().getValue(), "Target 2 has not turned off"); dimmerStateAwaiter.waitForState((DimmerData data) -> data.getPowerState().getValue() == PowerState.State.OFF); Thread.sleep(1000); System.out.println("\n\n\n"); // validate received requested states - assertEquals("Received at least one unknown requested state!", false, deliveredUnknownRequestedState[0]); + assertEquals(false, deliveredUnknownRequestedState[0], "Received at least one unknown requested state!"); // change color of the target which should also make the agent turn on the source LOGGER.info("Set color of target"); final HSBColor hsbColor = HSBColor.newBuilder().setHue(0).setSaturation(1d).setBrightness(1d).build(); waitForExecution(colorableLightRemote.setColor(hsbColor)); - assertEquals("Target 1 has not turned on", State.ON, colorableLightRemote.getPowerState().getValue()); - assertEquals("Target 1 does not have the expected color", hsbColor, colorableLightRemote.getColorState().getColor().getHsbColor()); - assertEquals("Target 2 has not stayed off", State.OFF, powerSwitchRemote.getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getPowerState().getValue(), "Target 1 has not turned on"); + assertEquals(hsbColor, colorableLightRemote.getColorState().getColor().getHsbColor(), "Target 1 does not have the expected color"); + assertEquals(State.OFF, powerSwitchRemote.getPowerState().getValue(), "Target 2 has not stayed off"); dimmerStateAwaiter.waitForState((DimmerData data) -> data.getPowerState().getValue() == PowerState.State.ON); Thread.sleep(1000); System.out.println("\n\n\n"); // validate received requested states - assertEquals("Received at least one unknown requested state!", false, deliveredUnknownRequestedState[0]); + assertEquals(false, deliveredUnknownRequestedState[0], "Received at least one unknown requested state!"); } @Override diff --git a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PresenceLightAgentTest.java b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PresenceLightAgentTest.java index eb32627c25..f3d9d8c1e4 100644 --- a/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PresenceLightAgentTest.java +++ b/module/app/preset/src/test/java/org/openbase/bco/app/preset/agent/PresenceLightAgentTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Timeout; import org.openbase.app.test.agent.AbstractBCOAgentManagerTest; import org.junit.jupiter.api.Test; @@ -59,7 +60,7 @@ import org.openbase.type.domotic.unit.dal.MotionDetectorDataType.MotionDetectorData; import org.openbase.type.domotic.unit.location.LocationDataType.LocationData; -import static org.junit.Assert.assertEquals; + /** * * @author Timo Michalski @@ -75,7 +76,7 @@ public class PresenceLightAgentTest extends AbstractBCOAgentManagerTest { public PresenceLightAgentTest() { } - //@BeforeClass //uncomment to enable debug mode + //@BeforeAll //uncomment to enable debug mode public static void showActionInspector() throws Throwable { JPService.registerProperty(JPDebugMode.class, true); @@ -124,9 +125,9 @@ public void testPresenceLightAgent() throws Exception { lightSensorController.applyServiceState(Illuminance.DARK, ServiceType.ILLUMINANCE_STATE_SERVICE); lightSensorStateAwaiter.waitForState((LightSensorData data) -> data.getIlluminanceState().getValue() == IlluminanceState.State.DARK); - assertEquals("Initial MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] is not NO_MOTION", MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("Initial PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] is not OFF", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("Initial PowerState of Location[" + locationRemote.getLabel() + "] is not OFF", PowerState.State.OFF, locationRemote.getPowerState().getValue()); + assertEquals(MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue(), "Initial MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] is not NO_MOTION"); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "Initial PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] is not OFF"); + assertEquals(PowerState.State.OFF, locationRemote.getPowerState().getValue(), "Initial PowerState of Location[" + locationRemote.getLabel() + "] is not OFF"); // test if on motion the lights are turned on @@ -136,10 +137,10 @@ public void testPresenceLightAgent() throws Exception { colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.ON); locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.ON); - assertEquals("MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to MOTION", MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to PRESENT.", PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to ON", PowerState.State.ON, colorableLightRemote.getPowerState().getValue()); - assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched to ON", PowerState.State.ON, locationRemote.getPowerState().getValue()); + assertEquals(MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue(), "MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to MOTION"); + assertEquals(PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue(), "PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to PRESENT."); + assertEquals(PowerState.State.ON, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched to ON"); + assertEquals(PowerState.State.ON, locationRemote.getPowerState().getValue(), "PowerState of Location[" + locationRemote.getLabel() + "] has not switched to ON"); // for (ActionDescription actionDescription : colorableLightRemote.getActionList()) { // System.out.println("action: " + actionDescription.getId()); @@ -154,10 +155,10 @@ public void testPresenceLightAgent() throws Exception { colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.OFF); locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); - assertEquals("MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION", MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT.", PresenceState.State.ABSENT, locationRemote.getPresenceState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched back to off", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched back to off", PowerState.State.OFF, locationRemote.getPowerState().getValue()); + assertEquals(MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue(), "MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION"); + assertEquals(PresenceState.State.ABSENT, locationRemote.getPresenceState().getValue(), "PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT."); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched back to off"); + assertEquals(PowerState.State.OFF, locationRemote.getPowerState().getValue(), "PowerState of Location[" + locationRemote.getLabel() + "] has not switched back to off"); // test if the lights stay off after bright illuminance @@ -170,11 +171,11 @@ public void testPresenceLightAgent() throws Exception { colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.OFF); locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); - assertEquals("MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to MOTION", MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to PRESENT.", PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue()); - assertEquals("Illuminance of Location[" + locationRemote.getLabel() + "] has not set to SUNNY.", IlluminanceState.State.SUNNY, locationRemote.getIlluminanceState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not stayed off", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not stayed off", PowerState.State.OFF, locationRemote.getPowerState().getValue()); + assertEquals(MotionState.State.MOTION, motionDetectorRemote.getMotionState().getValue(), "MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to MOTION"); + assertEquals(PresenceState.State.PRESENT, locationRemote.getPresenceState().getValue(), "PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to PRESENT."); + assertEquals(IlluminanceState.State.SUNNY, locationRemote.getIlluminanceState().getValue(), "Illuminance of Location[" + locationRemote.getLabel() + "] has not set to SUNNY."); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not stayed off"); + assertEquals(PowerState.State.OFF, locationRemote.getPowerState().getValue(), "PowerState of Location[" + locationRemote.getLabel() + "] has not stayed off"); // test if the lights switch on after darkness @@ -183,9 +184,9 @@ public void testPresenceLightAgent() throws Exception { colorableLightStateAwaiter.waitForState((ColorableLightData data) -> data.getPowerState().getValue() == PowerState.State.ON); locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.ON); - assertEquals("Illuminance of Location[" + locationRemote.getLabel() + "] has not set to BRIGHT.", IlluminanceState.State.DARK, locationRemote.getIlluminanceState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched on", PowerState.State.ON, colorableLightRemote.getPowerState().getValue()); - assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched on", PowerState.State.ON, locationRemote.getPowerState().getValue()); + assertEquals(IlluminanceState.State.DARK, locationRemote.getIlluminanceState().getValue(), "Illuminance of Location[" + locationRemote.getLabel() + "] has not set to BRIGHT."); + assertEquals(PowerState.State.ON, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched on"); + assertEquals(PowerState.State.ON, locationRemote.getPowerState().getValue(), "PowerState of Location[" + locationRemote.getLabel() + "] has not switched on"); // test if the lights switch off after no motion and brightness @@ -197,11 +198,11 @@ public void testPresenceLightAgent() throws Exception { locationStateAwaiter.waitForState((LocationData data) -> data.getPowerState().getValue() == PowerState.State.OFF); lightSensorStateAwaiter.waitForState((LightSensorData data) -> data.getIlluminanceState().getValue() == IlluminanceState.State.SUNNY); - assertEquals("MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION", MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue()); - assertEquals("PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT.", PresenceState.State.ABSENT, locationRemote.getPresenceState().getValue()); - assertEquals("PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched back to off", PowerState.State.OFF, colorableLightRemote.getPowerState().getValue()); - assertEquals("PowerState of Location[" + locationRemote.getLabel() + "] has not switched back to off", PowerState.State.OFF, locationRemote.getPowerState().getValue()); - assertEquals("Illuminance of Location[" + locationRemote.getLabel() + "] has not set to BRIGHT.", IlluminanceState.State.SUNNY, locationRemote.getIlluminanceState().getValue()); + assertEquals(MotionState.State.NO_MOTION, motionDetectorRemote.getMotionState().getValue(), "MotionState of MotionDetector[" + motionDetectorRemote.getLabel() + "] has not switched to NO_MOTION"); + assertEquals(PresenceState.State.ABSENT, locationRemote.getPresenceState().getValue(), "PresenceState of Location[" + locationRemote.getLabel() + "] has not switched to ABSENT."); + assertEquals(PowerState.State.OFF, colorableLightRemote.getPowerState().getValue(), "PowerState of ColorableLight[" + colorableLightRemote.getLabel() + "] has not switched back to off"); + assertEquals(PowerState.State.OFF, locationRemote.getPowerState().getValue(), "PowerState of Location[" + locationRemote.getLabel() + "] has not switched back to off"); + assertEquals(IlluminanceState.State.SUNNY, locationRemote.getIlluminanceState().getValue(), "Illuminance of Location[" + locationRemote.getLabel() + "] has not set to BRIGHT."); // cancel initial control cancelAllTestActions(); @@ -217,7 +218,7 @@ public void testPresenceLightAgent() throws Exception { // make sure all other actions are done final RemoteAction remoteAction = new RemoteAction(actionDescription); remoteAction.waitForRegistration(); - assertEquals("There is still the running Action[" + MultiLanguageTextProcessor.getBestMatch(remoteAction.getActionDescription().getDescription(), "?") + "] found which should actually be terminated!", true, remoteAction.isDone()); + assertEquals(true, remoteAction.isDone(), "There is still the running Action[" + MultiLanguageTextProcessor.getBestMatch(remoteAction.getActionDescription().getDescription(), "?") + "] found which should actually be terminated!"); } } diff --git a/module/app/test/build.gradle.kts b/module/app/test/build.gradle.kts index 23686607a1..c51e556c49 100644 --- a/module/app/test/build.gradle.kts +++ b/module/app/test/build.gradle.kts @@ -8,6 +8,9 @@ plugins { dependencies { api(project(":bco.dal.test")) + implementation("org.junit.jupiter:junit-jupiter:[5.8,5.9-alpha)") + implementation ("org.junit.jupiter:junit-jupiter-api:[5.8,5.9-alpha)") + implementation ("org.junit.jupiter:junit-jupiter-engine:[5.8,5.9-alpha)") } description = "BCO App Test Framework" diff --git a/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAgentManagerTest.java b/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAgentManagerTest.java index 8e5533ca44..25d19e6b5b 100644 --- a/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAgentManagerTest.java +++ b/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAgentManagerTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.openbase.bco.dal.remote.layer.unit.Units; import org.openbase.bco.dal.remote.layer.unit.agent.AgentRemote; import org.openbase.bco.dal.remote.layer.unit.util.UnitStateAwaiter; @@ -46,8 +46,8 @@ public abstract class AbstractBCOAgentManagerTest extends BCOAppTest { protected UnitConfig agentConfig = null; protected AgentRemote agentRemote = null; - @Before - public void setUp() throws Exception { + @BeforeEach + public void setupAgentManager() throws Exception { try { // register agent agentConfig = Registries.getUnitRegistry().registerUnitConfig(getAgentConfig()).get(5, TimeUnit.SECONDS); diff --git a/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAppManagerTest.java b/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAppManagerTest.java index b5bee18c43..26a99a3795 100644 --- a/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAppManagerTest.java +++ b/module/app/test/src/main/java/org/openbase/app/test/agent/AbstractBCOAppManagerTest.java @@ -22,9 +22,9 @@ * #L% */ -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.openbase.bco.dal.remote.layer.unit.Units; import org.openbase.bco.dal.remote.layer.unit.app.AppRemote; import org.openbase.bco.dal.remote.layer.unit.util.UnitStateAwaiter; @@ -49,18 +49,8 @@ public abstract class AbstractBCOAppManagerTest extends BCOAppTest { protected UnitConfig appConfig = null; protected AppRemote appRemote = null; - @BeforeClass - public static void setUpClass() throws Throwable { - BCOAppTest.setUpClass(); - } - - @AfterClass - public static void tearDownClass() throws Throwable { - BCOAppTest.tearDownClass(); - } - - @Before - public void setUp() throws Exception { + @BeforeEach + public void prepareAppManager() throws Exception { try { // setup and register app class AppClass.Builder appClassBuilder = AppClass.newBuilder(); diff --git a/module/app/test/src/main/java/org/openbase/app/test/agent/BCOAppTest.java b/module/app/test/src/main/java/org/openbase/app/test/agent/BCOAppTest.java index aa470af265..4ad96fa114 100644 --- a/module/app/test/src/main/java/org/openbase/app/test/agent/BCOAppTest.java +++ b/module/app/test/src/main/java/org/openbase/app/test/agent/BCOAppTest.java @@ -22,9 +22,9 @@ * #L% */ -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.openbase.bco.dal.control.layer.unit.agent.AgentManagerLauncher; import org.openbase.bco.dal.control.layer.unit.app.AppManagerLauncher; import org.openbase.bco.dal.control.layer.unit.device.DeviceManagerLauncher; @@ -46,12 +46,9 @@ public class BCOAppTest extends AbstractBCOTest { protected static DeviceManagerLauncher deviceManagerLauncher; protected static LocationManagerLauncher locationManagerLauncher; - @BeforeClass - public static void setUpClass() throws Throwable { + @BeforeAll + public static void setupBcoApp() throws Throwable { try { - LOGGER.info("Start app test setup..."); - AbstractBCOTest.setUpClass(); - LOGGER.trace("Start device manager..."); deviceManagerLauncher = new DeviceManagerLauncher(); deviceManagerLauncher.launch().get(); @@ -79,8 +76,8 @@ public static void setUpClass() throws Throwable { } } - @AfterClass - public static void tearDownClass() throws Throwable { + @AfterAll + public static void tearDownBCOApp() throws Throwable { LOGGER.info("Tear down app tests..."); try { if (appManagerLauncher != null) { @@ -95,7 +92,6 @@ public static void tearDownClass() throws Throwable { if (deviceManagerLauncher != null) { deviceManagerLauncher.shutdown(); } - AbstractBCOTest.tearDownClass(); LOGGER.info("App tests finished!"); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); @@ -107,7 +103,7 @@ public static void tearDownClass() throws Throwable { * * @throws InterruptedException is thrown if the thread was externally interrupted */ - @After + @AfterEach public void cancelAllOngoingActions() throws InterruptedException { LOGGER.info("Cancel all ongoing actions..."); try { diff --git a/module/app/util/src/test/java/org/openbase/bco/app/util/AbstractBCOManagerTest.java b/module/app/util/src/test/java/org/openbase/bco/app/util/AbstractBCOManagerTest.java index 145f016376..f5ba811226 100644 --- a/module/app/util/src/test/java/org/openbase/bco/app/util/AbstractBCOManagerTest.java +++ b/module/app/util/src/test/java/org/openbase/bco/app/util/AbstractBCOManagerTest.java @@ -53,10 +53,8 @@ public class AbstractBCOManagerTest extends AbstractBCOTest { protected static UserManagerLauncher userManagerLauncher; @BeforeAll - public static void setUpClass() throws Throwable { + public static void setupBCOManager() throws Throwable { try { - AbstractBCOTest.setUpClass(); - agentManagerLauncher = new AgentManagerLauncher(); agentManagerLauncher.launch().get(); appManagerLauncher = new AppManagerLauncher(); @@ -75,7 +73,7 @@ public static void setUpClass() throws Throwable { } @AfterAll - public static void tearDownClass() throws Throwable { + public static void tearDownBCOManager() throws Throwable { try { if (agentManagerLauncher != null) { agentManagerLauncher.shutdown(); @@ -95,8 +93,6 @@ public static void tearDownClass() throws Throwable { if (userManagerLauncher != null) { userManagerLauncher.shutdown(); } - - AbstractBCOTest.tearDownClass(); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); } diff --git a/module/app/util/src/test/java/org/openbase/bco/app/util/UnitTransformationTest.java b/module/app/util/src/test/java/org/openbase/bco/app/util/UnitTransformationTest.java index c10059c811..94bcb87625 100644 --- a/module/app/util/src/test/java/org/openbase/bco/app/util/UnitTransformationTest.java +++ b/module/app/util/src/test/java/org/openbase/bco/app/util/UnitTransformationTest.java @@ -20,7 +20,6 @@ * #L% */ -import org.junit.*; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -37,7 +36,7 @@ import org.openbase.type.domotic.unit.UnitConfigType.UnitConfig; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; import org.openbase.type.geometry.PoseType; - +import static org.junit.jupiter.api.Assertions.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -52,16 +51,6 @@ public class UnitTransformationTest extends AbstractBCOManagerTest { public UnitTransformationTest() { } - @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCOManagerTest.setUpClass(); - } - - @AfterAll - public static void tearDownClass() throws Throwable { - AbstractBCOManagerTest.tearDownClass(); - } - @Test @Timeout(30) public void testUnitTransformation() throws Exception { @@ -72,7 +61,7 @@ public void testUnitTransformation() throws Exception { // load bound to unithost unit UnitConfig lightUnitConfig = Registries.getUnitRegistry().getUnitConfigByAlias(MockRegistry.getUnitAlias(UnitType.COLORABLE_LIGHT)); - Assert.assertTrue(lightUnitConfig.getBoundToUnitHost()); + assertTrue(lightUnitConfig.getBoundToUnitHost()); // change unit host position UnitConfig.Builder hostUnitConfigBuilder = Registries.getUnitRegistry().getUnitConfigById(lightUnitConfig.getUnitHostId()).toBuilder(); @@ -91,9 +80,9 @@ public void testUnitTransformation() throws Exception { // todo: sleep is actually to long! Thread.sleep(500); - Assert.assertEquals("Positions are not synchronized!", lightUnitConfig.getPlacementConfig().getPose(), hostUnitConfig.getPlacementConfig().getPose()); - Assert.assertNotEquals("TransformationFrameId are not unique!", lightUnitConfig.getPlacementConfig().getTransformationFrameId(), hostUnitConfig.getPlacementConfig().getTransformationFrameId()); - Assert.assertEquals("Transformations are not synchronized!", Units.getRootToUnitTransformation(lightUnitConfig).get(5, TimeUnit.SECONDS).getTransform(), Units.getRootToUnitTransformation(hostUnitConfig).get(5, TimeUnit.SECONDS).getTransform()); + assertEquals(lightUnitConfig.getPlacementConfig().getPose(), hostUnitConfig.getPlacementConfig().getPose(), "Positions are not synchronized!"); + assertNotEquals(lightUnitConfig.getPlacementConfig().getTransformationFrameId(), hostUnitConfig.getPlacementConfig().getTransformationFrameId(), "TransformationFrameId are not unique!"); + assertEquals(Units.getRootToUnitTransformation(lightUnitConfig).get(5, TimeUnit.SECONDS).getTransform(), Units.getRootToUnitTransformation(hostUnitConfig).get(5, TimeUnit.SECONDS).getTransform(), "Transformations are not synchronized!"); // verify that all other unit transformations are available verifyTransformations(); diff --git a/module/app/util/src/test/java/org/openbase/bco/device/openhab/registry/synchronizer/SynchronizationProcessorTest.java b/module/app/util/src/test/java/org/openbase/bco/device/openhab/registry/synchronizer/SynchronizationProcessorTest.java index 386a68bbf7..fafd9540e0 100644 --- a/module/app/util/src/test/java/org/openbase/bco/device/openhab/registry/synchronizer/SynchronizationProcessorTest.java +++ b/module/app/util/src/test/java/org/openbase/bco/device/openhab/registry/synchronizer/SynchronizationProcessorTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -33,20 +33,18 @@ class SynchronizationProcessorTest { @Test @Timeout(20) void getUniquePrefix() { - Assert.assertNotEquals( - "Prefix is not unique!", + assertNotEquals( SynchronizationProcessor.getUniquePrefix("00:17:88:01:08:0c:f4:60-02-fc00"), - SynchronizationProcessor.getUniquePrefix("00:17:88:01:08:70:3c:a9-02-fc00") + SynchronizationProcessor.getUniquePrefix("00:17:88:01:08:70:3c:a9-02-fc00"), + "Prefix is not unique!" ); - Assert.assertEquals( - "Prefix is not unique!", + assertEquals( SynchronizationProcessor.getUniquePrefix("00:17:88:01:08:0c:f4:60-02-fc00"), - SynchronizationProcessor.getUniquePrefix("00:17:88:01:08:0c:f4:60-02-fc22") + SynchronizationProcessor.getUniquePrefix("00:17:88:01:08:0c:f4:60-02-fc22"), + "Prefix is not unique!" ); - - } } diff --git a/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/AuthenticationServerHandler.java b/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/AuthenticationServerHandler.java index fe50087166..e31f4def0e 100644 --- a/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/AuthenticationServerHandler.java +++ b/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/AuthenticationServerHandler.java @@ -51,7 +51,7 @@ */ public class AuthenticationServerHandler { - public static final long MAX_TIME_DIFF_SERVER_CLIENT = JPService.testMode() ? TimeUnit.SECONDS.toMillis(5) : TimeUnit.MINUTES.toMillis(2); + public static final long MAX_TIME_DIFF_SERVER_CLIENT = JPService.testMode() ? TimeUnit.SECONDS.toMillis(1) : TimeUnit.MINUTES.toMillis(2); /** * Handles a Key Distribution Center (KDC) login request diff --git a/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/SessionManager.java b/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/SessionManager.java index c9f917ffb9..acf629d705 100644 --- a/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/SessionManager.java +++ b/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/SessionManager.java @@ -336,15 +336,6 @@ public synchronized void loginClient(final String id, final LoginCredentials cre */ private synchronized void internalLogin(final String id, final LoginCredentials loginCredentials, final boolean stayLoggedIn, final boolean isUser) throws CouldNotPerformException, NotAvailableException { try { - // validate authentication property - try { - if (!JPService.getProperty(JPAuthentication.class).getValue()) { - throw new CouldNotPerformException("Could not login. Authentication is disabled"); - } - } catch (JPNotAvailableException ex) { - throw new CouldNotPerformException("Could not check JPEnableAuthenticationProperty", ex); - } - // handle cases when somebody is already logged in if (this.isLoggedIn()) { // do nothing if same user or client is already logged in diff --git a/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/jp/JPSessionTimeout.java b/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/jp/JPSessionTimeout.java index 096cfac894..99ea7989c3 100644 --- a/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/jp/JPSessionTimeout.java +++ b/module/authentication/lib/src/main/java/org/openbase/bco/authentication/lib/jp/JPSessionTimeout.java @@ -36,8 +36,8 @@ public class JPSessionTimeout extends AbstractJPTime { public final static String[] COMMAND_IDENTIFIERS = {"--session-timeout"}; - private static final long DEFAULT_TIMEOUT = TimeUnit.DAYS.toMillis(7); - private static final long DEFAULT_TEST_TIMEOUT = TimeUnit.MINUTES.toMillis(15); + public static final long DEFAULT_TIMEOUT = TimeUnit.DAYS.toMillis(7); + public static final long DEFAULT_TEST_TIMEOUT = TimeUnit.MINUTES.toMillis(15); public JPSessionTimeout() { super(COMMAND_IDENTIFIERS); diff --git a/module/authentication/test/build.gradle.kts b/module/authentication/test/build.gradle.kts index 2890b2a6c0..1b88e2097a 100644 --- a/module/authentication/test/build.gradle.kts +++ b/module/authentication/test/build.gradle.kts @@ -6,10 +6,19 @@ plugins { id("org.openbase.bco") } +configurations { + +} + dependencies { api(project(":bco.authentication.core")) api(project(":bco.authentication.lib")) - api("org.testcontainers:testcontainers:_") + api("org.testcontainers:junit-jupiter:_") { + exclude(group = "junit", module = "junit") + } + api("io.quarkus:quarkus-junit4-mock:_") + api("org.junit.jupiter:junit-jupiter:_") + api("org.junit.jupiter:junit-jupiter-api:_") } description = "BCO Authentication Test" diff --git a/module/authentication/test/src/main/java/org/openbase/bco/authentication/mock/MqttIntegrationTest.java b/module/authentication/test/src/main/java/org/openbase/bco/authentication/mock/MqttIntegrationTest.java index 0af7ff5dbd..b515ed9a6b 100644 --- a/module/authentication/test/src/main/java/org/openbase/bco/authentication/mock/MqttIntegrationTest.java +++ b/module/authentication/test/src/main/java/org/openbase/bco/authentication/mock/MqttIntegrationTest.java @@ -22,9 +22,13 @@ * #L% */ -import org.junit.AfterClass; -import org.junit.BeforeClass; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.openbase.jps.core.JPService; +import org.openbase.jps.exception.JPServiceException; import org.openbase.jul.communication.jp.JPComHost; import org.openbase.jul.communication.jp.JPComPort; import org.openbase.jul.communication.mqtt.SharedMqttClient; @@ -43,8 +47,8 @@ public class MqttIntegrationTest { public static Path mosquittoConfig; public static GenericContainer broker; - @BeforeClass - public static void setUpClass() throws Throwable { + @BeforeAll + public static void setupMqtt() throws Throwable { mosquittoConfig = Files.createTempFile("mosquitto_", ".conf"); Files.write(mosquittoConfig, Arrays.asList( "allow_anonymous true", @@ -59,16 +63,26 @@ public static void setUpClass() throws Throwable { BindMode.READ_ONLY ); broker.withStartupTimeout(Duration.ofSeconds(30)).start(); - - JPService.registerProperty(JPComPort.class, broker.getFirstMappedPort()); - JPService.registerProperty(JPComHost.class, broker.getHost()); - JPService.setupJUnitTestMode(); } - @AfterClass - public static void tearDownClass() throws Throwable { + @AfterAll + public static void tearDownMQTT() throws Throwable { SharedMqttClient.INSTANCE.waitForShutdown(); broker.stop(); Files.delete(mosquittoConfig); } + + /** + * Overwrite method to set custom test properties. + */ + public void setupTestProperties() { } + + @BeforeEach + public void customSetup() throws JPServiceException { + JPService.reset(); + JPService.registerProperty(JPComPort.class, broker.getFirstMappedPort()); + JPService.registerProperty(JPComHost.class, broker.getHost()); + JPService.setupJUnitTestMode(); + setupTestProperties(); + } } diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatedCommunicationTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatedCommunicationTest.java index f451733661..0e3ccaf083 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatedCommunicationTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatedCommunicationTest.java @@ -21,8 +21,9 @@ * . * #L% */ - +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.authentication.core.AuthenticationController; @@ -44,9 +45,6 @@ import java.util.List; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; - public class AuthenticatedCommunicationTest extends AuthenticationTest { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AuthenticatedCommunicationTest.class); @@ -56,10 +54,8 @@ public class AuthenticatedCommunicationTest extends AuthenticationTest { private static final String USER_ID = "authenticated"; private static final String USER_PASSWORD = "communication"; - @BeforeAll - public static void setUpClass() throws Throwable { - AuthenticationTest.setUpClass(); - + @BeforeEach + public void setupUser() throws Throwable { // register a user from which a ticket can be validated registerUser(); } @@ -115,9 +111,9 @@ public void testCommunication() throws Exception { LOGGER.info("Synchronizing remote finished! " + data.getAgentUnitConfigCount() + " agents"); assertEquals( - "Without being logged in only the 'OtherAgent' should be visible by the remote.", expectedAgentsLoggedOut, - data.getAgentUnitConfigList() + data.getAgentUnitConfigList(), + "Without being logged in only the 'OtherAgent' should be visible by the remote." ); LOGGER.info("Login!"); @@ -127,9 +123,9 @@ public void testCommunication() throws Exception { LOGGER.info("Synchronizing remote finished! " + data.getAgentUnitConfigCount() + " agents"); assertEquals( - "Being logged in both agens should be visible by the remote.", expectedAgentsLoggedIn, - data.getAgentUnitConfigList() + data.getAgentUnitConfigList(), + "Being logged in both agens should be visible by the remote." ); //expectedAgents.add(userAgentConfig.build()); assertTrue(remoteService.getData().getAgentUnitConfigList().contains(otherAgentConfig.build())); @@ -141,9 +137,9 @@ public void testCommunication() throws Exception { LOGGER.info("Synchronizing remote finished! " + data.getAgentUnitConfigCount() + " agents"); assertEquals( - "Only 'OtherAgent' should be visible again after logging out.", expectedAgentsLoggedOut, - data.getAgentUnitConfigList() + data.getAgentUnitConfigList(), + "Only 'OtherAgent' should be visible again after logging out." ); remoteService.shutdown(); @@ -171,9 +167,9 @@ protected UnitRegistryData filterDataForUser(UnitRegistryData.Builder dataBuilde } } if (userClientPair.getClientId().isEmpty() && userClientPair.getUserId().isEmpty()) { - assertTrue("Other permissions should only show the OtherAgent", dataBuilder.build().getAgentUnitConfigCount() < 2); + assertTrue(dataBuilder.build().getAgentUnitConfigCount() < 2, "Other permissions should only show the OtherAgent"); } else { - assertEquals("For a logged in user both agents should be visible", 2, dataBuilder.build().getAgentUnitConfigCount()); + assertEquals(2, dataBuilder.build().getAgentUnitConfigCount(), "For a logged in user both agents should be visible"); } return dataBuilder.build(); } diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticationTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticationTest.java index 29b5b85fff..7b6a711661 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticationTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticationTest.java @@ -24,8 +24,9 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.openbase.bco.authentication.core.AuthenticationController; import org.openbase.bco.authentication.lib.AuthenticatedServerManager; import org.openbase.bco.authentication.lib.CachedAuthenticationRemote; @@ -40,36 +41,30 @@ */ public class AuthenticationTest extends MqttIntegrationTest { - static AuthenticationController authenticationController; - static byte[] serviceServerSecretKey = EncryptionHelper.generateKey(); - - @BeforeAll - public static void setUpClass() throws Throwable { - MqttIntegrationTest.setUpClass(); + public static AuthenticationController authenticationController; + public static byte[] serviceServerSecretKey = EncryptionHelper.generateKey(); + @BeforeEach + public void setupAuthentication() throws Throwable { JPService.setupJUnitTestMode(); CachedAuthenticationRemote.prepare(); authenticationController = new AuthenticationController(MockCredentialStore.getInstance(), serviceServerSecretKey); authenticationController.init(); authenticationController.activate(); authenticationController.waitForActivation(); - - Assert.assertTrue("Initial password has not been generated despite an empty registry", AuthenticationController.getInitialPassword() != null); + assertNotNull(AuthenticationController.getInitialPassword(), "Initial password has not been generated despite an empty registry"); } - @AfterAll - public static void tearDownClass() { + @AfterEach + public void tearDownAuthentication() { + // reset credential store because it could have been changed in a test + MockCredentialStore.getInstance().reset(); CachedAuthenticationRemote.shutdown(); if (authenticationController != null) { authenticationController.shutdown(); } AuthenticatedServerManager.shutdown(); SessionManager.getInstance().shutdown(); - } - - @AfterEach - public void afterTest() { - // reset credential store because it could have been changed in a test - MockCredentialStore.getInstance().reset(); + authenticationController = null; } } diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatorControllerTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatorControllerTest.java index b25838a788..2ef2a61f6d 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatorControllerTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthenticatorControllerTest.java @@ -46,19 +46,14 @@ import java.util.concurrent.ExecutionException; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.*; /** * @author Tamino Huxohl */ public class AuthenticatorControllerTest extends AuthenticationTest { - private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AuthenticatorControllerTest.class); - - public AuthenticatorControllerTest() { - } - /** * Test of communication between ClientRemote and AuthenticatorController. * diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthorizationHelperTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthorizationHelperTest.java index 9f0a954bd4..b0330191a8 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthorizationHelperTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/AuthorizationHelperTest.java @@ -24,6 +24,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.authentication.lib.AuthorizationHelper; @@ -42,8 +43,6 @@ import java.util.Locale; import java.util.Map; -import static org.junit.Assert.assertEquals; - /** * @author Constantin Romankiewicz */ @@ -364,10 +363,10 @@ public void testUserAsGroupPermissions() { PermissionConfig.Builder permissionConfigBuilder = unitConfigBuilder.getPermissionConfigBuilder(); permissionConfigBuilder.setOtherPermission(NONE); // validate that user does not have any permissions for the unit - assertEquals("User should not have any permissions!", NONE, AuthorizationHelper.getPermission(unitConfigBuilder.build(), userId, groups, locations)); + assertEquals(NONE, AuthorizationHelper.getPermission(unitConfigBuilder.build(), userId, groups, locations), "User should not have any permissions!"); // add user as group with rwx permissions permissionConfigBuilder.addGroupPermissionBuilder().setGroupId(userId).setPermission(RWX); // validate that user now has rwx permissions - assertEquals("User is added as a group but did not get the according permissions", RWX, AuthorizationHelper.getPermission(unitConfigBuilder.build(), userId, groups, locations)); + assertEquals(RWX, AuthorizationHelper.getPermission(unitConfigBuilder.build(), userId, groups, locations), "User is added as a group but did not get the according permissions"); } } diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/CredentialStoreTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/CredentialStoreTest.java index 9b224d6ef8..7d970685cd 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/CredentialStoreTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/CredentialStoreTest.java @@ -32,11 +32,8 @@ import org.openbase.jul.exception.NotAvailableException; import org.openbase.jul.exception.printer.ExceptionPrinter; import org.slf4j.LoggerFactory; - import java.security.KeyPair; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Tamino Huxohl diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/EncryptionHelperTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/EncryptionHelperTest.java index 43d2a01c9f..f9397bdbd5 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/EncryptionHelperTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/EncryptionHelperTest.java @@ -21,15 +21,14 @@ * . * #L% */ + +import static org.junit.jupiter.api.Assertions.*; import com.google.protobuf.ByteString; import java.security.KeyPair; -import java.util.concurrent.ExecutionException; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Timeout; import org.openbase.bco.authentication.lib.EncryptionHelper; import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; import org.openbase.jul.exception.CouldNotPerformException; import org.slf4j.LoggerFactory; diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/InitialRegistrationTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/InitialRegistrationTest.java index 6d59f0c5d9..d1aeea79d3 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/InitialRegistrationTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/InitialRegistrationTest.java @@ -32,7 +32,7 @@ import org.openbase.type.domotic.authentication.LoginCredentialsType.LoginCredentials; import org.slf4j.LoggerFactory; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Tamino Huxohl @@ -64,6 +64,6 @@ public void initialRegistrationTest() throws Exception { // test if login works afterwards SessionManager.getInstance().loginUser(userId, password, false); - assertTrue("User is not logged in", SessionManager.getInstance().isLoggedIn()); + assertTrue(SessionManager.getInstance().isLoggedIn(), "User is not logged in"); } } diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/SessionManagerTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/SessionManagerTest.java index a5e8052448..b8ed3d8ca1 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/SessionManagerTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/SessionManagerTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; import org.openbase.bco.authentication.core.AuthenticationController; import org.openbase.bco.authentication.lib.CachedAuthenticationRemote; @@ -42,8 +43,6 @@ import java.util.concurrent.ExecutionException; -import static org.junit.Assert.*; - /** * @author Sebastian Fast */ @@ -52,20 +51,16 @@ public class SessionManagerTest extends AuthenticationTest { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(SessionManagerTest.class); private static CredentialStore clientStore; + private static String INITIAL_USER_ID = "InitialUserId"; - - public SessionManagerTest() { - } - - @BeforeAll - public static void setUpClass() throws Throwable { - AuthenticationTest.setUpClass(); + @BeforeEach + public void setupSessionManager() throws Throwable { clientStore = new MockClientStore(); // register an initial user for the authenticator try { LoginCredentials.Builder loginCredentials = LoginCredentials.newBuilder(); - loginCredentials.setId("InitialUserId"); + loginCredentials.setId(INITIAL_USER_ID); loginCredentials.setSymmetric(true); loginCredentials.setCredentials(EncryptionHelper.encryptSymmetric(EncryptionHelper.hash("InitialUserPwd"), EncryptionHelper.hash(AuthenticationController.getInitialPassword()))); AuthenticatedValue authenticatedValue = AuthenticatedValue.newBuilder().setValue(loginCredentials.build().toByteString()).build(); @@ -75,14 +70,6 @@ public static void setUpClass() throws Throwable { } } - @BeforeEach - public void setUp() throws Exception { - } - - @AfterEach - public void tearDown() throws Exception { - } - /** * Test of SessionManager.login() for client. * @@ -300,7 +287,8 @@ public void removeAdminHimself() { try { ExceptionPrinter.setBeQuit(Boolean.TRUE); - // remove himself + // remove all admins + manager.removeUser(INITIAL_USER_ID).get(); manager.removeUser(MockClientStore.ADMIN_ID).get(); } finally { ExceptionPrinter.setBeQuit(Boolean.FALSE); @@ -484,7 +472,7 @@ public void loginObservableTest() throws Exception { synchronized (loginSyncObject) { loginSyncObject.wait(maxWaitTime); } - assertEquals("Notification counter should be 1 after the first login", 1, notificationCounter); + assertEquals(1, notificationCounter, "Notification counter should be 1 after the first login"); synchronized (loginSyncObject) { loginSyncObject.wait(maxWaitTime); } @@ -492,12 +480,12 @@ public void loginObservableTest() throws Exception { synchronized (loginSyncObject) { loginSyncObject.wait(maxWaitTime); } - assertEquals("Notification counter should be 2 after logging in another user", 2, notificationCounter); + assertEquals(2, notificationCounter, "Notification counter should be 2 after logging in another user"); sessionManager.logout(); synchronized (loginSyncObject) { loginSyncObject.wait(maxWaitTime); } - assertEquals("Notification counter should be 3 after logout", 3, notificationCounter); + assertEquals(3, notificationCounter, "Notification counter should be 3 after logout"); sessionManager.removeLoginObserver(loginObserver); } diff --git a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/StayLoggedInTest.java b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/StayLoggedInTest.java index 076f27ee45..fc4dae407e 100644 --- a/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/StayLoggedInTest.java +++ b/module/authentication/test/src/test/java/org/openbase/bco/authentication/test/StayLoggedInTest.java @@ -22,40 +22,43 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; +import static org.openbase.bco.authentication.test.AuthenticationTest.serviceServerSecretKey; + import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.openbase.bco.authentication.core.AuthenticationController; import org.openbase.bco.authentication.lib.AuthenticationServerHandler; import org.openbase.bco.authentication.lib.CachedAuthenticationRemote; import org.openbase.bco.authentication.lib.SessionManager; import org.openbase.bco.authentication.lib.jp.JPSessionTimeout; import org.openbase.bco.authentication.mock.MockClientStore; +import org.openbase.bco.authentication.mock.MockCredentialStore; +import org.openbase.bco.authentication.mock.MqttIntegrationTest; import org.openbase.jps.core.JPService; import org.openbase.jul.exception.printer.ExceptionPrinter; import org.openbase.type.domotic.authentication.TicketAuthenticatorWrapperType.TicketAuthenticatorWrapper; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.*; - /** * Test the staying logged in functionality of the session manager. * This is not inside the session manager tests because the session timeout is greatly reduced. * * @author Tamino Huxohl */ -public class StayLoggedInTest extends AuthenticationTest { +public class StayLoggedInTest extends MqttIntegrationTest { /** * The session timeout for this test. */ private static final long SESSION_TIMEOUT = 500; - @BeforeAll - public static void setUpClass() throws Throwable { + @Override + public void setupTestProperties() { // set the session timeout and use the super method for initialization JPService.registerProperty(JPSessionTimeout.class, SESSION_TIMEOUT); - AuthenticationTest.setUpClass(); } /** @@ -64,17 +67,24 @@ public static void setUpClass() throws Throwable { * @throws Exception if something does not work as expected */ @Test - @Timeout(20) + @Timeout(10) public void testStayingLoggedIn() throws Exception { + + CachedAuthenticationRemote.prepare(); + AuthenticationController authenticationController = new AuthenticationController(MockCredentialStore.getInstance(), serviceServerSecretKey); + authenticationController.init(); + authenticationController.activate(); + authenticationController.waitForActivation(); + // validate that the session timeout has been setup accordingly - assertEquals("Session timeout has not been initialized correctly", SESSION_TIMEOUT, (long) JPService.getProperty(JPSessionTimeout.class).getValue()); + assertEquals(SESSION_TIMEOUT, (long) JPService.getProperty(JPSessionTimeout.class).getValue(), "Session timeout has not been initialized correctly"); // create a new session manager SessionManager sessionManager = new SessionManager(); // login with stay logged in activated sessionManager.loginUser(MockClientStore.ADMIN_ID, MockClientStore.ADMIN_PASSWORD, true); // wait longer than the session timeout - Thread.sleep(SESSION_TIMEOUT + AuthenticationServerHandler.MAX_TIME_DIFF_SERVER_CLIENT + 200); + Thread.sleep(SESSION_TIMEOUT + AuthenticationServerHandler.MAX_TIME_DIFF_SERVER_CLIENT); // perform a request TicketAuthenticatorWrapper wrapper = sessionManager.initializeServiceServerRequest(); CachedAuthenticationRemote.getRemote().validateClientServerTicket(wrapper).get(); @@ -82,7 +92,7 @@ public void testStayingLoggedIn() throws Exception { // login as a different user without staying logged in sessionManager.loginUser(MockClientStore.USER_ID, MockClientStore.USER_PASSWORD, false); // wait longer than the session timeout - Thread.sleep(SESSION_TIMEOUT + AuthenticationServerHandler.MAX_TIME_DIFF_SERVER_CLIENT + 200); + Thread.sleep(SESSION_TIMEOUT + AuthenticationServerHandler.MAX_TIME_DIFF_SERVER_CLIENT); // perform a request wrapper = sessionManager.initializeServiceServerRequest(); try { diff --git a/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/AbstractControllerServerTest.java b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/AbstractControllerServerTest.java new file mode 100644 index 0000000000..e7a7d51ee1 --- /dev/null +++ b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/AbstractControllerServerTest.java @@ -0,0 +1,417 @@ +package org.openbase.jul.communication.controller; + +/* + * #%L + * JUL Extension Controller + * %% + * Copyright (C) 2015 - 2022 openbase.org + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.openbase.jul.communication.iface.RPCServer; +import org.openbase.jul.exception.CouldNotPerformException; +import org.openbase.jul.exception.FatalImplementationErrorException; +import org.openbase.jul.exception.InstantiationException; +import org.openbase.jul.exception.StackTracePrinter; +import org.openbase.jul.exception.printer.ExceptionPrinter; +import org.openbase.jul.exception.printer.LogLevel; +import org.openbase.jul.schedule.GlobalCachedExecutorService; +import org.openbase.jul.schedule.Stopwatch; +import org.openbase.jul.schedule.SyncObject; +import org.openbase.type.domotic.registry.UnitRegistryDataType.UnitRegistryData; +import org.openbase.type.domotic.unit.UnitConfigType.UnitConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static org.junit.jupiter.api.Assertions.*; +import static org.openbase.type.domotic.state.AvailabilityStateType.AvailabilityState.State.OFFLINE; +import static org.openbase.type.domotic.state.AvailabilityStateType.AvailabilityState.State.ONLINE; +import static org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State.*; + +/** + * * @author Tamino Huxohl + */ +public class AbstractControllerServerTest extends MqttIntegrationTest { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + public AbstractControllerServerTest() { + } + + private boolean firstSync = false; + private boolean secondSync = false; + private AbstractControllerServer communicationService; + + /** + * Test if the initial sync that happens if a communication service starts + * successfully publishes its data to a remote. + * + * @throws Exception + */ + @Timeout(5) + @Test + public void testInitialSync() throws Exception { + String scope = "/test/synchronization"; + final SyncObject waitForDataSync = new SyncObject("WaitForDataSync"); + UnitConfig unit1 = UnitConfig.newBuilder().setId("Location1").build(); + UnitRegistryData.Builder testData = UnitRegistryData.getDefaultInstance().toBuilder().addLocationUnitConfig(unit1); + communicationService = new AbstractControllerServerImpl(testData); + communicationService.init(scope); + communicationService.activate(); + + AbstractRemoteClient remoteService = new AbstractRemoteClientImpl(); + remoteService.init(scope); + remoteService.addDataObserver((source, data) -> { + if (data.getLocationUnitConfigCount() == 1 && data.getLocationUnitConfig(0).getId().equals("Location1")) { + firstSync = true; + synchronized (waitForDataSync) { + waitForDataSync.notifyAll(); + } + } + if (data.getLocationUnitConfigCount() == 2 && data.getLocationUnitConfig(0).getId().equals("Location1") && data.getLocationUnitConfig(1).getId().equals("Location2")) { + secondSync = true; + synchronized (waitForDataSync) { + waitForDataSync.notifyAll(); + } + } + }); + + synchronized (waitForDataSync) { + if (!firstSync) { + remoteService.activate(); + waitForDataSync.wait(); + } + } + assertTrue(firstSync, "Synchronization after the start of the remote service has not been done"); + + communicationService.shutdown(); + UnitConfig location2 = UnitConfig.newBuilder().setId("Location2").build(); + testData.addLocationUnitConfig(location2); + communicationService = new AbstractControllerServerImpl(testData); + communicationService.init(scope); + + synchronized (waitForDataSync) { + if (!secondSync) { + communicationService.activate(); + waitForDataSync.wait(); + } + } + assertTrue(secondSync, "Synchronization after the restart of the communication service has not been done"); + + communicationService.deactivate(); + try { + remoteService.ping().get(); + fail("Pinging was not canceled after timeout."); + } catch (ExecutionException ex) { + // ping canceled + } + + assertEquals( + CONNECTING, + remoteService.getConnectionState(), + "Remote is still connected after remote service shutdown!"); + communicationService.activate(); + communicationService.waitForAvailabilityState(ONLINE); + remoteService.waitForConnectionState(CONNECTED); + remoteService.shutdown(); + communicationService.shutdown(); + assertEquals( + OFFLINE, + communicationService.getControllerAvailabilityState(), + "Communication Service is not offline after shutdown!"); + assertEquals( + DISCONNECTED, + remoteService.getConnectionState(), + "Remote is not disconnected after shutdown!"); + } + + /** + * Test if a RemoteService will reconnect when the communication service + * restarts. + * + * This test validates, that at least 10 re-connection cycles can be repeated + * within a timeout of 5 seconds. + */ + @Timeout(5) + @Test + public void testReconnection() throws Exception { + int cycles = 10; + String scope = "/test/reconnection"; + UnitConfig location1 = UnitConfig.newBuilder().setId("Location1").build(); + UnitRegistryData.Builder testData = UnitRegistryData.getDefaultInstance().toBuilder().addLocationUnitConfig(location1); + + communicationService = new AbstractControllerServerImpl(testData); + communicationService.init(scope); + communicationService.activate(); + + AbstractRemoteClient remoteService = new AbstractRemoteClientImpl(); + remoteService.init(scope); + remoteService.activate(); + + remoteService.waitForConnectionState(CONNECTED); + + Stopwatch stopWatch = new Stopwatch(); + stopWatch.start(); + for (int i = 0; i < cycles; i++) { + communicationService.deactivate(); + remoteService.waitForConnectionState(CONNECTING); + + communicationService.activate(); + remoteService.waitForConnectionState(CONNECTED); + } + logger.info(stopWatch.stop() + "ms for 100 reconnection cycles (" + (stopWatch.getTime() / cycles) + ")ms on average"); + + communicationService.shutdown(); + remoteService.shutdown(); + } + + /** + * Test waiting for data from a communication service. + */ + @Timeout(5) + @Test + public void testWaitForData() throws Exception { + String scope = "/test/waitfordata"; + UnitConfig location1 = UnitConfig.newBuilder().setId("Location1").build(); + UnitRegistryData.Builder testData = UnitRegistryData.getDefaultInstance().toBuilder().addLocationUnitConfig(location1); + + AbstractRemoteClient remoteService = new AbstractRemoteClientImpl(); + remoteService.init(scope); + communicationService = new AbstractControllerServerImpl(testData); + communicationService.init(scope); + + remoteService.activate(); + + Future dataFuture = remoteService.getDataFuture(); + + communicationService.activate(); + + assertEquals( + communicationService.getData(), + dataFuture.get(), + "DataFuture did not return data from communicationService!"); + + communicationService.shutdown(); + remoteService.shutdown(); + } + + /** + * Test requesting data from a communication service. + */ + @Timeout(5) + @Test + public void testRequestData() throws Exception { + String scope = "/test/requestdata"; + UnitConfig location1 = UnitConfig.newBuilder().setId("Location1").build(); + UnitRegistryData.Builder testData = UnitRegistryData.getDefaultInstance().toBuilder().addLocationUnitConfig(location1); + + AbstractRemoteClient remoteService = new AbstractRemoteClientImpl(); + remoteService.init(scope); + communicationService = new AbstractControllerServerImpl(testData); + communicationService.init(scope); + + remoteService.activate(); + communicationService.activate(); + + remoteService.requestData().get(); + + assertEquals( + communicationService.getData(), + remoteService.getData(), + "CommunicationService data and remoteService data do not match after requestData!"); + + communicationService.shutdown(); + remoteService.shutdown(); + } + + /** + * Test if when there are 2 remotes connected to a communication service + * the shutdown of one remote affects the communication of the other one. + */ + @Timeout(60) + @Test + public void testRemoteInterference() throws Exception { + String scope = "/test/interference"; + UnitConfig location1 = UnitConfig.newBuilder().setId("Location1").build(); + UnitRegistryData.Builder testData = UnitRegistryData.getDefaultInstance().toBuilder().addLocationUnitConfig(location1); + + AbstractRemoteClient remoteService1 = new AbstractRemoteClientImpl(); + AbstractRemoteClient remoteService2 = new AbstractRemoteClientImpl(); + remoteService1.init(scope); + remoteService2.init(scope); + communicationService = new AbstractControllerServerImpl(testData); + communicationService.init(scope); + communicationService.activate(); + + remoteService1.activate(); + remoteService2.activate(); + + remoteService1.waitForConnectionState(CONNECTED); + remoteService2.waitForConnectionState(CONNECTED); + System.out.println("shutdown remote 1"); + remoteService1.shutdown(); + remoteService1.waitForConnectionState(DISCONNECTED); + + assertEquals( + CONNECTED, + remoteService2.getConnectionState(), + "Remote connected to the same service got shutdown too"); + remoteService2.requestData().get(); + + System.out.println("deactivate server"); + communicationService.deactivate(); + remoteService2.waitForConnectionState(CONNECTING); + + System.out.println("activate server"); + communicationService.activate(); + remoteService2.waitForConnectionState(CONNECTED); + assertEquals( + DISCONNECTED, + remoteService1.getConnectionState(), + "Remote reconnected even though it already shutdown"); + + remoteService2.shutdown(); + communicationService.shutdown(); + } + + /** + * @throws Exception + */ + @Timeout(10) + @Test + @Disabled // Ignore test since it's pretty unstable. + public void testNotification() throws Exception { + String scope = "/test/notification"; + UnitConfig location = UnitConfig.newBuilder().setId("id").build(); + communicationService = new AbstractControllerServerImpl(UnitRegistryData.getDefaultInstance().toBuilder().addLocationUnitConfig(location)); + communicationService.init(scope); + + AbstractRemoteClient remoteService = new AbstractRemoteClientImpl(); + remoteService.init(scope); + remoteService.activate(); + remoteService.waitForMiddleware(); + + GlobalCachedExecutorService.submit(() -> { + try { + // make sure the remote is ready to wait for data + remoteService.waitForConnectionState(CONNECTING); + communicationService.activate(); + // notification should be sent automatically. + } catch (Exception ex) { + ExceptionPrinter.printHistory(new FatalImplementationErrorException(this, ex), System.err); + } + }); + + remoteService.waitForData(); + try { + remoteService.ping().get(1000, TimeUnit.MILLISECONDS); + } catch (TimeoutException | ExecutionException ex) { + StackTracePrinter.printAllStackTraces(LoggerFactory.getLogger(getClass()), LogLevel.WARN); + fail("Even though wait for data returned the pinging immediately afterwards took to long. Please check stacktrace for deadlocks..."); + } + + remoteService.shutdown(); + communicationService.shutdown(); + } + + @Timeout(5) + @Test + public void testReinit() throws Exception { + final int TEST_PARALLEL_REINIT_TASKS = 5; + String scope = "/test/notification"; + UnitConfig location = UnitConfig.newBuilder().setId("id").build(); + communicationService = new AbstractControllerServerImpl(UnitRegistryData.newBuilder().addLocationUnitConfig(location)); + communicationService.init(scope); + communicationService.activate(); + + AbstractRemoteClient remoteService = new AbstractRemoteClientImpl(); + remoteService.init(scope); + remoteService.activate(); + + final Runnable reinitTask = () -> { + try { + remoteService.reinit(); + remoteService.requestData().get(); + } catch (Exception ex) { + ExceptionPrinter.printHistory("reinit failed!", ex, logger); + } + }; + + // execute reinits + final ArrayList> taskFutures = new ArrayList<>(); + for (int i = 0; i < TEST_PARALLEL_REINIT_TASKS; i++) { + taskFutures.add(GlobalCachedExecutorService.submit(reinitTask)); + } + for (Future future : taskFutures) { + try { + future.get(15, TimeUnit.SECONDS); + } catch (TimeoutException ex) { + //StackTracePrinter.printAllStackTrace(AbstractControllerServerTest.class); + StackTracePrinter.detectDeadLocksAndPrintStackTraces(AbstractControllerServerTest.class); + fail("Reint took too long! Please analyse deadlock in stacktrace..."); + } + } + + remoteService.waitForData(); + try { + remoteService.ping().get(500, TimeUnit.MILLISECONDS); + } catch (TimeoutException ex) { + fail("Even though wait for data returned the pinging immediately afterwards failed"); + } + communicationService.deactivate(); + remoteService.deactivate(); + remoteService.reinit(); + + communicationService.shutdown(); + remoteService.shutdown(); + + + try { + remoteService.reinit(); + fail("No exception occurred."); + } catch (CouldNotPerformException ex) { + // this should happen + } + } + + public static class AbstractControllerServerImpl extends AbstractControllerServer { + + public AbstractControllerServerImpl(UnitRegistryData.Builder builder) throws InstantiationException { + super(builder); + } + + @Override + public void registerMethods(RPCServer server) throws CouldNotPerformException { + + } + } + + public static class AbstractRemoteClientImpl extends AbstractRemoteClient { + public AbstractRemoteClientImpl() { + super(UnitRegistryData.class); + } + } +} diff --git a/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/AbstractRemoteClientTest.java b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/AbstractRemoteClientTest.java new file mode 100644 index 0000000000..3a09424ea6 --- /dev/null +++ b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/AbstractRemoteClientTest.java @@ -0,0 +1,263 @@ +package org.openbase.jul.communication.controller; + +/*- + * #%L + * JUL Extension Controller + * %% + * Copyright (C) 2015 - 2022 openbase.org + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + +import com.google.protobuf.Any; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.openbase.jul.annotation.RPCMethod; +import org.openbase.jul.communication.controller.AbstractControllerServerTest.AbstractControllerServerImpl; +import org.openbase.jul.communication.controller.AbstractControllerServerTest.AbstractRemoteClientImpl; +import org.openbase.jul.communication.iface.RPCServer; +import org.openbase.jul.exception.CouldNotPerformException; +import org.openbase.jul.exception.InstantiationException; +import org.openbase.jul.exception.TimeoutException; +import org.openbase.jul.exception.printer.ExceptionPrinter; +import org.openbase.jul.extension.protobuf.ClosableDataBuilder; +import org.openbase.jul.extension.type.util.TransactionSynchronizationFuture; +import org.openbase.jul.schedule.FutureProcessor; +import org.openbase.jul.schedule.GlobalCachedExecutorService; +import org.openbase.type.domotic.communication.TransactionValueType.TransactionValue; +import org.openbase.type.domotic.registry.UnitRegistryDataType.UnitRegistryData; +import org.openbase.type.domotic.state.PowerStateType.PowerState.State; +import org.openbase.type.domotic.unit.dal.PowerSwitchDataType.PowerSwitchData; +import org.openbase.type.domotic.unit.dal.PowerSwitchDataType.PowerSwitchData.Builder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.openbase.type.domotic.state.AvailabilityStateType.AvailabilityState.State.ONLINE; +import static org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State.CONNECTED; + +/** + * @author Divine Threepwood + */ +public class AbstractRemoteClientTest extends MqttIntegrationTest { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + public AbstractRemoteClientTest() { + } + + /** + * Test of waitForConnectionState method, of class AbstractRemoteClient. + * + * @throws InterruptedException + * @throws CouldNotPerformException + */ + @Timeout(10) + @Test + public void testWaitForConnectionState() throws InterruptedException, CouldNotPerformException { + System.out.println("waitForConnectionState"); + AbstractRemoteClient instance = new AbstractRemoteClientImpl(); + instance.init("/test/waitForConnectionState"); + + // Test Timeout + instance.activate(); + + try { + instance.waitForConnectionState(CONNECTED, 10); + fail("No exception thrown."); + } catch (TimeoutException ex) { + // should be thrown... + assertTrue(true); + } + + // Test if shutdown is blocked by waitForConnection without timeout + System.out.println("Test if waitForConnection is interrupted through shutdown!"); + GlobalCachedExecutorService.submit(() -> { + try { + System.out.println("Thread is running"); + assertTrue(instance.isActive(), "Instance is not active while waiting"); + System.out.println("Wait for ConnectionState"); + instance.waitForConnectionState(CONNECTED); + } catch (CouldNotPerformException | InterruptedException ex) { +// ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); + } + return null; + }); + + Thread.sleep(100); + + instance.shutdown(); + } + + @Timeout(10) + @Test + public void testDeactivation() throws InterruptedException, CouldNotPerformException { + System.out.println("testDeactivation"); + final String scope = "/test/deactivation"; + + AbstractRemoteClient instance = new AbstractRemoteClientImpl(); + instance.init(scope); + instance.activate(); + + AbstractControllerServerImpl communicationService = new AbstractControllerServerImpl(UnitRegistryData.newBuilder()); + communicationService.init(scope); + communicationService.activate(); + communicationService.waitForAvailabilityState(ONLINE); + + instance.waitForConnectionState(CONNECTED); + instance.waitForData(); + System.out.println("shutdown..."); + System.out.println("main thread name: " + Thread.currentThread().getName()); + communicationService.deactivate(); + instance.deactivate(); + communicationService.shutdown(); + instance.shutdown(); + } + + /** + * Test what happens when one thread calls an asynchronous method while another reinitializes + * the remote services and requests new data afterwards. + * This is a simple example for issue https://github.com/openbase/bco.registry/issues/59, + * + * @throws Exception + */ + @Timeout(5) + @Test + public void testReinit() throws Exception { + System.out.println("testReinit"); + + final AbstractRemoteClient remoteService = new AbstractRemoteClientImpl(); + remoteService.init("/test/testReinit"); + remoteService.activate(); + + boolean[] check = new boolean[1]; + check[0] = false; + GlobalCachedExecutorService.submit(() -> { + try { + remoteService.callMethodAsync("method", Any.class).get(); + } catch (InterruptedException | ExecutionException ex) { + // is expected since reinit should kill the method call + check[0] = true; + } + }); + + Thread.sleep(100); + + remoteService.reinit(); + try { + remoteService.requestData().get(100, TimeUnit.MILLISECONDS); + } catch (CancellationException ex) { + throw ExceptionPrinter.printHistoryAndReturnThrowable(new CouldNotPerformException("Requesting data has been cancelled", ex), logger); + } catch (java.util.concurrent.TimeoutException ex) { + // is expected here since no server is started + } + + assertTrue(check[0], "call was not canceled!"); + + remoteService.shutdown(); + } + + private boolean prioritizedObservableFinished = false; + + /** + * Test for the synchronization using transaction ids. This tests verifies if the {@link TransactionSynchronizationFuture} + * can only return after the internal prioritized observable of the remote service has finished its notification. + *

+ * This is needed e.g. for registry remotes because they synchronize their internal remote registries using this + * observable. If it is not finished when the future returns following calls can fail. + * See issue: https://github.com/openbase/bco.registry/issues/98 + * + * @throws Exception if an error occurs. + */ + @Timeout(5) + @Test + public void testTransactionSynchronization() throws Exception { + final String scope = "/test/transaction/sync"; + + final TransactionControllerServer communicationService = new TransactionControllerServer(); + communicationService.init(scope); + communicationService.activate(); + + final TransactionRemoteClient remoteService = new TransactionRemoteClient(); + remoteService.init(scope); + remoteService.activate(); + remoteService.waitForData(); + + long transactionId = remoteService.getTransactionId(); + remoteService.getInternalPrioritizedDataObservable().addObserver((source, data) -> { + Thread.sleep(100); + prioritizedObservableFinished = true; + }); + remoteService.performTransaction().get(); + assertTrue(remoteService.getTransactionId() > transactionId, "Transaction id did not increase after performTransaction call"); + assertTrue(prioritizedObservableFinished, "Prioritized observable is not finished but sync future already returned"); + + remoteService.shutdown(); + communicationService.shutdown(); + } + + public static class TransactionControllerServer extends AbstractControllerServer { + + /** + * Create a communication service. + * + * @throws InstantiationException if the creation fails + */ + public TransactionControllerServer() throws CouldNotPerformException { + super(PowerSwitchData.newBuilder()); + } + + @Override + public void registerMethods(RPCServer server) throws CouldNotPerformException { + server.registerMethods((Class) getClass(), this); + } + + @RPCMethod + public TransactionValue performTransaction() throws CouldNotPerformException, InterruptedException { + // update transaction + updateTransactionId(); + // change data builder to trigger notification + try (ClosableDataBuilder dataBuilder = getDataBuilderInterruptible(this)) { + dataBuilder.getInternalBuilder().getPowerStateBuilder().setValue(State.ON); + } + // return transaction value + return TransactionValue.newBuilder().setTransactionId(getTransactionId()).build(); + } + } + + private static class TransactionRemoteClient extends AbstractRemoteClient { + + public TransactionRemoteClient() { + super(PowerSwitchData.class); + } + + public Future performTransaction() { + return new TransactionSynchronizationFuture<>( + FutureProcessor.postProcess( + (input, timeout, timeUnit) -> input.getResponse(), + this.callMethodAsync("performTransaction", TransactionValue.class) + ), + this + ); + } + } +} diff --git a/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/ConfigurableControllerAndRemoteTest.java b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/ConfigurableControllerAndRemoteTest.java new file mode 100644 index 0000000000..b322416819 --- /dev/null +++ b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/ConfigurableControllerAndRemoteTest.java @@ -0,0 +1,137 @@ +package org.openbase.jul.communication.controller; + +/*- + * #%L + * JUL Extension Controller + * %% + * Copyright (C) 2015 - 2022 openbase.org + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.openbase.jul.communication.iface.RPCServer; +import org.openbase.jul.exception.CouldNotPerformException; +import org.openbase.type.communication.ScopeType.Scope; +import org.openbase.type.domotic.unit.UnitConfigType.UnitConfig; +import org.openbase.type.domotic.unit.scene.SceneDataType.SceneData; +import org.openbase.type.domotic.unit.scene.SceneDataType.SceneData.Builder; + +import java.util.UUID; + +import static org.openbase.type.domotic.state.AvailabilityStateType.AvailabilityState.State.ONLINE; +import static org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State.CONNECTED; +import static org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State.CONNECTING; + +/** + * * @author Tamino Huxohl + */ +public class ConfigurableControllerAndRemoteTest extends MqttIntegrationTest { + + public ConfigurableControllerAndRemoteTest() { + } + + @Timeout(10) + @Test + public void initTest() throws Exception { + System.out.println("initTest"); + + Scope scope = Scope.newBuilder().addComponent("test").addComponent("configurable").addComponent("controller").addComponent("and").addComponent("remote").build(); + UnitConfig unitConfig = UnitConfig.newBuilder().setId(UUID.randomUUID().toString()).setScope(scope).build(); + + AbstractConfigurableController controller = new AbstractConfigurableControllerImpl(); + controller.init(unitConfig); + controller.activate(); + + AbstractConfigurableRemote remote = new AbstractConfigurableRemoteImpl(SceneData.class, UnitConfig.class); + remote.init(unitConfig); + remote.activate(); + + remote.waitForConnectionState(CONNECTED); + controller.waitForAvailabilityState(ONLINE); + System.out.println("Successfully connected controller and remote!"); + + scope = scope.toBuilder().clearComponent().addComponent("test").addComponent("configurables").build(); + unitConfig = unitConfig.toBuilder().setScope(scope).build(); + controller.init(unitConfig); + controller.waitForAvailabilityState(ONLINE); + System.out.println("Controller is online again!"); + remote.waitForConnectionState(CONNECTING); + System.out.println("Remote switched to connecting after config change in the controller!"); + remote.init(unitConfig); + remote.waitForConnectionState(CONNECTED); + System.out.println("Remote reconnected after reinitialization!"); + + controller.shutdown(); + remote.shutdown(); + } + + @Timeout(10) + @Test + public void applyConfigUpdateTest() throws Exception { + System.out.println("applyConfigUpdateTest"); + + Scope scope = Scope.newBuilder().addComponent("test2").addComponent("configurable2").addComponent("controller2").addComponent("and2").addComponent("remote2").build(); + UnitConfig unitConfig = UnitConfig.newBuilder().setId(UUID.randomUUID().toString()).setScope(scope).build(); + + AbstractConfigurableController controller = new AbstractConfigurableControllerImpl(); + controller.init(unitConfig); + controller.activate(); + + AbstractConfigurableRemote remote = new AbstractConfigurableRemoteImpl(SceneData.class, UnitConfig.class); + remote.init(unitConfig); + remote.activate(); + + remote.waitForConnectionState(CONNECTED); + controller.waitForAvailabilityState(ONLINE); + System.out.println("Succesfully connected controller and remote!"); + + scope = scope.toBuilder().clearComponent().addComponent("test2").addComponent("configurables2").build(); + unitConfig = unitConfig.toBuilder().setScope(scope).build(); + + controller.applyConfigUpdate(unitConfig); + controller.waitForAvailabilityState(ONLINE); + System.out.println("Controller is online again!"); + remote.waitForConnectionState(CONNECTING); + System.out.println("Remote switched to connecting after config change in the controller!"); + remote.applyConfigUpdate(unitConfig); + remote.waitForConnectionState(CONNECTED); + System.out.println("Remote reconnected after reinitialization!"); + + remote.shutdown(); + controller.shutdown(); + } + + public class AbstractConfigurableControllerImpl extends AbstractConfigurableController { + + public AbstractConfigurableControllerImpl() throws Exception { + super(SceneData.newBuilder()); + } + + @Override + public void registerMethods(RPCServer server) throws CouldNotPerformException { + } + } + + public class AbstractConfigurableRemoteImpl extends AbstractConfigurableRemote { + + public AbstractConfigurableRemoteImpl(Class dataClass, Class configClass) { + super(dataClass, configClass); + } + } + +} diff --git a/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/FrequentBlockingMethodCallTest.java b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/FrequentBlockingMethodCallTest.java new file mode 100644 index 0000000000..8269412478 --- /dev/null +++ b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/FrequentBlockingMethodCallTest.java @@ -0,0 +1,135 @@ +package org.openbase.jul.communication.controller; + +/*- + * #%L + * JUL Extension Controller + * %% + * Copyright (C) 2015 - 2022 openbase.org + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + +import org.openbase.jps.core.JPService; +import org.openbase.jul.annotation.RPCMethod; +import org.openbase.jul.communication.iface.RPCServer; +import org.openbase.jul.exception.CouldNotPerformException; +import org.openbase.jul.exception.InstantiationException; +import org.openbase.jul.exception.printer.ExceptionPrinter; +import org.openbase.jul.schedule.GlobalCachedExecutorService; +import org.openbase.type.domotic.registry.UnitRegistryDataType.UnitRegistryData; +import org.openbase.type.domotic.registry.UnitRegistryDataType.UnitRegistryData.Builder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +public class FrequentBlockingMethodCallTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(FrequentBlockingMethodCallTest.class); + + /** + * Deactivated because its a system test which does not really perform any unit tests but tests the capacity of + * the executor service by repeatedly calling blocking rpc calls. + * @throws Exception + */ +// @Test + public void testFrequentBlockingMethodCall() throws Exception { + JPService.setupJUnitTestMode(); + final String scope = "/test/blocking"; + + AbstractBlockingControllerServerImpl communicationService = new AbstractBlockingControllerServerImpl(UnitRegistryData.newBuilder()); + communicationService.init(scope); + communicationService.activate(); + + BlockingAbstractRemoteClientImpl remoteService = new BlockingAbstractRemoteClientImpl(); + remoteService.init(scope); + remoteService.activate(); + + remoteService.waitForData(1, TimeUnit.SECONDS); + + while (GlobalCachedExecutorService.getInstance().getExecutorService().getActiveCount() < 1960) { + remoteService.blockForever(); + + LOGGER.info("Active count: " + GlobalCachedExecutorService.getInstance().getExecutorService().getActiveCount()); + Thread.sleep(10); + } + + Thread.sleep(TimeUnit.MINUTES.toMillis(2)); + + if (!remoteService.getFutures().get(0).isDone()) { + LOGGER.error("Future from first task should be done"); + } else { + try { + remoteService.getFutures().get(0).get(); + } catch (ExecutionException ex) { + ExceptionPrinter.printHistory(ex, LOGGER); + } + } + } + + + public interface Blocked { + + @RPCMethod + Void blockForever(); + } + + public class AbstractBlockingControllerServerImpl extends AbstractControllerServer implements Blocked { + + public AbstractBlockingControllerServerImpl(Builder builder) throws InstantiationException { + super(builder); + } + + @Override + public void registerMethods(RPCServer server) throws CouldNotPerformException { + server.registerMethods(Blocked.class, this); + } + + @Override + public Void blockForever() { + LOGGER.info("BlockForever called"); + Integer count = 0; + while (!Thread.currentThread().isInterrupted()) { + count = count++; + } + LOGGER.info("Quit because thread has been interrupted[" + Thread.currentThread().isInterrupted() + "]"); + return null; + } + } + + public class BlockingAbstractRemoteClientImpl extends AbstractRemoteClient implements Blocked { + + private final List futureList = new ArrayList<>(); + + public BlockingAbstractRemoteClientImpl() { + super(UnitRegistryData.class); + } + + @Override + public Void blockForever() { + futureList.add(this.callMethodAsync("blockForever", Void.class)); + return null; + } + + public List getFutures() { + return futureList; + } + } +} diff --git a/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/FutureCancelTest.java b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/FutureCancelTest.java new file mode 100644 index 0000000000..4a8f58a7ee --- /dev/null +++ b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/FutureCancelTest.java @@ -0,0 +1,129 @@ +package org.openbase.jul.communication.controller; + +/*- + * #%L + * JUL Extension Controller + * %% + * Copyright (C) 2015 - 2022 openbase.org + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + +import com.google.protobuf.Any; +import org.junit.jupiter.api.Test; +import org.openbase.jul.annotation.RPCMethod; +import org.openbase.jul.communication.config.CommunicatorConfig; +import org.openbase.jul.communication.data.RPCResponse; +import org.openbase.jul.communication.iface.CommunicatorFactory; +import org.openbase.jul.communication.iface.RPCClient; +import org.openbase.jul.communication.iface.RPCServer; +import org.openbase.jul.communication.mqtt.CommunicatorFactoryImpl; +import org.openbase.jul.communication.mqtt.DefaultCommunicatorConfig; +import org.openbase.jul.exception.CouldNotPerformException; +import org.openbase.jul.extension.type.processing.ScopeProcessor; +import org.openbase.jul.iface.Requestable; +import org.openbase.jul.schedule.WatchDog; +import org.openbase.type.communication.ScopeType.Scope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * @author Tamino Huxohl + */ +public class FutureCancelTest extends MqttIntegrationTest implements Requestable { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + public FutureCancelTest() { + } + + private boolean run = true; + + @RPCMethod + @Override + public Integer requestStatus() throws CouldNotPerformException { + System.out.println("RequestStatus"); + try { + while (run) { + if (Thread.currentThread().isInterrupted()) { + System.out.println("Interrupted"); + Thread.currentThread().interrupt(); + } + System.out.println("Sleeping..."); + Thread.sleep(200); + } + } catch (InterruptedException ex) { + System.out.println("Interrupted"); + } catch (CancellationException ex) { + System.out.println("Cancelled"); + } catch (Exception ex) { + System.out.println("Other" + ex); + } catch (Throwable ex) { + System.out.println("Test" + ex); + } + + return 0; + } + + /** + * This test shows that the method executed by the local server does not + * get interrupted through canceling the future. + * + * @throws Exception + */ + @Test + public void testFutureCancellation() throws Exception { + System.out.println("TestFutureCancellation"); + + final CommunicatorFactory factory = CommunicatorFactoryImpl.Companion.getInstance(); + final CommunicatorConfig defaultCommunicatorConfig = DefaultCommunicatorConfig.Companion.getInstance(); + + Scope scope = ScopeProcessor.generateScope("/test/futureCancel"); + + RPCServer server = factory.createRPCServer(scope, defaultCommunicatorConfig); + RPCClient client = factory.createRPCClient(scope, defaultCommunicatorConfig); + + WatchDog serverWatchDog = new WatchDog(server, "PRCServer"); + WatchDog clientWatchDog = new WatchDog(client, "RPCClient"); + + // register rpc methods. + server.registerMethods((Class) getClass(), this); + + serverWatchDog.activate(); + serverWatchDog.waitForServiceActivation(); + + clientWatchDog.activate(); + clientWatchDog.waitForServiceActivation(); + + Future> future = client.callMethod("requestStatus", Any.class); + try { + future.get(1000, TimeUnit.MILLISECONDS); + } catch (TimeoutException ex) { + System.out.println("Future cancelled: " + future.cancel(true)); + Thread.sleep(1000); + } + + serverWatchDog.shutdown(); + clientWatchDog.shutdown(); + + run = false; + } +} diff --git a/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/MqttIntegrationTest.java b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/MqttIntegrationTest.java new file mode 100644 index 0000000000..a9d35e95a9 --- /dev/null +++ b/module/authentication/test/src/test/java/org/openbase/jul/communication/controller/MqttIntegrationTest.java @@ -0,0 +1,76 @@ +package org.openbase.jul.communication.controller; + +/*- + * #%L + * JUL Extension Controller + * %% + * Copyright (C) 2015 - 2022 openbase.org + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * . + * #L% + */ + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.openbase.jps.core.JPService; +import org.openbase.jps.exception.JPServiceException; +import org.openbase.jul.communication.jp.JPComHost; +import org.openbase.jul.communication.jp.JPComPort; +import org.openbase.jul.communication.mqtt.SharedMqttClient; +import org.testcontainers.containers.BindMode; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.utility.DockerImageName; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Arrays; + +public class MqttIntegrationTest { + + public static final int port = 1883; + public static Path mosquittoConfig; + public static GenericContainer broker; + + @BeforeAll + public static void setUpClass() throws JPServiceException, IOException { + mosquittoConfig = Files.createTempFile("mosquitto_", ".conf"); + Files.write(mosquittoConfig, Arrays.asList( + "allow_anonymous true", + "listener "+port) + ); + + broker = new GenericContainer<>(DockerImageName.parse("eclipse-mosquitto")) + .withExposedPorts(port) + .withFileSystemBind( + mosquittoConfig.toString(), + "/mosquitto/config/mosquitto.conf", + BindMode.READ_ONLY + ); + broker.withStartupTimeout(Duration.ofSeconds(30)).start(); + + JPService.registerProperty(JPComPort.class, broker.getFirstMappedPort()); + JPService.registerProperty(JPComHost.class, broker.getHost()); + JPService.setupJUnitTestMode(); + } + + @AfterAll + public static void tearDownClass() throws IOException { + SharedMqttClient.INSTANCE.waitForShutdown(); + broker.stop(); + Files.delete(mosquittoConfig); + } +} diff --git a/module/dal/control/src/main/java/org/openbase/bco/dal/control/action/ActionImpl.java b/module/dal/control/src/main/java/org/openbase/bco/dal/control/action/ActionImpl.java index 0b4b00bf72..872b6b6e96 100644 --- a/module/dal/control/src/main/java/org/openbase/bco/dal/control/action/ActionImpl.java +++ b/module/dal/control/src/main/java/org/openbase/bco/dal/control/action/ActionImpl.java @@ -71,7 +71,7 @@ public class ActionImpl implements SchedulableAction { protected final AbstractUnitController unit; private final SyncObject executionStateChangeSync = new SyncObject("ExecutionStateChangeSync"); private final SyncObject actionTaskLock = new SyncObject("ActionTaskLock"); - private final ReentrantReadWriteLock actionDescriptionBuilderLock = new ReentrantReadWriteLock(); + private final BundledReentrantReadWriteLock actionDescriptionBuilderLock; private ActionDescription.Builder actionDescriptionBuilder; private Message serviceState; private ServiceDescription serviceDescription; @@ -87,8 +87,9 @@ public class ActionImpl implements SchedulableAction { * * @throws InstantiationException is throw in case the given action description is invalid. Checkout the exception cause chain for more details. */ - public ActionImpl(final ActionDescription actionDescription, final AbstractUnitController unit) throws InstantiationException { + public ActionImpl(final ActionDescription actionDescription, final AbstractUnitController unit, final ReentrantReadWriteLock dataLock) throws InstantiationException { try { + this.actionDescriptionBuilderLock = new BundledReentrantReadWriteLock(dataLock, true, this); this.unit = unit; this.init(actionDescription); } catch (InterruptedException ex) { @@ -108,8 +109,9 @@ public ActionImpl(final ActionDescription actionDescription, final AbstractUnitC * * @throws InstantiationException is throw in case the given action description is invalid. Checkout the exception cause chain for more details. */ - public ActionImpl(final Message serviceState, final AbstractUnitController unit) throws InstantiationException { + public ActionImpl(final Message serviceState, final AbstractUnitController unit, final ReentrantReadWriteLock dataLock) throws InstantiationException { try { + this.actionDescriptionBuilderLock = new BundledReentrantReadWriteLock(dataLock, true, this); this.unit = unit; this.init(serviceState); } catch (InterruptedException ex) { @@ -128,7 +130,7 @@ public void init(final ActionDescription actionDescription) throws Initializatio private void init(final ActionDescription actionDescription, final boolean prepare) throws InitializationException, InterruptedException { LOGGER.trace("================================================================================"); - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); try { actionDescriptionBuilder = actionDescription.toBuilder(); @@ -152,13 +154,13 @@ private void init(final ActionDescription actionDescription, final boolean prepa } catch (CouldNotPerformException ex) { throw new InitializationException(this, ex); } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } private void init(final Message serviceState) throws InitializationException, InterruptedException { LOGGER.trace("================================================================================"); - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); try { this.serviceState = serviceState; @@ -179,7 +181,7 @@ private void init(final Message serviceState) throws InitializationException, In } catch (CouldNotPerformException ex) { throw new InitializationException(this, ex); } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } @@ -212,7 +214,7 @@ public Future execute() { // builder lock has to be locked first before locking the action task lock to avoid deadlocks try { - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return FutureProcessor.canceledFuture(ActionDescription.class, ex); @@ -241,6 +243,7 @@ public Future execute() { try { updateActionState(ActionState.State.INITIATING); } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); return FutureProcessor.canceledFuture(ActionDescription.class, ex); } @@ -351,7 +354,7 @@ public Future execute() { return actionTask; } } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } @@ -410,11 +413,15 @@ private void setRequestedState() throws CouldNotPerformException, InterruptedExc */ @Override public ActionDescription getActionDescription() { - actionDescriptionBuilderLock.readLock().lock(); try { - return actionDescriptionBuilder.build(); - } finally { - actionDescriptionBuilderLock.readLock().unlock(); + actionDescriptionBuilderLock.lockReadInterruptibly(); + try { + return actionDescriptionBuilder.build(); + } finally { + actionDescriptionBuilderLock.unlockRead(); + } + } catch (InterruptedException ex) { + throw new RuntimeException(new NotAvailableException("ActionDescription", ex)); } } @@ -422,7 +429,12 @@ public ActionDescription getActionDescription() { public void autoExtendWithLowPriority() throws VerificationFailedException { // auto extend - actionDescriptionBuilderLock.writeLock().lock(); + try { + actionDescriptionBuilderLock.lockWriteInterruptibly(); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + try { // validate if action is extendable @@ -443,7 +455,7 @@ public void autoExtendWithLowPriority() throws VerificationFailedException { // has to be reset because otherwise the action would still be invalid. actionDescriptionBuilder.setLastExtensionTimestamp(TimestampProcessor.getCurrentTimestamp()); } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } // validate that action is valid after extension @@ -459,42 +471,47 @@ public void autoExtendWithLowPriority() throws VerificationFailedException { public Future cancel() { try { - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return FutureProcessor.canceledFuture(ActionDescription.class, ex); } try { - // if action is not executing, set to canceled if not already done and finish - if (!isProcessing()) { - if (!isDone()) { - updateActionStateWhileHoldingWriteLock(State.CANCELED); - } + synchronized (actionTaskLock) { + // if action is not executing, set to canceled if not already done and finish + if (!isProcessing()) { + if (!isDone()) { + updateActionStateWhileHoldingWriteLock(State.CANCELED); + } - // we need to update the transaction id to inform the remote that the action was successful even when already canceled. - try { - unit.updateTransactionId(); - } catch (CouldNotPerformException ex) { - ExceptionPrinter.printHistory("Could not update transaction id", ex, LOGGER); - } + // we need to update the transaction id to inform the remote that the action was successful even when already canceled. + try { + unit.updateTransactionId(); + } catch (CouldNotPerformException ex) { + ExceptionPrinter.printHistory("Could not update transaction id", ex, LOGGER); + } - // notify transaction id change - try { - if (!unit.isDataBuilderWriteLockedByCurrentThread()) { - unit.notifyChange(); + // notify transaction id change + try { + if (!unit.isDataBuilderWriteLockedByCurrentThread()) { + unit.notifyChange(); + } + } catch (CouldNotPerformException ex) { + ExceptionPrinter.printHistory("Could not notify transaction id update", ex, LOGGER); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + return FutureProcessor.canceledFuture(ActionDescription.class, ex); } - } catch (CouldNotPerformException ex) { - ExceptionPrinter.printHistory("Could not notify transaction id update", ex, LOGGER); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - return FutureProcessor.canceledFuture(ActionDescription.class, ex); + + return FutureProcessor.completedFuture(getActionDescription()); } - return FutureProcessor.completedFuture(getActionDescription()); - } + // action is currently executing, so set to canceling, wait till its done, set to canceled and trigger reschedule - // action is currently executing, so set to canceling, wait till its done, set to canceled and trigger reschedule - updateActionStateWhileHoldingWriteLock(State.CANCELING); + if(getActionState() != State.INITIATING) { + updateActionStateWhileHoldingWriteLock(State.CANCELING); + } + } try { return GlobalCachedExecutorService.submit(() -> { @@ -520,14 +537,14 @@ public Future cancel() { return FutureProcessor.canceledFuture(ActionDescription.class, new CouldNotPerformException("Could not cancel " + this, ex)); } } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } @Override public Future abort(boolean forceReject) { try { - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return FutureProcessor.canceledFuture(ActionDescription.class, ex); @@ -559,7 +576,7 @@ public Future abort(boolean forceReject) { return getActionDescription(); }); } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } @@ -572,7 +589,11 @@ public void schedule() { // cancel action task cancelActionTask(); - actionDescriptionBuilderLock.writeLock().lock(); + try { + actionDescriptionBuilderLock.lockWriteInterruptibly(); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } try { if (isProcessing()) { @@ -599,7 +620,7 @@ public void schedule() { updateActionStateWhileHoldingWriteLock(State.SCHEDULED); } } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } @@ -612,7 +633,11 @@ public void reject() { // cancel action task cancelActionTask(); - actionDescriptionBuilderLock.writeLock().lock(); + try { + actionDescriptionBuilderLock.lockWriteInterruptibly(); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } try { if (isProcessing()) { @@ -639,7 +664,7 @@ public void reject() { updateActionStateWhileHoldingWriteLock(State.REJECTED); } } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } @@ -652,7 +677,11 @@ public void finish() { // cancel action task cancelActionTask(); - actionDescriptionBuilderLock.writeLock().lock(); + try { + actionDescriptionBuilderLock.lockWriteInterruptibly(); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } try { // if not already finished then we force the state. @@ -660,15 +689,15 @@ public void finish() { updateActionStateWhileHoldingWriteLock(State.FINISHED); } } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } private void cancelActionTask() { - if (actionDescriptionBuilderLock.isWriteLockedByCurrentThread()) { - new FatalImplementationErrorException("Any thead that cancels the action task should not hold the builder lock, because the lock is required to guarantee a proper task shutdown.", this); - } +// if (actionDescriptionBuilderLock.isAnyWriteLockHeldByCurrentThread()) { +// new FatalImplementationErrorException("Any thread that cancels the action task should not hold the builder lock, because the lock is required to guarantee a proper task shutdown.", this); +// } // finalize if still running if (!isActionTaskFinish()) { @@ -709,7 +738,7 @@ private void updateActionStateIfNotCanceled(final ActionState.State state) throw } private void updateActionStateWhileHoldingWriteLock(final ActionState.State state) { - if (!actionDescriptionBuilderLock.isWriteLockedByCurrentThread()) { + if (!actionDescriptionBuilderLock.isAnyWriteLockHeldByCurrentThread()) { new FatalImplementationErrorException("Update Action description while not holding the action description write lock!", this); } try { @@ -721,7 +750,7 @@ private void updateActionStateWhileHoldingWriteLock(final ActionState.State stat } private void updateActionState(final ActionState.State state) throws InterruptedException { - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); try { // duplicated state confirmation should be ok to simplify the code, but than skip the update. @@ -786,7 +815,7 @@ private void updateActionState(final ActionState.State state) throws Interrupted actionDescriptionBuilder.setTerminationTimestamp(TimestampProcessor.getCurrentTimestamp()); } } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } // make sure that state changes to finishing states, scheduled and executing always trigger a notification @@ -887,21 +916,21 @@ private void validateStateTransition(final ActionState.State state) throws Inval } public void setExecutionTimePeriod(final long time, final TimeUnit timeUnit) throws InterruptedException, CouldNotPerformException { - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); try { if (time <= 0) { throw new CouldNotPerformException("Invalid execution time " + time + timeUnit.name()); } TimestampProcessor.updateTimestamp(time, actionDescriptionBuilder, timeUnit, LOGGER); } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } @Override public Future extend() { try { - actionDescriptionBuilderLock.writeLock().lockInterruptibly(); + actionDescriptionBuilderLock.lockWriteInterruptibly(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return FutureProcessor.canceledFuture(ActionDescription.class, ex); @@ -910,7 +939,7 @@ public Future extend() { actionDescriptionBuilder.setLastExtensionTimestamp(TimestampProcessor.getCurrentTimestamp()); return FutureProcessor.completedFuture(actionDescriptionBuilder.build()); } finally { - actionDescriptionBuilderLock.writeLock().unlock(); + actionDescriptionBuilderLock.unlockWrite(); } } diff --git a/module/dal/control/src/main/java/org/openbase/bco/dal/control/layer/unit/AbstractUnitController.java b/module/dal/control/src/main/java/org/openbase/bco/dal/control/layer/unit/AbstractUnitController.java index fe19687b2b..279cf69220 100644 --- a/module/dal/control/src/main/java/org/openbase/bco/dal/control/layer/unit/AbstractUnitController.java +++ b/module/dal/control/src/main/java/org/openbase/bco/dal/control/layer/unit/AbstractUnitController.java @@ -617,7 +617,7 @@ public void registerTerminatingAction() throws InterruptedException { actionParameter.getActionInitiatorBuilder().setInitiatorType(InitiatorType.SYSTEM); actionParameter.setExecutionTimePeriod(TimeUnit.MILLISECONDS.toMicros(TimedProcessable.INFINITY_TIMEOUT)); - final ActionImpl action = new ActionImpl(ActionDescriptionProcessor.generateActionDescriptionBuilder(actionParameter).build(), this); + final ActionImpl action = new ActionImpl(ActionDescriptionProcessor.generateActionDescriptionBuilder(actionParameter).build(), this, dataLock); action.schedule(); // add action to action list and sync it back into the data builder @@ -672,7 +672,7 @@ public Future applyUnauthorizedAction(final ActionDescription @Override public Future applyAction(final ActionDescription actionDescription) { try { - return scheduleAction(new ActionImpl(actionDescription, this)); + return scheduleAction(new ActionImpl(actionDescription, this, dataLock)); } catch (CouldNotPerformException ex) { return FutureProcessor.canceledFuture(ActionDescription.class, ExceptionPrinter.printHistoryAndReturnThrowable(new CouldNotPerformException("Could not apply action!", ex), logger)); } @@ -1675,7 +1675,8 @@ private Message forceActionExecution(final Message serviceState, final ServiceTy } // add action to force - scheduledActionList.add(0, new ActionImpl(serviceStateBuilder.build(), this)); + + scheduledActionList.add(0, new ActionImpl(serviceStateBuilder.build(), this, dataLock)); // trigger a reschedule which can trigger the action with a higher priority again reschedule(); diff --git a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionComparatorTest.java b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionComparatorTest.java index 936e1ff44f..2e14c8a4fc 100644 --- a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionComparatorTest.java +++ b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionComparatorTest.java @@ -34,8 +34,8 @@ import java.util.List; import java.util.concurrent.Future; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; + +import static org.junit.jupiter.api.Assertions.*; /** * @author Tamino Huxohl diff --git a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionDescriptionProcessorTest.java b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionDescriptionProcessorTest.java index 7382b84638..aab799ca26 100644 --- a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionDescriptionProcessorTest.java +++ b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/action/ActionDescriptionProcessorTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.openbase.type.domotic.action.ActionDescriptionType.ActionDescription; import org.openbase.type.domotic.action.ActionDescriptionType.ActionDescription.Builder; @@ -55,16 +55,16 @@ void getUnitChainSuffixForNonReplaceableAction() { ActionDescriptionProcessor.updateActionCause(locationActionDescription, sceneMoodLightActionDescription); ActionDescriptionProcessor.updateActionCause(lightActionDescription, locationActionDescription); - Assert.assertEquals(true, buttonActionDescription.getReplaceable()); - Assert.assertEquals(false, sceneChillActionDescription.getReplaceable()); - Assert.assertEquals(false, sceneMoodLightActionDescription.getReplaceable()); - Assert.assertEquals(true, locationActionDescription.getReplaceable()); - Assert.assertEquals(true, lightActionDescription.getReplaceable()); + assertEquals(true, buttonActionDescription.getReplaceable()); + assertEquals(false, sceneChillActionDescription.getReplaceable()); + assertEquals(false, sceneMoodLightActionDescription.getReplaceable()); + assertEquals(true, locationActionDescription.getReplaceable()); + assertEquals(true, lightActionDescription.getReplaceable()); - Assert.assertEquals("Chain suffix does not match!", "Button", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(buttonActionDescription.build())); - Assert.assertEquals("Chain suffix does not match!", "SceneChill", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(sceneChillActionDescription.build())); - Assert.assertEquals("Chain suffix does not match!", "SceneMoodLight", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(sceneMoodLightActionDescription.build())); - Assert.assertEquals("Chain suffix does not match!", "SceneMoodLight_Location", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(locationActionDescription.build())); - Assert.assertEquals("Chain suffix does not match!", "SceneMoodLight_Location_Light", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(lightActionDescription.build())); + assertEquals("Button", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(buttonActionDescription.build()), "Chain suffix does not match!"); + assertEquals("SceneChill", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(sceneChillActionDescription.build()), "Chain suffix does not match!"); + assertEquals("SceneMoodLight", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(sceneMoodLightActionDescription.build()), "Chain suffix does not match!"); + assertEquals("SceneMoodLight_Location", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(locationActionDescription.build()), "Chain suffix does not match!"); + assertEquals("SceneMoodLight_Location_Light", ActionDescriptionProcessor.getUnitChainSuffixForNonReplaceableAction(lightActionDescription.build()), "Chain suffix does not match!"); } } diff --git a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceJSonProcessorTest.java b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceJSonProcessorTest.java index 3233242098..53a9515e4d 100644 --- a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceJSonProcessorTest.java +++ b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceJSonProcessorTest.java @@ -23,7 +23,7 @@ */ import com.google.protobuf.Message; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceStateProcessorTest.java b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceStateProcessorTest.java index ad09d17220..ece7e4cc90 100644 --- a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceStateProcessorTest.java +++ b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServiceStateProcessorTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import com.google.protobuf.Message; import org.junit.jupiter.api.Test; import org.openbase.jul.exception.CouldNotPerformException; @@ -40,13 +41,9 @@ import org.openbase.type.timing.TimestampType.Timestamp; import org.openbase.type.vision.ColorType.Color; import org.openbase.type.vision.HSBColorType.HSBColor; - import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - public class ServiceStateProcessorTest { @Test @@ -54,23 +51,23 @@ public void updateLatestValueOccurrence() throws Exception { PresenceState.Builder builder = PresenceState.newBuilder(); ServiceStateProcessor.updateLatestValueOccurrence(State.PRESENT, 2000, builder); // System.out.println(builder.build()); - assertEquals("Timestamp update not correctly handled.", 2000, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime()); + assertEquals(2000, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime(), "Timestamp update not correctly handled."); // System.out.println("=============="); ServiceStateProcessor.updateLatestValueOccurrence(State.ABSENT, 2002, builder); // System.out.println(builder.build()); - assertEquals("Timestamp update not correctly handled.", 2000, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime()); - assertEquals("Timestamp update not correctly handled.", 2002, ServiceStateProcessor.getLatestValueOccurrence(State.ABSENT, builder).getTime()); + assertEquals(2000, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime(), "Timestamp update not correctly handled."); + assertEquals(2002, ServiceStateProcessor.getLatestValueOccurrence(State.ABSENT, builder).getTime(), "Timestamp update not correctly handled."); // System.out.println("=============="); ServiceStateProcessor.updateLatestValueOccurrence(State.PRESENT, 2004, builder); // System.out.println(builder.build()); - assertEquals("Timestamp update not correctly handled.", 2004, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime()); - assertEquals("Timestamp update not correctly handled.", 2002, ServiceStateProcessor.getLatestValueOccurrence(State.ABSENT, builder).getTime()); + assertEquals(2004, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime(), "Timestamp update not correctly handled."); + assertEquals(2002, ServiceStateProcessor.getLatestValueOccurrence(State.ABSENT, builder).getTime(), "Timestamp update not correctly handled."); // System.out.println("=============="); ServiceStateProcessor.updateLatestValueOccurrence(State.PRESENT, 1200, builder); ServiceStateProcessor.updateLatestValueOccurrence(State.ABSENT, 2200, builder); ServiceStateProcessor.updateLatestValueOccurrence(State.ABSENT, -1, builder); - assertEquals("", 2004, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime()); - assertEquals("", 2200, ServiceStateProcessor.getLatestValueOccurrence(State.ABSENT, builder).getTime()); + assertEquals(2004, ServiceStateProcessor.getLatestValueOccurrence(State.PRESENT, builder).getTime()); + assertEquals(2200, ServiceStateProcessor.getLatestValueOccurrence(State.ABSENT, builder).getTime()); } /** @@ -129,16 +126,18 @@ public void testForNestedType() throws Exception { @Override public void update(DataProvider source, LocationData data) throws Exception { notificationCounter++; - assertEquals("LocationData has been notified even though only the timestamp changed", 1, notificationCounter); + assertEquals(1, notificationCounter, "LocationData has been notified even though only the timestamp changed"); } }); - assertFalse("LocationData equal even though they have different timestamps", locationData1.build().equals(locationData2.build())); - assertFalse("LocationData hashcodes are equal even though they have different timestamps", locationData1.build().hashCode() == locationData2.build().hashCode()); + assertFalse(locationData1.build().equals(locationData2.build()), "LocationData equal even though they have different timestamps"); + assertFalse(locationData1.build().hashCode() == locationData2.build().hashCode(), "LocationData hashcodes are equal even though they have different timestamps"); - assertEquals("Hashes of both data types do not match after removed timestamps", + assertEquals( messageObservable.removeTimestamps(locationData1).build().hashCode(), - messageObservable.removeTimestamps(locationData2).build().hashCode()); + messageObservable.removeTimestamps(locationData2).build().hashCode(), + "Hashes of both data types do not match after removed timestamps" + ); messageObservable.notifyObservers(locationData1.build()); messageObservable.notifyObservers(locationData2.build()); diff --git a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServicesTest.java b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServicesTest.java index 0582e59f0c..74470be5a1 100644 --- a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServicesTest.java +++ b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/ServicesTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import com.google.protobuf.Message; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -38,8 +39,6 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.*; - /** * @author Tamino Huxohl */ @@ -56,7 +55,7 @@ public void testSuperStateConversion() throws Exception { final BrightnessState brightnessState = BrightnessState.newBuilder().setBrightness(.5d).build(); final Message expectedPowerState = BrightnessStateProviderService.toPowerState(brightnessState); final Message actualPowerState = Services.convertToSuperState(ServiceType.BRIGHTNESS_STATE_SERVICE, brightnessState, ServiceType.POWER_STATE_SERVICE); - assertEquals("Conversion from brightness state to power state did not go as expected", expectedPowerState, actualPowerState); + assertEquals(expectedPowerState, actualPowerState, "Conversion from brightness state to power state did not go as expected"); } /** @@ -84,9 +83,9 @@ public void testEqualServiceStates() throws Exception { for (int i = 0; i < localPositionStateList.size(); i++) { for (int j = 1; j < localPositionStateList.size(); j++) { - assertEquals("Comparison between position states " + i + " and " + j + " yields unexpected result", (i == j || (i != 3 && j != 3)), Services.equalServiceStates(localPositionStateList.get(i), localPositionStateList.get(j))); + assertEquals((i == j || (i != 3 && j != 3)), Services.equalServiceStates(localPositionStateList.get(i), localPositionStateList.get(j)), "Comparison between position states " + i + " and " + j + " yields unexpected result"); } - assertFalse("PowerState should never match a local position state", Services.equalServiceStates(localPositionStateList.get(i), powerState)); + assertFalse(Services.equalServiceStates(localPositionStateList.get(i), powerState), "PowerState should never match a local position state"); } } @@ -97,8 +96,8 @@ public void testEqualBrightnessStateServices() throws Exception { BrightnessState brightnessStateInMargin = BrightnessState.newBuilder().setBrightness(brightness + 0.9 * Services.DOUBLE_MARGIN).build(); BrightnessState brightnessStateOutsideMargin = BrightnessState.newBuilder().setBrightness(brightness + 2 * Services.DOUBLE_MARGIN).build(); - assertTrue("Brightness states are not considered equal even though the value is within margin", Services.equalServiceStates(brightnessState, brightnessStateInMargin)); - assertFalse("Brightness states are considered equal even though the value is outside margin", Services.equalServiceStates(brightnessState, brightnessStateOutsideMargin)); + assertTrue(Services.equalServiceStates(brightnessState, brightnessStateInMargin), "Brightness states are not considered equal even though the value is within margin"); + assertFalse(Services.equalServiceStates(brightnessState, brightnessStateOutsideMargin), "Brightness states are considered equal even though the value is outside margin"); } diff --git a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ColorStateProviderServiceTest.java b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ColorStateProviderServiceTest.java index ae090ef2a7..03411ae085 100644 --- a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ColorStateProviderServiceTest.java +++ b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ColorStateProviderServiceTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.openbase.jps.core.JPService; import org.openbase.jps.exception.JPServiceException; @@ -47,8 +47,8 @@ public void verifyColorState() throws VerificationFailedException, JPServiceExce final ColorState verifiedColorState = ColorStateProviderService.verifyColorState(builder.build()); ExceptionPrinter.setBeQuit(false); - Assert.assertEquals("Hue value invalid!", builder.getColorBuilder().getHsbColorBuilder().getHue(), verifiedColorState.getColor().getHsbColor().getHue(), 0.00001); - Assert.assertEquals("Hue value invalid!", 1d, verifiedColorState.getColor().getHsbColor().getSaturation(), 0.00001); - Assert.assertEquals("Hue value invalid!", 0.5d, verifiedColorState.getColor().getHsbColor().getBrightness(), 0.00001); + assertEquals(builder.getColorBuilder().getHsbColorBuilder().getHue(), verifiedColorState.getColor().getHsbColor().getHue(), 0.00001, "Hue value invalid!"); + assertEquals(1d, verifiedColorState.getColor().getHsbColor().getSaturation(), 0.00001, "Hue value invalid!"); + assertEquals(0.5d, verifiedColorState.getColor().getHsbColor().getBrightness(), 0.00001, "Hue value invalid!"); } } diff --git a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ServicesTest.java b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ServicesTest.java index bf9faf35fc..f5f04fa87a 100644 --- a/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ServicesTest.java +++ b/module/dal/lib/src/test/java/org/openbase/bco/dal/lib/layer/service/provider/ServicesTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.dal.lib.layer.service.Services; @@ -56,7 +56,7 @@ public void testComputeActionImpact() throws CouldNotPerformException, Interrupt final Set impact = Services.computeActionImpact(serviceStateBuilder.build()); impact.forEach( - it -> Assert.assertNotEquals("Computed impact does not offer an valid action id!", "", it.getActionId()) + it -> assertNotEquals("Computed impact does not offer an valid action id!", "", it.getActionId()) ); final List impactedUnitIdList = impact.stream() @@ -73,6 +73,6 @@ public void testComputeActionImpact() throws CouldNotPerformException, Interrupt .sorted() .collect(Collectors.toList()); - Assert.assertEquals("impacted unit id list differs as expected", affectedUnitsUnsorted, impactedUnitIdList); + assertEquals(affectedUnitsUnsorted, impactedUnitIdList, "impacted unit id list differs as expected"); } } diff --git a/module/dal/test/build.gradle.kts b/module/dal/test/build.gradle.kts index 4cf5780499..22f9ccee53 100644 --- a/module/dal/test/build.gradle.kts +++ b/module/dal/test/build.gradle.kts @@ -1,3 +1,4 @@ + /* * This file was generated by the Gradle 'init' task. */ @@ -12,6 +13,9 @@ dependencies { api(project(":bco.dal.control")) api(project(":bco.dal.visual")) api(project(":bco.authentication.test")) + implementation("org.junit.jupiter:junit-jupiter:[5.8,5.9-alpha)") + implementation ("org.junit.jupiter:junit-jupiter-api:[5.8,5.9-alpha)") + implementation ("org.junit.jupiter:junit-jupiter-engine:[5.8,5.9-alpha)") } description = "BCO DAL Test" diff --git a/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCODeviceManagerTest.java b/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCODeviceManagerTest.java index a6fa22b957..e32746ca67 100644 --- a/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCODeviceManagerTest.java +++ b/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCODeviceManagerTest.java @@ -22,10 +22,10 @@ * #L% */ -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.openbase.bco.dal.control.layer.unit.device.DeviceManagerLauncher; import org.openbase.bco.dal.lib.layer.unit.UnitController; import org.openbase.jul.exception.CouldNotPerformException; @@ -36,17 +36,15 @@ /** * @author Tamino Huxohl */ -public class AbstractBCODeviceManagerTest extends AbstractBCOTest { +public abstract class AbstractBCODeviceManagerTest extends AbstractBCOTest { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractBCODeviceManagerTest.class); protected static DeviceManagerLauncher deviceManagerLauncher; - @BeforeClass - public static void setUpClass() throws Throwable { + @BeforeAll + public static void setupDeviceManager() throws Throwable { try { - AbstractBCOTest.setUpClass(); - deviceManagerLauncher = new DeviceManagerLauncher(); deviceManagerLauncher.launch().get(); } catch (Throwable ex) { @@ -54,13 +52,12 @@ public static void setUpClass() throws Throwable { } } - @AfterClass - public static void tearDownClass() throws Throwable { + @AfterAll + public static void tearDownDeviceManage() throws Throwable { try { if (deviceManagerLauncher != null) { deviceManagerLauncher.shutdown(); } - AbstractBCOTest.tearDownClass(); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); } @@ -71,8 +68,8 @@ public static void tearDownClass() throws Throwable { * * @throws InterruptedException is thrown if the thread was externally interrupted */ - @Before - @After + @BeforeEach + @AfterEach public void cancelAllOngoingActions() throws InterruptedException { LOGGER.info("Cancel all ongoing actions..."); try { diff --git a/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCOTest.java b/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCOTest.java index 6aa907b8d8..ab8cf857be 100644 --- a/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCOTest.java +++ b/module/dal/test/src/main/java/org/openbase/bco/dal/test/AbstractBCOTest.java @@ -23,10 +23,11 @@ */ import lombok.NonNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.openbase.bco.authentication.lib.SessionManager; import org.openbase.bco.authentication.lib.iface.BCOSession; import org.openbase.bco.authentication.mock.MqttIntegrationTest; @@ -35,6 +36,7 @@ import org.openbase.bco.registry.mock.MockRegistry; import org.openbase.bco.registry.mock.MockRegistryHolder; import org.openbase.jps.core.JPService; +import org.openbase.jps.exception.JPServiceException; import org.openbase.jul.exception.CouldNotPerformException; import org.openbase.jul.exception.StackTracePrinter; import org.openbase.jul.exception.printer.ExceptionPrinter; @@ -52,7 +54,7 @@ /** * @author Tamino Huxohl */ -public class AbstractBCOTest extends MqttIntegrationTest { +public abstract class AbstractBCOTest extends MqttIntegrationTest { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AbstractBCOTest.class); @@ -60,11 +62,9 @@ public class AbstractBCOTest extends MqttIntegrationTest { private final List testActions = Collections.synchronizedList(new ArrayList<>()); - @BeforeClass - public static void setUpClass() throws Throwable { + @BeforeAll + public static void setupBCO() throws Throwable { try { - MqttIntegrationTest.setUpClass(); - JPService.setupJUnitTestMode(); mockRegistry = MockRegistryHolder.newMockRegistry(); Units.reinitialize(); } catch (Throwable ex) { @@ -72,13 +72,12 @@ public static void setUpClass() throws Throwable { } } - @AfterClass - public static void tearDownClass() throws Throwable { + @AfterAll + public static void tearDownBCO() throws Throwable { try { Units.reset(AbstractBCOTest.class); SessionManager.getInstance().completeLogout(); MockRegistryHolder.shutdownMockRegistry(); - MqttIntegrationTest.tearDownClass(); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); } @@ -88,17 +87,17 @@ public static void tearDownClass() throws Throwable { * Method is automatically called after each test run and there is no need to call it manually. * If you want to cancel all actions manually please use method {@code cancelAllTestActions()} to get feedback about the cancellation process. */ - @After + @AfterEach public void autoCancelActionsAfterTestRun() { // before canceling pending actions lets just validate that the test did not cause any deadlocks - Assert.assertFalse("Deadlocks found!", StackTracePrinter.detectDeadLocksAndPrintStackTraces(LOGGER)); + assertFalse(StackTracePrinter.detectDeadLocksAndPrintStackTraces(LOGGER), "Deadlocks found!"); try { cancelAllTestActions(); } catch (Exception ex) { ExceptionPrinter.printHistory("Could not cancel all test actions of test suite: " + getClass().getName(), ex, LOGGER); - Assert.fail("Could not cancel all test actions of test suite: " + getClass().getName()); + fail("Could not cancel all test actions of test suite: " + getClass().getName()); } } diff --git a/module/dal/test/src/main/java/org/openbase/bco/dal/test/TestPropertyHandler.kt b/module/dal/test/src/main/java/org/openbase/bco/dal/test/TestPropertyHandler.kt new file mode 100644 index 0000000000..cebefcc37f --- /dev/null +++ b/module/dal/test/src/main/java/org/openbase/bco/dal/test/TestPropertyHandler.kt @@ -0,0 +1,6 @@ +package org.openbase.bco.dal.test + +interface TestPropertyHandler { + fun setupCustomTestProperties() + fun resetCustomTestProperties() +} diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/remote/layer/unit/CustomUnitPoolTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/remote/layer/unit/CustomUnitPoolTest.java index 977956865a..b90e840077 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/remote/layer/unit/CustomUnitPoolTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/remote/layer/unit/CustomUnitPoolTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import com.google.protobuf.Message; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -34,7 +35,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; + public class CustomUnitPoolTest extends AbstractBCODeviceManagerTest { @@ -47,7 +48,7 @@ public class CustomUnitPoolTest extends AbstractBCODeviceManagerTest { @Timeout(10) public void testUnitPool() throws Exception { final CustomUnitPool customUnitPool = new CustomUnitPool(); - assertEquals("pool is active while never activated", false, customUnitPool.isActive()); + assertEquals(false, customUnitPool.isActive(), "pool is active while never activated"); customUnitPool.activate(); @@ -58,7 +59,7 @@ public void testUnitPool() throws Exception { customUnitPool.activate(); for (UnitRemote unitRemote : customUnitPool.getInternalUnitList()) { - assertEquals("pool contains actually filtered entry!", UnitType.BUTTON, unitRemote.getUnitType()); + assertEquals(UnitType.BUTTON, unitRemote.getUnitType(), "pool contains actually filtered entry!"); System.out.println("is button: "+ unitRemote.getLabel()); } @@ -69,7 +70,7 @@ public void testUnitPool() throws Exception { Registries.getUnitRegistry().updateUnitConfig(lightUnitConfig.get(0).toBuilder().addAlias("MyLightestUnit").build()).get(5, TimeUnit.SECONDS); for (UnitRemote unitRemote : customUnitPool.getInternalUnitList()) { - assertEquals("pool contains actually filtered entry!", UnitType.BUTTON, unitRemote.getUnitType()); + assertEquals(UnitType.BUTTON, unitRemote.getUnitType(), "pool contains actually filtered entry!"); System.out.println("is button: "+ unitRemote.getLabel()); } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/ActionChainTest.kt b/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/ActionChainTest.kt index 7a2e2f4935..c3caec2523 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/ActionChainTest.kt +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/ActionChainTest.kt @@ -1,8 +1,8 @@ package org.openbase.bco.dal.test.action -import org.junit.Assert -import org.junit.BeforeClass -import org.junit.Test +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout import org.openbase.bco.dal.remote.layer.unit.Units import org.openbase.bco.dal.test.layer.unit.location.AbstractBCOLocationManagerTest @@ -41,7 +41,7 @@ class ActionChainTest : AbstractBCOLocationManagerTest() { remoteAction.actionDescription.actionImpactList .map { it.serviceStateDescription.unitId } .forEach { impactedUnitId -> - Assert.assertTrue(powerStateUnits.any { it.id == impactedUnitId }) + assertTrue(powerStateUnits.any { it.id == impactedUnitId }) } } @@ -56,25 +56,11 @@ class ActionChainTest : AbstractBCOLocationManagerTest() { .map { light -> waitForExecution(light.setPowerState(PowerState.State.ON)) } .map { action -> action.actionDescription.actionImpactList } - impact.forEach { Assert.assertFalse(it.isEmpty()) } + impact.forEach { assertFalse(it.isEmpty()) } impact.forEach { impactedUnits -> - Assert.assertTrue(impactedUnits.any { + assertTrue(impactedUnits.any { it.serviceStateDescription.unitId == rootLocationRemote.id }) } } - - companion object { - private val logger = LoggerFactory.getLogger(LocationRemoteTest::class.java) - - @BeforeClass - @Throws(Throwable::class) - fun setUpClass() { - try { - AbstractBCOLocationManagerTest.setUpClass() - } catch (ex: Throwable) { - throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger) - } - } - } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/RemoteActionTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/RemoteActionTest.java index cf24e38d77..197ecaa1fd 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/RemoteActionTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/action/RemoteActionTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; import org.junit.jupiter.api.Test; import org.openbase.bco.authentication.lib.SessionManager; @@ -60,10 +60,6 @@ import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.fail; - public class RemoteActionTest extends AbstractBCOLocationManagerTest { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteActionTest.class); @@ -93,9 +89,7 @@ public RemoteActionTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCOLocationManagerTest.setUpClass(); - + public static void setupRemoteActionTest() throws Throwable { // create new user token for test try { // login as admin @@ -125,16 +119,6 @@ public static void setUpClass() throws Throwable { } } - @BeforeEach - public void setUp() throws InitializationException, InvalidStateException { - - } - - @AfterEach - public void tearDown() throws CouldNotPerformException { - - } - @Test @Timeout(10) public void testExecutionAndCancellationWithToken() throws Exception { @@ -146,20 +130,20 @@ public void testExecutionAndCancellationWithToken() throws Exception { for (int i = 0; i < 10; i++) { PowerStateType.PowerState.State powerState = (i % 2 == 0) ? PowerStateType.PowerState.State.ON : PowerStateType.PowerState.State.OFF; final RemoteAction locationRemoteAction = waitForExecution(locationRemote.setPowerState(powerState, UnitType.COLORABLE_LIGHT, mrPinkActionParameter), mrPinkUserToken); - assertTrue("Action of location does not offer an id after submission!", !locationRemoteAction.getId().isEmpty()); + assertTrue(!locationRemoteAction.getId().isEmpty(), "Action of location does not offer an id after submission!"); for (ColorableLightRemote unit : units) { boolean actionIsExecuting = false; for (ActionReferenceType.ActionReference actionReference : unit.getActionList().get(0).getActionCauseList()) { - assertTrue("Subaction of location does not offer an id after submission!", !actionReference.getActionId().isEmpty()); + assertTrue(!actionReference.getActionId().isEmpty(), "Subaction of location does not offer an id after submission!"); if (actionReference.getActionId().equals(locationRemoteAction.getId())) { actionIsExecuting = true; break; } } - assertTrue("Action on unit[" + unit + "] is not executing", actionIsExecuting); - assertEquals("Action was not authenticated by the correct user", mrPinkUserId, unit.getActionList().get(0).getActionInitiator().getAuthenticatedBy()); + assertTrue(actionIsExecuting, "Action on unit[" + unit + "] is not executing"); + assertEquals(mrPinkUserId, unit.getActionList().get(0).getActionInitiator().getAuthenticatedBy(), "Action was not authenticated by the correct user"); } locationRemoteAction.cancel().get(); @@ -185,7 +169,7 @@ public void testExecutionAndCancellationWithToken() throws Exception { fail("Caused action on unit[" + colorableLightRemote + "] could not be found!"); } - Assert.assertEquals("Action on unit[" + colorableLightRemote + "] was not cancelled!", ActionStateType.ActionState.State.CANCELED, causedAction.getActionState().getValue()); + assertEquals(ActionStateType.ActionState.State.CANCELED, causedAction.getActionState().getValue(), "Action on unit[" + colorableLightRemote + "] was not cancelled!"); } } @@ -233,7 +217,7 @@ public Boolean call() throws Exception { for (ColorableLightRemote unit : units) { unit.requestData().get(); - Assert.assertEquals("Light[" + unit + "] not on", State.ON, unit.getPowerState().getValue()); + assertEquals(State.ON, unit.getPowerState().getValue(), "Light[" + unit + "] not on"); } System.out.println("cancel dominant action"); @@ -263,12 +247,12 @@ public Boolean call() throws Exception { for (ColorableLightRemote unit : units) { unit.requestData().get(); - Assert.assertEquals("Light[" + unit + "] not off", State.OFF, unit.getPowerState().getValue()); + assertEquals(State.OFF, unit.getPowerState().getValue(), "Light[" + unit + "] not off"); } System.out.println("wait until last extension timeout and validate if no further extension will be performed for dominant action..."); Thread.sleep(dominantAction.getValidityTime(TimeUnit.MILLISECONDS) + 10); - Assert.assertEquals("Dominant action was extended even through the action was already canceled.", false, dominantActionExtentionFlag.value); + assertFalse(dominantActionExtentionFlag.value, "Dominant action was extended even through the action was already canceled."); System.out.println("cancel low prio action"); lowPrioLongtermAction.cancel().get(); @@ -284,13 +268,13 @@ public Boolean call() throws Exception { continue; } - Assert.assertEquals("Zombie[" + actionDescription.getActionState().getValue().name() + "] actions detected: " + MultiLanguageTextProcessor.getBestMatch(actionDescription.getDescription()), true, new RemoteAction(actionDescription).isDone()); + assertTrue(new RemoteAction(actionDescription).isDone(), "Zombie[" + actionDescription.getActionState().getValue().name() + "] actions detected: " + MultiLanguageTextProcessor.getBestMatch(actionDescription.getDescription())); } } System.out.println("wait until last extension timeout and validate if no further extension will be performed for low prio longterm action..."); Thread.sleep(lowPrioLongtermAction.getValidityTime(TimeUnit.MILLISECONDS) + 10); - Assert.assertEquals("Low prio action was extended even through the action was already canceled.", false, lowPrioLongtermActionExtentionFlag.value); + assertEquals(false, lowPrioLongtermActionExtentionFlag.value, "Low prio action was extended even through the action was already canceled."); System.out.println("validate if still everything is done"); for (ColorableLightRemote unit : units) { @@ -301,7 +285,7 @@ public Boolean call() throws Exception { continue; } - Assert.assertEquals("Zombie[" + actionDescription.getActionState().getValue().name() + "] actions detected: " + MultiLanguageTextProcessor.getBestMatch(actionDescription.getDescription()), true, new RemoteAction(actionDescription).isDone()); + assertEquals(true, new RemoteAction(actionDescription).isDone(), "Zombie[" + actionDescription.getActionState().getValue().name() + "] actions detected: " + MultiLanguageTextProcessor.getBestMatch(actionDescription.getDescription())); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/service/ServiceTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/service/ServiceTest.java index 64c4838d31..cd393f8a56 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/service/ServiceTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/service/ServiceTest.java @@ -26,9 +26,9 @@ import com.google.protobuf.ProtocolMessageEnum; import org.junit.jupiter.api.AfterAll; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; + -import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -49,19 +49,6 @@ */ public class ServiceTest extends AbstractBCOTest { - public ServiceTest() { - } - - @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCOTest.setUpClass(); - } - - @AfterAll - public static void tearDownClass() throws Throwable { - AbstractBCOTest.tearDownClass(); - } - /** * Test of getServiceStateClass method, of class Service. */ @@ -69,10 +56,10 @@ public static void tearDownClass() throws Throwable { public void testDetectServiceDataClass() throws Exception { System.out.println("detectServiceDataClass"); try { - Assert.assertEquals("wrong service class detected!", Services.getServiceStateClass(ServiceType.BATTERY_STATE_SERVICE), BatteryStateType.BatteryState.class); - assertEquals("wrong service class detected!", Services.getServiceStateClass(ServiceType.COLOR_STATE_SERVICE), ColorStateType.ColorState.class); - assertEquals("wrong service class detected!", Services.getServiceStateClass(ServiceType.SMOKE_STATE_SERVICE), SmokeStateType.SmokeState.class); - assertEquals("wrong service class detected!", Services.getServiceStateClass(ServiceType.MOTION_STATE_SERVICE), MotionStateType.MotionState.class); + assertEquals(Services.getServiceStateClass(ServiceType.BATTERY_STATE_SERVICE), BatteryStateType.BatteryState.class, "wrong service class detected!"); + assertEquals(Services.getServiceStateClass(ServiceType.COLOR_STATE_SERVICE), ColorStateType.ColorState.class, "wrong service class detected!"); + assertEquals(Services.getServiceStateClass(ServiceType.SMOKE_STATE_SERVICE), SmokeStateType.SmokeState.class, "wrong service class detected!"); + assertEquals(Services.getServiceStateClass(ServiceType.MOTION_STATE_SERVICE), MotionStateType.MotionState.class, "wrong service class detected!"); } catch (Exception ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, System.out); } @@ -88,7 +75,7 @@ public void testGetServiceStateValues() throws Exception { Registries.getClassRegistry().waitForData(); Collection values = Services.getServiceStateEnumValues(ServiceType.POWER_STATE_SERVICE); for (PowerState.State state : PowerState.State.values()) { - Assert.assertTrue("Detected values does not contain " + state.name(), values.contains(state)); + assertTrue(values.contains(state), "Detected values does not contain " + state.name()); } } catch (Exception ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, System.err); diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/AbstractUnitControllerTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/AbstractUnitControllerTest.java index afa4dde8df..142a677e55 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/AbstractUnitControllerTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/AbstractUnitControllerTest.java @@ -23,7 +23,7 @@ */ import com.google.protobuf.Message; -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; import org.junit.jupiter.api.Test; import org.openbase.bco.authentication.lib.SessionManager; @@ -75,8 +75,7 @@ public AbstractUnitControllerTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loginUser() throws Throwable { colorableLightRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.COLORABLE_LIGHT), true, Units.COLORABLE_LIGHT); colorableLightController = deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(colorableLightRemote.getId()); @@ -87,13 +86,12 @@ public static void setUpClass() throws Throwable { } } @AfterAll - public static void tearDownClass() throws Throwable { + public static void logoutUser() throws Throwable { sessionManager.logout(); - AbstractBCODeviceManagerTest.tearDownClass(); } @BeforeEach - public void setUp() throws CouldNotPerformException, InterruptedException, TimeoutException, ExecutionException { + public void setupUnitController() throws CouldNotPerformException, InterruptedException, TimeoutException, ExecutionException { for (ActionDescription actionDescription : colorableLightController.getActionList()) { // filter termination action @@ -102,12 +100,12 @@ public void setUp() throws CouldNotPerformException, InterruptedException, Timeo } final RemoteAction remoteAction = new RemoteAction(actionDescription); - Assert.assertTrue("Found ongoing " + remoteAction + " on stack which could interfere with test execution!", remoteAction.isDone()); + assertTrue(remoteAction.isDone(), "Found ongoing " + remoteAction + " on stack which could interfere with test execution!"); } } @AfterEach - public void tearDown() throws CouldNotPerformException, InterruptedException, TimeoutException, ExecutionException { + public void tearDownUnitController() throws CouldNotPerformException, InterruptedException, TimeoutException, ExecutionException { // cleanup leftover actions which were manually submitted to the controller. colorableLightController.cancelAllActions(); } @@ -117,26 +115,26 @@ public void tearDown() throws CouldNotPerformException, InterruptedException, Ti public void applyDataStateUpdateTest() { try { colorableLightController.applyServiceState(States.Power.ON, ServiceType.POWER_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied!", State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); + assertEquals(State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue(), "Power state updated was not applied!"); colorableLightRemote.requestData().get(); - Assert.assertEquals("Power state updated was not applied to remote instance!", State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getData().getPowerState().getValue(), "Power state updated was not applied to remote instance!"); colorableLightController.applyServiceState(States.Power.OFF, ServiceType.POWER_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied because of: "+ MultiLanguageTextProcessor.getBestMatch(((ColorableLightData) colorableLightController.getData()).getPowerState().getResponsibleAction().getDescription(), "?"), State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); + assertEquals(State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue(), "Power state updated was not applied because of: "+ MultiLanguageTextProcessor.getBestMatch(((ColorableLightData) colorableLightController.getData()).getPowerState().getResponsibleAction().getDescription(), "?")); colorableLightRemote.requestData().get(); - Assert.assertEquals("Power state updated was not applied to remote instance!", State.OFF, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.OFF, colorableLightRemote.getData().getPowerState().getValue(), "Power state updated was not applied to remote instance!"); colorableLightController.applyServiceState(States.Power.ON, ServiceType.POWER_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied!", State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); + assertEquals(State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue(), "Power state updated was not applied!"); colorableLightRemote.requestData().get(); - Assert.assertEquals("Power state updated was not applied to remote instance!", State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getData().getPowerState().getValue(), "Power state updated was not applied to remote instance!"); colorableLightController.applyServiceState(States.Power.OFF, ServiceType.POWER_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied!", State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); + assertEquals(State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue(), "Power state updated was not applied!"); colorableLightRemote.requestData().get(); - Assert.assertEquals("Power state updated was not applied to remote instance!", State.OFF, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.OFF, colorableLightRemote.getData().getPowerState().getValue(), "Power state updated was not applied to remote instance!"); } catch (CouldNotPerformException | InterruptedException | ExecutionException ex) { ExceptionPrinter.printHistory(ex, System.err); - Assert.assertTrue("Error occurred during update!", false); + assertTrue(false, "Error occurred during update!"); } } @@ -148,32 +146,32 @@ public void applyCustomDataStateUpdateTest() { System.out.println("apply on " + i); colorableLightController.applyServiceState(States.Power.ON, ServiceType.POWER_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied!", State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); - Assert.assertEquals("Power state updated was not applied!", 1.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0001); - Assert.assertEquals("Power state updated was not applied!", 1.0, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor().getHsbColor().getBrightness(), 0.0001); + assertEquals(State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue(), "Power state updated was not applied!"); + assertEquals(1.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0002, "Power state updated was not applied!"); + assertEquals(1.0, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor().getHsbColor().getBrightness(), 0.0002, "Power state updated was not applied!"); System.out.println("apply off " + i); colorableLightController.applyServiceState(States.Power.OFF, ServiceType.POWER_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied!", State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); - Assert.assertEquals("Power state updated was not applied!", 0.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0001); - Assert.assertEquals("Power state updated was not applied!", 0.0, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor().getHsbColor().getBrightness(), 0.0001); + assertEquals(State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); + assertEquals(0.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0002, "Power state updated was not applied!"); + assertEquals(0.0, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor().getHsbColor().getBrightness(), 0.0002, "Power state updated was not applied!"); System.out.println("apply green " + i); colorableLightController.applyServiceState(States.Color.GREEN, ServiceType.COLOR_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied!", State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); - Assert.assertEquals("Power state updated was not applied!", 1.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0001); - Assert.assertEquals("Power state updated was not applied!", Color.GREEN_VALUE, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor()); + assertEquals(State.ON, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); + assertEquals(1.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0002, "Power state updated was not applied!"); + assertEquals(Color.GREEN_VALUE, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor()); System.out.println("apply black " + i); colorableLightController.applyServiceState(Color.BLACK, ServiceType.COLOR_STATE_SERVICE); - Assert.assertEquals("Power state updated was not applied!", State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); - Assert.assertEquals("Power state updated was not applied!", 0.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0001); - Assert.assertEquals("Power state updated was not applied!", Color.BLACK_VALUE, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor()); + assertEquals(State.OFF, ((ColorableLightData) colorableLightController.getData()).getPowerState().getValue()); + assertEquals(0.0, ((ColorableLightData) colorableLightController.getData()).getBrightnessState().getBrightness(), 0.0002, "Power state updated was not applied!"); + assertEquals(Color.BLACK_VALUE, ((ColorableLightData) colorableLightController.getData()).getColorState().getColor()); } } catch (CouldNotPerformException ex) { ExceptionPrinter.printHistory(ex, System.err); - Assert.assertTrue("Error occurred during update!", false); + assertTrue(false, "Error occurred during update!"); } } @@ -190,15 +188,15 @@ public void applyCustomDataStateFeedbackLoopTest() { colorableLightController.applyServiceState(Power.OFF, ServiceType.POWER_STATE_SERVICE); action = waitForExecution(colorableLightRemote.setPowerState(Power.ON)); - Assert.assertEquals("Action rejected by hardware feedback loop!", ActionState.State.EXECUTING, action.getActionState()); + assertEquals(ActionState.State.EXECUTING, action.getActionState(), "Action rejected by hardware feedback loop!"); colorableLightController.applyServiceState(Color.BLUE, ServiceType.COLOR_STATE_SERVICE); colorableLightRemote.requestData().get(); - Assert.assertEquals("Action rejected by power state feedback loop!", ActionState.State.EXECUTING, action.getActionState()); + assertEquals(ActionState.State.EXECUTING, action.getActionState(), "Action rejected by power state feedback loop!"); colorableLightController.applyServiceState(BrightnessState.newBuilder().setBrightness(1.0), ServiceType.BRIGHTNESS_STATE_SERVICE); colorableLightRemote.requestData().get(); - Assert.assertEquals("Action rejected by brightness state feedback loop!", ActionState.State.EXECUTING, action.getActionState()); + assertEquals(ActionState.State.EXECUTING, action.getActionState(), "Action rejected by brightness state feedback loop!"); // perform inverse order @@ -206,19 +204,19 @@ public void applyCustomDataStateFeedbackLoopTest() { colorableLightController.applyServiceState(BrightnessState.newBuilder().setBrightness(0.0), ServiceType.BRIGHTNESS_STATE_SERVICE); action = waitForExecution(colorableLightRemote.setColorState(Color.GREEN)); - Assert.assertEquals("Action rejected by hardware feedback loop!", ActionState.State.EXECUTING, action.getActionState()); + assertEquals(ActionState.State.EXECUTING, action.getActionState(), "Action rejected by hardware feedback loop!"); colorableLightController.applyServiceState(Power.ON, ServiceType.POWER_STATE_SERVICE); colorableLightRemote.requestData().get(); - Assert.assertEquals("Action rejected by power state feedback loop!", ActionState.State.EXECUTING, action.getActionState()); + assertEquals(ActionState.State.EXECUTING, action.getActionState(), "Action rejected by power state feedback loop!"); colorableLightController.applyServiceState(BrightnessState.newBuilder().setBrightness(1.0), ServiceType.BRIGHTNESS_STATE_SERVICE); colorableLightRemote.requestData().get(); - Assert.assertEquals("Action rejected by brightness state feedback loop!", ActionState.State.EXECUTING, action.getActionState()); + assertEquals(ActionState.State.EXECUTING, action.getActionState(), "Action rejected by brightness state feedback loop!"); } catch (CouldNotPerformException | InterruptedException | ExecutionException ex) { ExceptionPrinter.printHistory(ex, System.err); - Assert.assertTrue("Error occurred during update!", false); + assertTrue(false, "Error occurred during update!"); } } @@ -227,32 +225,32 @@ public void applyCustomDataStateFeedbackLoopTest() { public void rejectUpdateWhenStateIsCompatibleTest() { try { final RemoteAction mainAction = waitForExecution(colorableLightRemote.setColorState(Color.BLUE)); - Assert.assertTrue("Main action not on top!", colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId())); - Assert.assertEquals("Main action not executing!", ActionState.State.EXECUTING, mainAction.getActionState()); + assertTrue(colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId()), "Main action not on top!"); + assertEquals(ActionState.State.EXECUTING, mainAction.getActionState(), "Main action not executing!"); // test compatible power state Message.Builder serviceStateBuilder = Power.ON.toBuilder(); serviceStateBuilder = ActionDescriptionProcessor.generateAndSetResponsibleAction(serviceStateBuilder, ServiceType.POWER_STATE_SERVICE, colorableLightController, 30, TimeUnit.MINUTES, false, true, false, Priority.HIGH, ActionInitiator.newBuilder().setInitiatorType(InitiatorType.HUMAN).build()); colorableLightController.applyDataUpdate(serviceStateBuilder, ServiceType.POWER_STATE_SERVICE); - Assert.assertTrue("Too many actions on stack!", colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId())); - Assert.assertEquals("Main action not executing!", ActionState.State.EXECUTING, mainAction.getActionState()); + assertTrue(colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId()), "Too many actions on stack!"); + assertEquals(ActionState.State.EXECUTING, mainAction.getActionState(), "Main action not executing!"); // test compatible color state serviceStateBuilder = Color.BLUE.toBuilder(); serviceStateBuilder = ActionDescriptionProcessor.generateAndSetResponsibleAction(serviceStateBuilder, ServiceType.COLOR_STATE_SERVICE, colorableLightController, 30, TimeUnit.MINUTES, false, true, false, Priority.HIGH, ActionInitiator.newBuilder().setInitiatorType(InitiatorType.HUMAN).build()); colorableLightController.applyDataUpdate(serviceStateBuilder, ServiceType.COLOR_STATE_SERVICE); - Assert.assertTrue("Too many actions on stack!", colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId())); - Assert.assertEquals("Main action not executing!", ActionState.State.EXECUTING, mainAction.getActionState()); + assertTrue(colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId()), "Too many actions on stack!"); + assertEquals(ActionState.State.EXECUTING, mainAction.getActionState(), "Main action not executing!"); // test compatible brightness state serviceStateBuilder = Brightness.MAX.toBuilder(); serviceStateBuilder = ActionDescriptionProcessor.generateAndSetResponsibleAction(serviceStateBuilder, ServiceType.BRIGHTNESS_STATE_SERVICE, colorableLightController, 30, TimeUnit.MINUTES, false, true, false, Priority.HIGH, ActionInitiator.newBuilder().setInitiatorType(InitiatorType.HUMAN).build()); colorableLightController.applyDataUpdate(serviceStateBuilder, ServiceType.BRIGHTNESS_STATE_SERVICE); - Assert.assertTrue("Too many actions on stack!", colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId())); - Assert.assertEquals("Main action not executing!", ActionState.State.EXECUTING, mainAction.getActionState()); + assertTrue(colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId()), "Too many actions on stack!"); + assertEquals(ActionState.State.EXECUTING, mainAction.getActionState(), "Main action not executing!"); // test nearly compatible color state ColorState.Builder colorServiceStateBuilder = Color.BLUE.toBuilder(); @@ -262,12 +260,12 @@ public void rejectUpdateWhenStateIsCompatibleTest() { colorServiceStateBuilder = ActionDescriptionProcessor.generateAndSetResponsibleAction(colorServiceStateBuilder, ServiceType.COLOR_STATE_SERVICE, colorableLightController, 30, TimeUnit.MINUTES, false, true, false, Priority.HIGH, ActionInitiator.newBuilder().setInitiatorType(InitiatorType.HUMAN).build()); colorableLightController.applyDataUpdate(colorServiceStateBuilder, ServiceType.COLOR_STATE_SERVICE); - Assert.assertTrue("Too many actions on stack!", colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId())); - Assert.assertEquals("Main action not executing!", ActionState.State.EXECUTING, mainAction.getActionState()); + assertTrue(colorableLightController.getActionList().get(0).getActionId().equals(mainAction.getId()), "Too many actions on stack!"); + assertEquals(ActionState.State.EXECUTING, mainAction.getActionState(), "Main action not executing!"); } catch (CouldNotPerformException | InterruptedException ex) { ExceptionPrinter.printHistory(ex, System.err); - Assert.assertTrue("Error occurred during update!", false); + assertTrue(false, "Error occurred during update!"); } } @@ -283,7 +281,7 @@ public void futureSyncTest() throws InterruptedException, ExecutionException, Ti } } - Assert.assertTrue("No other colorable light found", anotherColorableLightId != null); + assertTrue(anotherColorableLightId != null, "No other colorable light found"); CachedUnitRegistryRemote.shutdown(); CachedUnitRegistryRemote.prepare(); diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/BatteryRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/BatteryRemoteTest.java index 873d5f51bd..cac67fc2b0 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/BatteryRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/BatteryRemoteTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -37,8 +38,6 @@ import org.openbase.type.domotic.state.BatteryStateType.BatteryState.State; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; -import static org.junit.Assert.assertEquals; - /** * @author Tamino Huxohl */ @@ -50,8 +49,7 @@ public BatteryRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { batteryRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.BATTERY), true, BatteryRemote.class); } @@ -76,17 +74,17 @@ public void testGetBatteryLevel() throws Exception { BatteryState state = BatteryState.newBuilder().setLevel(level).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(batteryRemote.getId()).applyServiceState(state, ServiceType.BATTERY_STATE_SERVICE); batteryRemote.requestData().get(); - assertEquals("The getter for the battery level returns the wrong value!", state.getLevel(), batteryRemote.getBatteryState().getLevel(), 0.001); - assertEquals("The battery state has not been updated according to the level!", BatteryState.State.OK, batteryRemote.getData().getBatteryState().getValue()); + assertEquals(state.getLevel(), batteryRemote.getBatteryState().getLevel(), 0.001, "The getter for the battery level returns the wrong value!"); + assertEquals(BatteryState.State.OK, batteryRemote.getData().getBatteryState().getValue(), "The battery state has not been updated according to the level!"); BatteryState lastState = batteryRemote.getBatteryState(); level = 0.095d; state = BatteryState.newBuilder().setLevel(level).setValue(State.CRITICAL).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(batteryRemote.getId()).applyServiceState(state, ServiceType.BATTERY_STATE_SERVICE); batteryRemote.requestData().get(); - assertEquals("The getter for the battery level returns the wrong value!", state.getLevel(), batteryRemote.getBatteryState().getLevel(), 0.001); - assertEquals("The battery state value has not been updated correctly!", state.getValue(), batteryRemote.getData().getBatteryState().getValue()); - assertEquals("The last battery state has not been updated correctly!", lastState, batteryRemote.getData().getBatteryStateLast()); + assertEquals(state.getLevel(), batteryRemote.getBatteryState().getLevel(), 0.001, "The getter for the battery level returns the wrong value!"); + assertEquals(state.getValue(), batteryRemote.getData().getBatteryState().getValue(), "The battery state value has not been updated correctly!"); + assertEquals(lastState, batteryRemote.getData().getBatteryStateLast(), "The last battery state has not been updated correctly!"); } catch (Exception ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LoggerFactory.getLogger(BatteryRemoteTest.class)); } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ButtonRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ButtonRemoteTest.java index da35deae9e..f8beaf00d2 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ButtonRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ButtonRemoteTest.java @@ -21,7 +21,7 @@ * . * #L% */ - +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -38,8 +38,6 @@ import org.openbase.type.domotic.state.ButtonStateType.ButtonState.State; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; -import static org.junit.Assert.*; - /** * @author Tamino Huxohl */ @@ -51,18 +49,10 @@ public ButtonRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { buttonRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.BUTTON), true, ButtonRemote.class); } - /** - * Test of notifyUpdated method, of class ButtonRemote. - */ - @Disabled - public void testNotifyUpdated() { - } - /** * Test of getButtonState method, of class ButtonRemote. * @@ -79,8 +69,8 @@ public void testGetButtonState() throws Exception { .get(buttonRemote.getId()) .applyServiceState(buttonState, ServiceType.BUTTON_STATE_SERVICE); buttonRemote.requestData().get(); - assertEquals("The getter for the button returns the wrong value!", buttonState.getValue(), controllerButtonState.getValue()); - assertEquals("The getter for the button returns the wrong value!", buttonState.getValue(), buttonRemote.getButtonState().getValue()); + assertEquals(buttonState.getValue(), controllerButtonState.getValue(), "The getter for the button returns the wrong value!"); + assertEquals(buttonState.getValue(), buttonRemote.getButtonState().getValue(), "The getter for the button returns the wrong value!"); } /** @@ -100,9 +90,9 @@ public void testGetButtonStateTimestamp() throws Exception { deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(buttonRemote.getId()).applyServiceState(buttonState, ServiceType.BUTTON_STATE_SERVICE); stopwatch.stop(); buttonRemote.requestData().get(); - assertEquals("The getter for the button returns the wrong value!", buttonState.getValue(), buttonRemote.getButtonState().getValue()); + assertEquals(buttonState.getValue(), buttonRemote.getButtonState().getValue(), "The getter for the button returns the wrong value!"); timestamp = TimestampJavaTimeTransform.transform(Services.getLatestValueOccurrence(State.DOUBLE_PRESSED, buttonRemote.getButtonState())); - assertTrue("The timestamp of the button state has not been updated!", (timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime())); + assertTrue((timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime()), "The timestamp of the button state has not been updated!"); // just to be safe that the next test does not set the motion state in the same millisecond Thread.sleep(1); @@ -112,9 +102,9 @@ public void testGetButtonStateTimestamp() throws Exception { deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(buttonRemote.getId()).applyServiceState(buttonState, ServiceType.BUTTON_STATE_SERVICE); stopwatch.stop(); buttonRemote.requestData().get(); - assertEquals("The getter for the button returns the wrong value!", buttonState.getValue(), buttonRemote.getButtonState().getValue()); + assertEquals(buttonState.getValue(), buttonRemote.getButtonState().getValue(), "The getter for the button returns the wrong value!"); timestamp = TimestampJavaTimeTransform.transform(Services.getLatestValueOccurrence(State.PRESSED, buttonRemote.getButtonState())); - assertTrue("The timestamp of the button state has not been updated!", (timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime())); + assertTrue((timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime()), "The timestamp of the button state has not been updated!"); // just to be safe that the next test does not set the motion state in the same millisecond Thread.sleep(1); @@ -124,8 +114,8 @@ public void testGetButtonStateTimestamp() throws Exception { deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(buttonRemote.getId()).applyServiceState(buttonState, ServiceType.BUTTON_STATE_SERVICE); stopwatch.stop(); buttonRemote.requestData().get(); - assertEquals("The getter for the button returns the wrong value!", buttonState.getValue(), buttonRemote.getButtonState().getValue()); + assertEquals(buttonState.getValue(), buttonRemote.getButtonState().getValue(), "The getter for the button returns the wrong value!"); timestamp = TimestampJavaTimeTransform.transform(Services.getLatestValueOccurrence(State.PRESSED, buttonRemote.getButtonState())); - assertFalse("The timestamp of the button state has been updated even though it should not!", (timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime())); + assertFalse((timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime()), "The timestamp of the button state has been updated even though it should not!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteTest.java index 9a709a8b54..4fc969bdd2 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; import org.junit.jupiter.api.Test; import org.openbase.bco.authentication.lib.SessionManager; @@ -35,6 +35,8 @@ import org.openbase.bco.dal.test.AbstractBCODeviceManagerTest; import org.openbase.bco.registry.mock.MockRegistry; import org.openbase.jps.core.JPService; +import org.openbase.jps.preset.JPDebugMode; +import org.openbase.jps.preset.JPLogLevel; import org.openbase.jul.communication.jp.JPComLegacyMode; import org.openbase.jul.exception.CouldNotPerformException; import org.openbase.jul.exception.InitializationException; @@ -55,7 +57,7 @@ import java.util.concurrent.ExecutionException; -import static org.junit.Assert.assertEquals; + /** * @author Tamino Huxohl @@ -66,40 +68,26 @@ public class ColorableLightRemoteTest extends AbstractBCODeviceManagerTest { private static ColorableLightRemote colorableLightRemote; - public ColorableLightRemoteTest() { - } - - @BeforeAll - public static void setUpClass() throws Throwable { - + @Override + public void setupTestProperties() { // legacy mode needed for testLegacyRemoteCallGetColor() test. JPService.registerProperty(JPComLegacyMode.class, true); - + System.out.println("called"); // enable to get debug logging - // JPService.registerProperty(JPDebugMode.class, true); - // JPService.registerProperty(JPLogLevel.class, LogLevel.DEBUG); +// JPService.registerProperty(JPDebugMode.class, true); +// JPService.registerProperty(JPLogLevel.class, LogLevel.DEBUG); + } - AbstractBCODeviceManagerTest.setUpClass(); + @BeforeAll + public static void loadUnits() throws Throwable { colorableLightRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.COLORABLE_LIGHT), true, ColorableLightRemote.class); } @AfterAll - public static void tearDownClass() throws Throwable { - AbstractBCODeviceManagerTest.tearDownClass(); - + public static void tearDownTest() throws Throwable { JPService.registerProperty(JPComLegacyMode.class, false); } - @BeforeEach - public void setUp() throws InitializationException, InvalidStateException { - - } - - @AfterEach - public void tearDown() throws CouldNotPerformException { - - } - /** * Test of setColor method, of class ColorableLightRemote. * @@ -111,7 +99,7 @@ public void testSetColor_Color() throws Exception { System.out.println("setColor"); HSBColor color = HSBColor.newBuilder().setBrightness(0.50).setSaturation(0.70).setHue(150).build(); waitForExecution(colorableLightRemote.setColor(color)); - assertEquals("Color has not been set in time!", color, colorableLightRemote.getData().getColorState().getColor().getHsbColor()); + assertEquals(color, colorableLightRemote.getData().getColorState().getColor().getHsbColor(), "Color has not been set in time!"); } /** @@ -119,7 +107,6 @@ public void testSetColor_Color() throws Exception { * * @throws Exception if an error occurs */ - @Disabled @Test @Timeout(15) public void testControllingViaLightRemote() throws Exception { @@ -175,7 +162,7 @@ public void testSetColor_HSBColor() throws Exception { System.out.println("setColor"); HSBColor color = HSBColor.newBuilder().setHue(50).setSaturation(0.50).setBrightness(0.50).build(); waitForExecution(colorableLightRemote.setColor(color)); - assertEquals("Color has not been set in time!", color, colorableLightRemote.getHSBColor()); + assertEquals(color, colorableLightRemote.getHSBColor(), "Color has not been set in time!"); } /** @@ -192,13 +179,13 @@ public void testSetColor_InvalidHSBColor() throws Exception { HSBColor color = HSBColor.newBuilder().setHue(370).setSaturation(0.3d).setBrightness(0.8d).build(); try { colorableLightRemote.setColor(color).get(); - Assert.assertTrue("Exception does not occur if invalid service state is set!", false); + assertTrue(false, "Exception does not occur if invalid service state is set!"); } catch (ExecutionException ex) { // should occur! } - Assert.assertNotEquals("Invalid hue color has been applied!", color.getHue(), colorableLightRemote.getHSBColor().getHue()); - Assert.assertNotEquals("Parts of an invalid color has been applied!", color.getSaturation(), colorableLightRemote.getHSBColor().getSaturation()); - Assert.assertNotEquals("Parts of an invalid color has been applied!", color.getBrightness(), colorableLightRemote.getHSBColor().getBrightness()); + assertNotEquals(color.getHue(), colorableLightRemote.getHSBColor().getHue(), "Invalid hue color has been applied!"); + assertNotEquals(color.getSaturation(), colorableLightRemote.getHSBColor().getSaturation(), "Parts of an invalid color has been applied!"); + assertNotEquals(color.getBrightness(), colorableLightRemote.getHSBColor().getBrightness(), "Parts of an invalid color has been applied!"); colorableLightRemote.requestData().get(); for (ActionDescription actionDescription : colorableLightRemote.getActionList()) { @@ -210,7 +197,7 @@ public void testSetColor_InvalidHSBColor() throws Exception { // validate if done final RemoteAction remoteAction = new RemoteAction(actionDescription); - Assert.assertTrue(remoteAction + " is not done!", remoteAction.isDone()); + assertTrue(remoteAction.isDone(), remoteAction + " is not done!"); } } @@ -225,38 +212,7 @@ public void testRemoteGetColor() throws Exception { System.out.println("getColor"); HSBColor color = HSBColor.newBuilder().setHue(66).setSaturation(0.63).setBrightness(0.33).build(); waitForExecution(colorableLightRemote.setColor(color)); - assertEquals("Color has not been set in time or the return value from the getter is different!", color, colorableLightRemote.getHSBColor()); - } - - /** - * Test of getColor method, of class ColorableLightRemote. - * - * @throws java.lang.Exception - */ - @Test - @Timeout(10) - public void testLegacyRemoteCallGetColor() throws Exception { - System.out.println("getColor"); - HSBColor color = HSBColor.newBuilder().setHue(61).setSaturation(0.23).setBrightness(0.37).build(); - final RemoteAction action = waitForExecution(colorableLightRemote.setColor(color)); - ColorState colorResult = colorableLightRemote.callMethodAsync("getColorState", ColorState.class) - .get() - .getResponse(); - assertEquals("Color has not been set in time or the return value from the getter is different!", color, colorResult.getColor().getHsbColor()); - - // cancel manual action - action.cancel().get(); - colorableLightRemote.requestData().get(); - for (ActionDescription actionDescription : colorableLightRemote.getActionList()) { - - // filter termination action - if (actionDescription.getPriority() == Priority.TERMINATION) { - continue; - } - - final RemoteAction remoteAction = new RemoteAction(actionDescription); - Assert.assertTrue(remoteAction + " is not done!", remoteAction.isDone()); - } + assertEquals(color, colorableLightRemote.getHSBColor(), "Color has not been set in time or the return value from the getter is different!"); } /** @@ -270,7 +226,7 @@ public void testSetPowerState() throws Exception { System.out.println("setPowerState"); PowerState state = PowerState.newBuilder().setValue(PowerState.State.ON).build(); waitForExecution(colorableLightRemote.setPowerState(state)); - assertEquals("Power state has not been set in time!", state.getValue(), colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(state.getValue(), colorableLightRemote.getData().getPowerState().getValue(), "Power state has not been set in time!"); } /** @@ -284,7 +240,7 @@ public void testGetPowerState() throws Exception { System.out.println("getPowerState"); PowerState state = PowerState.newBuilder().setValue(PowerState.State.OFF).build(); waitForExecution(colorableLightRemote.setPowerState(state)); - assertEquals("Power state has not been set in time or the return value from the getter is different!", state.getValue(), colorableLightRemote.getPowerState().getValue()); + assertEquals(state.getValue(), colorableLightRemote.getPowerState().getValue(), "Power state has not been set in time or the return value from the getter is different!"); } /** @@ -299,7 +255,7 @@ public void testSetBrightness() throws Exception { Double brightness = 0.75d; BrightnessState brightnessState = BrightnessState.newBuilder().setBrightness(brightness).build(); waitForExecution(colorableLightRemote.setBrightnessState(brightnessState)); - assertEquals("Brightness has not been set in time!", brightness, colorableLightRemote.getHSBColor().getBrightness(), 0.001); + assertEquals(brightness, colorableLightRemote.getHSBColor().getBrightness(), 0.001, "Brightness has not been set in time!"); } /** @@ -314,7 +270,7 @@ public void testGetBrightness() throws Exception { Double brightness = 0.25d; BrightnessState brightnessState = BrightnessState.newBuilder().setBrightness(brightness).build(); waitForExecution(colorableLightRemote.setBrightnessState(brightnessState)); - assertEquals("Brightness has not been set in time or the return value from the getter is different!", brightnessState.getBrightness(), colorableLightRemote.getBrightnessState().getBrightness(), 0.001); + assertEquals(brightnessState.getBrightness(), colorableLightRemote.getBrightnessState().getBrightness(), 0.001, "Brightness has not been set in time or the return value from the getter is different!"); } @Test @@ -322,7 +278,7 @@ public void testGetBrightness() throws Exception { public void testSetNeutralWhite() throws Exception { System.out.println("testSetNeutralWhite"); waitForExecution(colorableLightRemote.setNeutralWhite()); - assertEquals("Neutral white was not set to the default value!", ColorStateOperationService.DEFAULT_NEUTRAL_WHITE, colorableLightRemote.getColorState().getColor().getHsbColor()); + assertEquals(ColorStateOperationService.DEFAULT_NEUTRAL_WHITE, colorableLightRemote.getColorState().getColor().getHsbColor(), "Neutral white was not set to the default value!"); } private int powerStateObserverUpdateNumber = 0; @@ -360,7 +316,7 @@ public void testPowerStateObserver() throws Exception { waitForExecution(colorableLightRemote.setPowerState(PowerState.State.OFF)); // notification 3 waitForExecution(colorableLightRemote.setPowerState(PowerState.State.OFF)); - assertEquals("PowerStateObserver wasn't notified the correct amount of times!", 3, powerStateObserverUpdateNumber); + assertEquals(3, powerStateObserverUpdateNumber, "PowerStateObserver wasn't notified the correct amount of times!"); colorableLightRemote.removeServiceStateObserver(ServiceType.POWER_STATE_SERVICE, powerStateObserver); } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteWithAuthenticationTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteWithAuthenticationTest.java index fd9c8a3265..86eb0d912c 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteWithAuthenticationTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ColorableLightRemoteWithAuthenticationTest.java @@ -21,7 +21,7 @@ * . * #L% */ - +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; import org.openbase.bco.authentication.lib.AuthenticatedServerManager; import org.openbase.bco.authentication.lib.EncryptionHelper; @@ -72,8 +72,6 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.*; - /** * @author Sebastian Fast */ @@ -91,13 +89,12 @@ public ColorableLightRemoteWithAuthenticationTest() { } @BeforeAll - public static void setUpClass() throws Throwable { + public static void registerProperties() throws Throwable { JPService.registerProperty(JPAuthentication.class, true); - AbstractBCODeviceManagerTest.setUpClass(); } @BeforeEach - public void setUp() throws CouldNotPerformException, InterruptedException, ExecutionException { + public void prepareTest() throws CouldNotPerformException, InterruptedException, ExecutionException { adminSessionManager.loginUser(Registries.getUnitRegistry().getUnitConfigByAlias(UnitRegistry.ADMIN_USER_ALIAS).getId(), UserCreationPlugin.ADMIN_PASSWORD, false); @@ -110,7 +107,7 @@ public void setUp() throws CouldNotPerformException, InterruptedException, Execu } @AfterEach - public void tearDown() throws CouldNotPerformException, ExecutionException, InterruptedException { + public void tearDownTest() throws CouldNotPerformException, ExecutionException, InterruptedException { adminSessionManager.logout(); colorableLightRemote.setSessionManager(SessionManager.getInstance()); } @@ -127,7 +124,7 @@ public void testSetColorWithAuthentication() throws Exception { waitForExecution(colorableLightRemote.setPowerState(PowerStateType.PowerState.State.ON), adminToken); colorableLightRemote.requestData().get(); - assertEquals("Power has not been set in time!", PowerStateType.PowerState.State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } /** @@ -185,7 +182,7 @@ public void testSetColorWithClientWithoutAuthentication() throws Exception { System.out.println("execute action"); waitForExecution(colorableLightRemote.setPowerState(PowerStateType.PowerState.State.ON), adminToken); colorableLightRemote.requestData().get(); - assertEquals("Power has not been set in time!", PowerStateType.PowerState.State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } /** @@ -222,7 +219,7 @@ public void testSetColorWithUserWithoutAuthentication() throws Exception { System.out.println("execute action"); waitForExecution(colorableLightRemote.setPowerState(PowerStateType.PowerState.State.ON), adminToken); colorableLightRemote.requestData().get(); - assertEquals("Power has not been set in time!", PowerStateType.PowerState.State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } @Test @@ -268,7 +265,7 @@ public void testApplyActionWithToken() throws Exception { try { ExceptionPrinter.setBeQuit(true); colorableLightRemote.setPowerState(State.ON).get(); - assertTrue("Could set power state without access permissions", false); + assertTrue(false, "Could set power state without access permissions"); } catch (ExecutionException ex) { // this should happen // ExceptionPrinter.printHistory(ex, LOGGER, LogLevel.INFO); @@ -359,7 +356,7 @@ public void testApplyActionViaServiceRemoteWithToken() throws Exception { powerStateServiceRemote.cancelAction(future.get(), largosAuthToken).get(5 , TimeUnit.SECONDS); future = powerStateServiceRemote.setPowerState(Power.OFF, largosDefaultParameter); - final RemoteAction largoOffAction = waitForExecution(future, largosAuthToken); + waitForExecution(future, largosAuthToken); // make sure sync is done powerStateServiceRemote.requestData().get(5 , TimeUnit.SECONDS); diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/DimmableLightRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/DimmableLightRemoteTest.java index f90482870b..07e0b3e8f4 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/DimmableLightRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/DimmableLightRemoteTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -36,8 +37,6 @@ import org.openbase.type.domotic.state.PowerStateType.PowerState; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; -import static org.junit.Assert.assertEquals; - /** * @author Tamino Huxohl */ @@ -49,18 +48,10 @@ public DimmableLightRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { dimmableLightRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.DIMMABLE_LIGHT), true, DimmableLightRemote.class); } - /** - * Test of notifyUpdated method, of class DimmerRemote. - */ - @Disabled - public void testNotifyUpdated() { - } - /** * Test of setPower method, of class DimmerRemote. * @@ -72,7 +63,7 @@ public void testSetPower() throws Exception { System.out.println("setPowerState"); PowerState state = PowerState.newBuilder().setValue(PowerState.State.ON).build(); waitForExecution(dimmableLightRemote.setPowerState(state)); - assertEquals("Power has not been set in time!", state.getValue(), dimmableLightRemote.getData().getPowerState().getValue()); + assertEquals(state.getValue(), dimmableLightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } /** @@ -86,7 +77,7 @@ public void testGetPower() throws Exception { System.out.println("getPowerState"); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(dimmableLightRemote.getId()).applyServiceState(Power.ON, ServiceType.POWER_STATE_SERVICE); dimmableLightRemote.requestData().get(); - assertEquals("Power has not been set in time!", Power.ON.getValue(), dimmableLightRemote.getPowerState().getValue()); + assertEquals(Power.ON.getValue(), dimmableLightRemote.getPowerState().getValue(), "Power has not been set in time!"); } /** @@ -101,7 +92,7 @@ public void testSetBrightness() throws Exception { Double brightness = 0.66d; BrightnessState brightnessState = BrightnessState.newBuilder().setBrightness(brightness).build(); waitForExecution(dimmableLightRemote.setBrightnessState(brightnessState)); - assertEquals("Brightness has not been set in time!", brightness, dimmableLightRemote.getBrightnessState().getBrightness(), 0.001); + assertEquals(brightness, dimmableLightRemote.getBrightnessState().getBrightness(), 0.001, "Brightness has not been set in time!"); } /** @@ -118,6 +109,6 @@ public void testGetBrightness() throws Exception { final BrightnessState brightnessState = BrightnessState.newBuilder().setBrightness(brightness).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(dimmableLightRemote.getId()).applyServiceState(brightnessState, ServiceType.BRIGHTNESS_STATE_SERVICE); dimmableLightRemote.requestData().get(); - assertEquals("Brightness has not been set in time!", brightnessState.getBrightness(), dimmableLightRemote.getBrightnessState().getBrightness(), 0.001); + assertEquals(brightnessState.getBrightness(), dimmableLightRemote.getBrightnessState().getBrightness(), 0.001, "Brightness has not been set in time!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/HandleRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/HandleRemoteTest.java index 17e695e488..7f465bac8d 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/HandleRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/HandleRemoteTest.java @@ -21,7 +21,7 @@ * . * #L% */ -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -46,8 +46,7 @@ public HandleRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { handleRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.HANDLE), true, HandleRemote.class); } @@ -70,6 +69,6 @@ public void testGetRotaryHandleState() throws Exception { HandleState handlestate =HandleState.newBuilder().setPosition(90).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(handleRemote.getId()).applyServiceState(handlestate, ServiceType.HANDLE_STATE_SERVICE); handleRemote.requestData().get(); - Assert.assertEquals("The getter for the handle state returns the wrong value!", handlestate.getPosition(), handleRemote.getHandleState().getPosition()); + assertEquals(handlestate.getPosition(), handleRemote.getHandleState().getPosition(), "The getter for the handle state returns the wrong value!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightRemoteTest.java index 49e7895b39..2735000efe 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightRemoteTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -33,8 +34,6 @@ import org.openbase.type.domotic.service.ServiceTemplateType.ServiceTemplate.ServiceType; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; -import static org.junit.Assert.assertEquals; - /** * @author Tamino Huxohl */ @@ -46,8 +45,7 @@ public LightRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { lightRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.LIGHT), true, LightRemote.class); } @@ -61,7 +59,7 @@ public static void setUpClass() throws Throwable { public void testSetPowerState() throws Exception { System.out.println("setPowerState"); waitForExecution(lightRemote.setPowerState(Power.ON)); - assertEquals("Power has not been set in time!", Power.ON.getValue(), lightRemote.getData().getPowerState().getValue()); + assertEquals(Power.ON.getValue(), lightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } /** @@ -81,7 +79,7 @@ public void testGetPowerState() throws Exception { lightRemote.requestData().get(); // validate service state - assertEquals("Light has not been set in time!", Power.OFF.getValue(), lightRemote.getPowerState().getValue()); + assertEquals(Power.OFF.getValue(), lightRemote.getPowerState().getValue(), "Light has not been set in time!"); // apply service state deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(lightRemote.getId()).applyServiceState(Power.ON, ServiceType.POWER_STATE_SERVICE); @@ -90,6 +88,6 @@ public void testGetPowerState() throws Exception { lightRemote.requestData().get(); // validate service state - assertEquals("Light has not been set in time!", Power.ON.getValue(), lightRemote.getPowerState().getValue()); + assertEquals(Power.ON.getValue(), lightRemote.getPowerState().getValue(), "Light has not been set in time!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightSensorRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightSensorRemoteTest.java index 024bab0e24..cfcda0a10f 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightSensorRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/LightSensorRemoteTest.java @@ -21,8 +21,8 @@ * . * #L% */ -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -46,8 +46,7 @@ public LightSensorRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { lightSensorRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.LIGHT_SENSOR), true, LightSensorRemote.class); } @@ -64,6 +63,6 @@ public void testGetIlluminance() throws Exception { IlluminanceState illuminanceState = IlluminanceState.newBuilder().setIlluminance(illuminance).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(lightSensorRemote.getId()).applyServiceState(illuminanceState, ServiceType.ILLUMINANCE_STATE_SERVICE); lightSensorRemote.requestData().get(); - assertEquals("The getter for the illuminance returns the wrong value!", illuminanceState.getIlluminance(), lightSensorRemote.getIlluminanceState().getIlluminance(), 0.1); + assertEquals(illuminanceState.getIlluminance(), lightSensorRemote.getIlluminanceState().getIlluminance(), 0.1, "The getter for the illuminance returns the wrong value!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/MotionDetectorRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/MotionDetectorRemoteTest.java index 5429b9fc89..e3b9684218 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/MotionDetectorRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/MotionDetectorRemoteTest.java @@ -21,10 +21,7 @@ * . * #L% */ -import org.junit.Assert; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -55,8 +52,7 @@ public MotionDetectorRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { motionDetectorRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.MOTION_DETECTOR), true, MotionDetectorRemote.class); } @@ -73,7 +69,7 @@ public void testGetMotionState() throws Exception { MotionState motion = MotionState.newBuilder().setValue(MotionState.State.MOTION).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(motionDetectorRemote.getId()).applyServiceState(motion, ServiceType.MOTION_STATE_SERVICE); motionDetectorRemote.requestData().get(); - Assert.assertEquals("The getter for the motion state returns the wrong value!", motion.getValue(), motionDetectorRemote.getMotionState().getValue()); + assertEquals(motion.getValue(), motionDetectorRemote.getMotionState().getValue(), "The getter for the motion state returns the wrong value!"); } /** @@ -93,10 +89,10 @@ public void testGetMotionStateTimestamp() throws Exception { deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(motionDetectorRemote.getId()).applyServiceState(motion, ServiceType.MOTION_STATE_SERVICE); stopwatch.stop(); motionDetectorRemote.requestData().get(); - Assert.assertEquals("The getter for the motion state returns the wrong value!", motion.getValue(), motionDetectorRemote.getMotionState().getValue()); + assertEquals(motion.getValue(), motionDetectorRemote.getMotionState().getValue(), "The getter for the motion state returns the wrong value!"); timestamp = TimestampJavaTimeTransform.transform(Services.getLatestValueOccurrence(State.MOTION, motionDetectorRemote.getMotionState())); String comparision = "Timestamp: " + timestamp + ", interval: [" + stopwatch.getStartTime() + ", " + stopwatch.getEndTime() + "]"; - assertTrue("The last motion timestamp has not been updated! " + comparision, (timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime())); + assertTrue((timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime()), "The last motion timestamp has not been updated! " + comparision); // just to be safe that the next test does not set the motion state in the same millisecond Thread.sleep(1); @@ -106,9 +102,9 @@ public void testGetMotionStateTimestamp() throws Exception { deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(motionDetectorRemote.getId()).applyServiceState(motion, ServiceType.MOTION_STATE_SERVICE); stopwatch.stop(); motionDetectorRemote.requestData().get(); - Assert.assertEquals("The getter for the motion state returns the wrong value!", motion.getValue(), motionDetectorRemote.getMotionState().getValue()); + assertEquals(motion.getValue(), motionDetectorRemote.getMotionState().getValue(), "The getter for the motion state returns the wrong value!"); timestamp = TimestampJavaTimeTransform.transform(Services.getLatestValueOccurrence(State.MOTION, motionDetectorRemote.getMotionState())); comparision = "Timestamp: " + timestamp + ", interval: [" + stopwatch.getStartTime() + ", " + stopwatch.getEndTime() + "]"; - assertFalse("The last motion timestamp has been updated even though it sould not! " + comparision, (timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime())); + assertFalse((timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime()), "The last motion timestamp has been updated even though it sould not! " + comparision); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerConsumptionSensorRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerConsumptionSensorRemoteTest.java index 9e8540c992..3ffec027a1 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerConsumptionSensorRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerConsumptionSensorRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -46,8 +46,7 @@ public PowerConsumptionSensorRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { powerConsumptionRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.POWER_CONSUMPTION_SENSOR), true, PowerConsumptionSensorRemote.class); } @@ -74,8 +73,8 @@ public void testGetPowerConsumption() throws Exception { PowerConsumptionState state = PowerConsumptionState.newBuilder().setConsumption(consumption).setCurrent(current).setVoltage(voltage).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(powerConsumptionRemote.getId()).applyServiceState(state, ServiceType.POWER_CONSUMPTION_STATE_SERVICE); powerConsumptionRemote.requestData().get(); - Assert.assertEquals("The getter for the power consumption returns the wrong voltage value!", state.getVoltage(), powerConsumptionRemote.getPowerConsumptionState().getVoltage(), 0.1); - Assert.assertEquals("The getter for the power consumption returns the wrong consumption value!", state.getConsumption(), powerConsumptionRemote.getPowerConsumptionState().getConsumption(), 0.1); - Assert.assertEquals("The getter for the power consumption returns the wrong current value!", state.getCurrent(), powerConsumptionRemote.getPowerConsumptionState().getCurrent(), 0.1); + assertEquals(state.getVoltage(), powerConsumptionRemote.getPowerConsumptionState().getVoltage(), 0.1, "The getter for the power consumption returns the wrong voltage value!"); + assertEquals(state.getConsumption(), powerConsumptionRemote.getPowerConsumptionState().getConsumption(), 0.1, "The getter for the power consumption returns the wrong consumption value!"); + assertEquals(state.getCurrent(), powerConsumptionRemote.getPowerConsumptionState().getCurrent(), 0.1, "The getter for the power consumption returns the wrong current value!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerSwitchRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerSwitchRemoteTest.java index 1f32e138c0..1f4267e6eb 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerSwitchRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/PowerSwitchRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -49,8 +49,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.*; - /** * @author Tamino Huxohl */ @@ -62,8 +60,7 @@ public PowerSwitchRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { powerSwitchRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.POWER_SWITCH), true, PowerSwitchRemote.class); } @@ -76,7 +73,7 @@ public static void setUpClass() throws Throwable { @Timeout(3) public void testSetPowerState() throws Exception { waitForExecution(powerSwitchRemote.setPowerState(Power.ON)); - assertEquals("Power state has not been set in time!", Power.ON.getValue(), powerSwitchRemote.getData().getPowerState().getValue()); + assertEquals(Power.ON.getValue(), powerSwitchRemote.getData().getPowerState().getValue(), "Power state has not been set in time!"); } /** @@ -95,7 +92,7 @@ public void testGetPowerState() throws Exception { powerSwitchRemote.requestData().get(); // validate service state - assertEquals("Switch has not been set in time.", Power.OFF.getValue(), powerSwitchRemote.getPowerState().getValue()); + assertEquals(Power.OFF.getValue(), powerSwitchRemote.getPowerState().getValue(), "Switch has not been set in time."); // apply service state unitController.applyServiceState(Power.ON, ServiceType.POWER_STATE_SERVICE); @@ -104,7 +101,7 @@ public void testGetPowerState() throws Exception { powerSwitchRemote.requestData().get(); // validate service state - assertEquals("Switch has not been set in time.", Power.ON.getValue(), powerSwitchRemote.getPowerState().getValue()); + assertEquals(Power.ON.getValue(), powerSwitchRemote.getPowerState().getValue(), "Switch has not been set in time."); } /** @@ -136,7 +133,7 @@ public void testPowerStateServicePerformance() throws Exception { try { powerSwitchRemote.requestData().get(1, TimeUnit.SECONDS); } catch (TimeoutException ex) { - assertTrue("PowerSwitch did not response in time after massive load!", true); + assertTrue(true, "PowerSwitch did not response in time after massive load!"); } // invert state @@ -147,7 +144,7 @@ public void testPowerStateServicePerformance() throws Exception { try { testAction.waitForActionState(State.EXECUTING); } catch (CancellationException ex) { - Assert.fail("Power action is not executing and instead: "+testAction.getActionState().name()); + fail("Power action is not executing and instead: "+testAction.getActionState().name()); } // make sure the final state is correctly applied. @@ -215,13 +212,13 @@ public void testPowerStateServiceCancellationPerformance() throws Exception { } // analyse errors - assertEquals("Some errors occurred during cancellation!", Collections.EMPTY_LIST, errorList); + assertEquals(Collections.EMPTY_LIST, errorList, "Some errors occurred during cancellation!"); // make sure unit is still responding try { powerSwitchRemote.requestData().get(1, TimeUnit.SECONDS); } catch (TimeoutException ex) { - assertTrue("PowerSwitch did not response in time after massive load!", true); + assertTrue(true, "PowerSwitch did not response in time after massive load!"); } // wait until all actions are canceled diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ReedContactRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ReedContactRemoteTest.java index e40aa7fd09..afb7fc6eee 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ReedContactRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/ReedContactRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -46,18 +46,10 @@ public ReedContactRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { reedContactRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.REED_CONTACT), true, ReedContactRemote.class); } - /** - * Test of notifyUpdated method, of class ReedSwitchRemote. - */ - @Disabled - public void testNotifyUpdated() { - } - /** * Test of getReedSwitchState method, of class ReedSwitchRemote. * @@ -70,6 +62,6 @@ public void testGetReedSwitchState() throws Exception { ContactState state = ContactState.newBuilder().setValue(ContactState.State.OPEN).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(reedContactRemote.getId()).applyServiceState(state, ServiceType.CONTACT_STATE_SERVICE); reedContactRemote.requestData().get(); - Assert.assertEquals("The getter for the reed switch state returns the wrong value!", state.getValue(), reedContactRemote.getContactState().getValue()); + assertEquals(state.getValue(), reedContactRemote.getContactState().getValue(), "The getter for the reed switch state returns the wrong value!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/RollerShutterRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/RollerShutterRemoteTest.java index 842dac1e84..c7de28b788 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/RollerShutterRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/RollerShutterRemoteTest.java @@ -22,8 +22,8 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.dal.remote.layer.unit.RollerShutterRemote; @@ -35,7 +35,7 @@ import org.openbase.type.domotic.state.BlindStateType.BlindState.State; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; -import static org.junit.Assert.assertEquals; + /** * @author Tamino Huxohl @@ -48,8 +48,7 @@ public RollerShutterRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void loadUnits() throws Throwable { rollerShutterRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.ROLLER_SHUTTER), true, RollerShutterRemote.class); } @@ -64,7 +63,7 @@ public void testSetShutterState() throws Exception { System.out.println("setShutterState"); BlindState state = BlindState.newBuilder().setValue(BlindState.State.DOWN).build(); waitForExecution(rollerShutterRemote.setBlindState(state)); - assertEquals("Shutter movement state has not been set in time!", state.getValue(), rollerShutterRemote.getData().getBlindState().getValue()); + assertEquals(state.getValue(), rollerShutterRemote.getData().getBlindState().getValue(), "Shutter movement state has not been set in time!"); } /** @@ -79,13 +78,6 @@ public void testGetShutterState() throws Exception { final BlindState blindState = BlindState.newBuilder().setValue(State.UP).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(rollerShutterRemote.getId()).applyServiceState(blindState, ServiceType.BLIND_STATE_SERVICE); rollerShutterRemote.requestData().get(); - assertEquals("Shutter has not been set in time!", rollerShutterRemote.getBlindState().getValue(), blindState.getValue()); - } - - /** - * Test of notifyUpdated method, of class RollershutterRemote. - */ - @Disabled - public void testNotifyUpdated() { + assertEquals(rollerShutterRemote.getBlindState().getValue(), blindState.getValue(), "Shutter has not been set in time!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/SmokeDetectorRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/SmokeDetectorRemoteTest.java index c0a5f05928..591e8bd937 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/SmokeDetectorRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/SmokeDetectorRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -47,8 +47,7 @@ public SmokeDetectorRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void setupTest() throws Throwable { smokeDetectorRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.SMOKE_DETECTOR), true, SmokeDetectorRemote.class); } @@ -73,7 +72,7 @@ public void testGetSmokeAlarmState() throws Exception { AlarmState alarmState = AlarmState.newBuilder().setValue(AlarmState.State.ALARM).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(smokeDetectorRemote.getId()).applyServiceState(alarmState, ServiceType.SMOKE_ALARM_STATE_SERVICE); smokeDetectorRemote.requestData().get(); - Assert.assertEquals("The getter for the smoke alarm state returns the wrong value!", alarmState.getValue(), smokeDetectorRemote.getSmokeAlarmState().getValue()); + assertEquals(alarmState.getValue(), smokeDetectorRemote.getSmokeAlarmState().getValue(), "The getter for the smoke alarm state returns the wrong value!"); } /** @@ -88,7 +87,7 @@ public void testGetSmokeState() throws Exception { SmokeState smokeState = SmokeState.newBuilder().setValue(SmokeState.State.SOME_SMOKE).setSmokeLevel(0.13d).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(smokeDetectorRemote.getId()).applyServiceState(smokeState, ServiceType.SMOKE_STATE_SERVICE); smokeDetectorRemote.requestData().get(); - Assert.assertEquals("The getter for the smoke state returns the wrong value!", smokeState.getValue(), smokeDetectorRemote.getSmokeState().getValue()); + assertEquals(smokeState.getValue(), smokeDetectorRemote.getSmokeState().getValue(), "The getter for the smoke state returns the wrong value!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TamperDetectorRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TamperDetectorRemoteTest.java index 660b71d7d6..a790a3011f 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TamperDetectorRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TamperDetectorRemoteTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -38,8 +39,6 @@ import org.openbase.type.domotic.state.TamperStateType.TamperState.State; import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; -import static org.junit.Assert.*; - /** * @author Tamino Huxohl */ @@ -51,8 +50,7 @@ public TamperDetectorRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void setupTest() throws Throwable { tamperDetectorRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.TAMPER_DETECTOR), true, TamperDetectorRemote.class); } @@ -75,7 +73,7 @@ public void testGetTamperState() throws Exception { TamperState tamperState = TamperState.newBuilder().setValue(TamperState.State.TAMPER).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(tamperDetectorRemote.getId()).applyServiceState(tamperState, ServiceType.TAMPER_STATE_SERVICE); tamperDetectorRemote.requestData().get(); - assertEquals("The getter for the tamper switch state returns the wrong value!", tamperState.getValue(), tamperDetectorRemote.getTamperState().getValue()); + assertEquals(tamperState.getValue(), tamperDetectorRemote.getTamperState().getValue(), "The getter for the tamper switch state returns the wrong value!"); } /** @@ -95,10 +93,10 @@ public void testGetTamperStateTimestamp() throws Exception { deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(tamperDetectorRemote.getId()).applyServiceState(tamperState, ServiceType.TAMPER_STATE_SERVICE); stopwatch.stop(); tamperDetectorRemote.requestData().get(); - assertEquals("The getter for the tamper switch state returns the wrong value!", tamperState.getValue(), tamperDetectorRemote.getTamperState().getValue()); + assertEquals(tamperState.getValue(), tamperDetectorRemote.getTamperState().getValue(), "The getter for the tamper switch state returns the wrong value!"); timestamp = TimestampJavaTimeTransform.transform(Services.getLatestValueOccurrence(State.TAMPER, tamperDetectorRemote.getTamperState())); String comparision = "Timestamp: " + timestamp + ", interval: [" + stopwatch.getStartTime() + ", " + stopwatch.getEndTime() + "]"; - assertTrue("The last detection timestamp has not been updated! " + comparision, (timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime())); + assertTrue((timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime()), "The last detection timestamp has not been updated! " + comparision); // just to be safe that the next test does not set the motion state in the same millisecond Thread.sleep(1); @@ -108,9 +106,9 @@ public void testGetTamperStateTimestamp() throws Exception { deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(tamperDetectorRemote.getId()).applyServiceState(tamperState, ServiceType.TAMPER_STATE_SERVICE); stopwatch.stop(); tamperDetectorRemote.requestData().get(); - assertEquals("The getter for the tamper switch state returns the wrong value!", tamperState.getValue(), tamperDetectorRemote.getTamperState().getValue()); + assertEquals(tamperState.getValue(), tamperDetectorRemote.getTamperState().getValue(), "The getter for the tamper switch state returns the wrong value!"); timestamp = TimestampJavaTimeTransform.transform(Services.getLatestValueOccurrence(State.TAMPER, tamperDetectorRemote.getTamperState())); comparision = "Timestamp: " + timestamp + ", interval: [" + stopwatch.getStartTime() + ", " + stopwatch.getEndTime() + "]"; - assertFalse("The last detection timestamp has been updated even though it should not! " + comparision, (timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime())); + assertFalse((timestamp >= stopwatch.getStartTime() && timestamp <= stopwatch.getEndTime()), "The last detection timestamp has been updated even though it should not! " + comparision); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureControllerRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureControllerRemoteTest.java index c4e6bfc6c1..27b1649ca3 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureControllerRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureControllerRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -45,8 +45,7 @@ public TemperatureControllerRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void setupTest() throws Throwable { temperatureControllerRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.TEMPERATURE_CONTROLLER), true, TemperatureControllerRemote.class); } @@ -63,7 +62,7 @@ public void testSetTargetTemperature() throws Exception { TemperatureState temperatureState = TemperatureState.newBuilder().setTemperature(temperature).build(); waitForExecution(temperatureControllerRemote.setTargetTemperatureState(temperatureState)); temperatureControllerRemote.requestData().get(); - Assert.assertEquals("The getter for the target temperature returns the wrong value!", temperature, temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 0.1); + assertEquals(temperature, temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 0.1, "The getter for the target temperature returns the wrong value!"); } /** @@ -80,7 +79,7 @@ public void testGetTargetTemperature() throws Exception { final TemperatureState temperatureState = TemperatureState.newBuilder().setTemperature(temperature).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(temperatureControllerRemote.getId()).applyServiceState(temperatureState, ServiceType.TARGET_TEMPERATURE_STATE_SERVICE); temperatureControllerRemote.requestData().get(); - Assert.assertEquals("The getter for the target temperature returns the wrong value!", temperatureState.getTemperature(), temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 0.1); + assertEquals(temperatureState.getTemperature(), temperatureControllerRemote.getTargetTemperatureState().getTemperature(), 0.1, "The getter for the target temperature returns the wrong value!"); } /** @@ -96,6 +95,6 @@ public void testGetTemperature() throws Exception { TemperatureState temperatureState = TemperatureState.newBuilder().setTemperature(temperature).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(temperatureControllerRemote.getId()).applyServiceState(temperatureState, ServiceType.TEMPERATURE_STATE_SERVICE); temperatureControllerRemote.requestData().get(); - Assert.assertEquals("The getter for the temperature returns the wrong value!", temperature, temperatureControllerRemote.getTemperatureState().getTemperature(), 0.1); + assertEquals(temperature, temperatureControllerRemote.getTemperatureState().getTemperature(), 0.1, "The getter for the temperature returns the wrong value!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureSensorRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureSensorRemoteTest.java index 5968e036ca..a364dbac5a 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureSensorRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/TemperatureSensorRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -47,8 +47,7 @@ public TemperatureSensorRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCODeviceManagerTest.setUpClass(); + public static void setupTest() throws Throwable { temperatureSensorRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.TEMPERATURE_SENSOR), true, TemperatureSensorRemote.class); } @@ -71,7 +70,7 @@ public void testGetTemperature() throws Exception { double temperature = 37.0F; deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(temperatureSensorRemote.getId()).applyServiceState(TemperatureState.newBuilder().setTemperature(temperature), ServiceType.TEMPERATURE_STATE_SERVICE); temperatureSensorRemote.requestData().get(); - Assert.assertEquals("The getter for the temperature returns the wrong value!", temperature, temperatureSensorRemote.getTemperatureState().getTemperature(), 0.1); + assertEquals(temperature, temperatureSensorRemote.getTemperatureState().getTemperature(), 0.1, "The getter for the temperature returns the wrong value!"); } /** @@ -87,6 +86,6 @@ public void testGetTemperatureAlarmState() throws Exception { AlarmState alarmState = AlarmState.newBuilder().setValue(AlarmState.State.ALARM).build(); deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().get(temperatureSensorRemote.getId()).applyServiceState(alarmState, ServiceType.TEMPERATURE_ALARM_STATE_SERVICE); temperatureSensorRemote.requestData().get(); - Assert.assertEquals("The getter for the temperature alarm state returns the wrong value!", alarmState.getValue(), temperatureSensorRemote.getTemperatureAlarmState().getValue()); + assertEquals(alarmState.getValue(), temperatureSensorRemote.getTemperatureAlarmState().getValue(), "The getter for the temperature alarm state returns the wrong value!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitAllocationTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitAllocationTest.java index 99c96a351b..173818c565 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitAllocationTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitAllocationTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; import org.openbase.bco.authentication.lib.SessionManager; import org.openbase.bco.authentication.lib.future.AuthenticatedValueFuture; @@ -65,8 +66,6 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.*; - /** * @author Tamino Huxohl */ @@ -92,9 +91,6 @@ public static void setUpClass() throws Throwable { // JPService.registerProperty(JPDebugMode.class, true); // JPService.registerProperty(JPLogLevel.class, LogLevel.DEBUG); - // trigger super method - AbstractBCODeviceManagerTest.setUpClass(); - // retrieve colorable light remote colorableLightRemote = Units.getUnitByAlias(MockRegistry.getUnitAlias(UnitType.COLORABLE_LIGHT), true, ColorableLightRemote.class); @@ -103,14 +99,8 @@ public static void setUpClass() throws Throwable { // new Thread(() -> BCOActionInspector.main(args)).start(); } - @AfterAll - public static void tearDownClass() throws Throwable { - AbstractBCODeviceManagerTest.tearDownClass(); - } - - @BeforeEach - public void setUp() throws Exception { + public void loginUser() throws Exception { sessionManager.loginUser(Registries.getUnitRegistry().getUnitConfigByAlias(UnitRegistry.ADMIN_USER_ALIAS).getId(), UserCreationPlugin.ADMIN_PASSWORD, false); if (adminToken == null) { @@ -119,7 +109,7 @@ public void setUp() throws Exception { } @AfterEach - public void tearDown() { + public void logoutUser() { sessionManager.logout(); } @@ -152,13 +142,13 @@ public void testActionStateNotifications() throws Exception { remoteAction.waitForActionState(ActionState.State.EXECUTING); // validate that the action is available from unit data - assertTrue("Unit data does not contain any action descriptions", colorableLightRemote.getData().getActionCount() > 0); + assertTrue(colorableLightRemote.getData().getActionCount() > 0, "Unit data does not contain any action descriptions"); // validate the initiator of the action - assertEquals("Unexpected action initiator", SessionManager.getInstance().getUserClientPair().getClientId(), remoteAction.getActionDescription().getActionInitiator().getInitiatorId()); + assertEquals(SessionManager.getInstance().getUserClientPair().getClientId(), remoteAction.getActionDescription().getActionInitiator().getInitiatorId(), "Unexpected action initiator"); // validate that the action is currently executing - assertEquals("ActionState is not executing", ActionState.State.EXECUTING, remoteAction.getActionState()); + assertEquals(ActionState.State.EXECUTING, remoteAction.getActionState(), "ActionState is not executing"); // validate that the power state is set - assertEquals("PowerState has not been updated", State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getData().getPowerState().getValue(), "PowerState has not been updated"); // cancel the action System.out.println("try to cancel"); @@ -169,13 +159,13 @@ public void testActionStateNotifications() throws Exception { colorableLightRemote.requestData().get(); // validate that the action is cancelled - assertEquals("ActionState is not canceled", ActionState.State.CANCELED, remoteAction.getActionState()); + assertEquals(ActionState.State.CANCELED, remoteAction.getActionState(), "ActionState is not canceled"); // validate state order actionStateObserver.validateActionStates(remoteAction.getActionId()); // validate that all states were notified - assertEquals("Not all action states have been notified", actionStates.length, actionStateObserver.getReceivedActionStateCounter(remoteAction.getActionId())); + assertEquals(actionStates.length, actionStateObserver.getReceivedActionStateCounter(remoteAction.getActionId()), "Not all action states have been notified"); // remove the action state observer colorableLightRemote.removeDataObserver(actionStateObserver); @@ -240,7 +230,7 @@ public int getReceivedActionStateCounter(final String actionId) { void validateActionStates(final String actionId) { synchronized (actionIdStateMapLock) { - assertEquals("Unexpected action state order.", StringProcessor.transformCollectionToString(Arrays.asList(actionStates), ", "), StringProcessor.transformCollectionToString(actionIdStateMap.get(actionId), ", ")); + assertEquals(StringProcessor.transformCollectionToString(Arrays.asList(actionStates), ", "), StringProcessor.transformCollectionToString(actionIdStateMap.get(actionId), ", "), "Unexpected action state order."); } } } @@ -372,8 +362,8 @@ public void testPriorityHandling() throws Exception { primaryActionParameter.getActionInitiatorBuilder().setInitiatorId(sessionManager.getUserClientPair().getUserId()); primaryActionParameter.getActionInitiatorBuilder().setInitiatorType(InitiatorType.SYSTEM); final ActionDescription actionDescription = ActionDescriptionProcessor.generateActionDescriptionBuilder(primaryActionParameter).build(); - assertTrue("initiator type not set.", actionDescription.getActionInitiator().hasInitiatorType()); - assertEquals("initiator type not correct.", InitiatorType.SYSTEM, actionDescription.getActionInitiator().getInitiatorType()); + assertTrue(actionDescription.getActionInitiator().hasInitiatorType(), "initiator type not set."); + assertEquals(InitiatorType.SYSTEM, actionDescription.getActionInitiator().getInitiatorType(), "initiator type not correct."); AuthenticatedValue authenticatedValue = sessionManager.initializeRequest(actionDescription, null); @@ -506,13 +496,13 @@ public void testActionExtension() throws Exception { // validate that power value was set assertEquals(State.ON, colorableLightRemote.getPowerState().getValue()); - assertEquals("last extension time was not initialized with the action creation time!", actionToExtend.getCreationTime(), actionToExtend.getLastExtensionTime()); + assertEquals(actionToExtend.getCreationTime(), actionToExtend.getLastExtensionTime(), "last extension time was not initialized with the action creation time!"); // make sure this works when using quantum computing Thread.sleep(1); actionToExtend.extend(); actionToExtend.waitForExtension(); - assertNotEquals("last extension time was not updated!", actionToExtend.getCreationTime(), actionToExtend.getLastExtensionTime()); + assertNotEquals(actionToExtend.getCreationTime(), actionToExtend.getLastExtensionTime(), "last extension time was not updated!"); // cancel remaining action for the next test actionToExtend.cancel().get(); diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitDataFilteredObservableTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitDataFilteredObservableTest.java index a91225a7e9..67c180f536 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitDataFilteredObservableTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/UnitDataFilteredObservableTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.openbase.bco.dal.lib.layer.unit.UnitDataFilteredObservable; import org.openbase.bco.registry.mock.MockRegistry; @@ -55,65 +55,65 @@ public void testRequestedTempusObservation() throws Exception { builder.getPowerStateRequestedBuilder().setValue(PowerStateType.PowerState.State.ON); observable.notifyObservers(builder.build()); - Assert.assertEquals(1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size()); builder.getBrightnessStateBuilder().setBrightness(100); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the current brightness state triggered requested observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the current brightness state triggered requested observable"); builder.addActionBuilder().getDescriptionBuilder().addEntryBuilder().setKey("en").setValue("ActionDescription"); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the action list triggered requested state observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the action list triggered requested state observable"); builder.getPowerStateBuilder().setValue(PowerStateType.PowerState.State.OFF); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the current power state triggered requested state observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the current power state triggered requested state observable"); builder.addAlias("test"); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the aliases triggered requested state observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the aliases triggered requested state observable"); builder.getPowerStateLastBuilder().setValue(PowerStateType.PowerState.State.ON); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the last power state triggered requested state observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the last power state triggered requested state observable"); builder.getBrightnessStateLastBuilder().setBrightness(50); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the last brightness state triggered requested state observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the last brightness state triggered requested state observable"); builder.setTransactionId(10); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the transaction id triggered requested state observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the transaction id triggered requested state observable"); builder.setId("testID"); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the id triggered requested state observable", 1, observer.getEvents().size()); + assertEquals(1, observer.getEvents().size(), "Changes to the id triggered requested state observable"); builder.getBrightnessStateRequestedBuilder().setBrightness(30); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the requested brightness state did not trigger the requested state observable", 2, observer.getEvents().size()); + assertEquals(2, observer.getEvents().size(), "Changes to the requested brightness state did not trigger the requested state observable"); builder.getBrightnessStateRequestedBuilder().setBrightness(30); observable.notifyObservers(builder.build()); - Assert.assertEquals("The same requested brightness state is notified twice", 2, observer.getEvents().size()); + assertEquals(2, observer.getEvents().size(), "The same requested brightness state is notified twice"); PowerStateType.PowerState.Builder powerStateRequestedBuilder = builder.getPowerStateRequestedBuilder(); powerStateRequestedBuilder.addLastValueOccurrenceBuilder().setKey(PowerStateType.PowerState.State.OFF).setValue(TimestampProcessor.getCurrentTimestamp()); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the latest value occurrence did not trigger the requested state observable", 3, observer.getEvents().size()); + assertEquals(3, observer.getEvents().size(), "Changes to the latest value occurrence did not trigger the requested state observable"); powerStateRequestedBuilder.addAggregatedValueCoverageBuilder().setKey(PowerStateType.PowerState.State.ON).setCoverage(0.5); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the aggregated value coverage triggered the requested state observable", 3, observer.getEvents().size()); + assertEquals(3, observer.getEvents().size(), "Changes to the aggregated value coverage triggered the requested state observable"); powerStateRequestedBuilder.setTimestamp(TimestampProcessor.getCurrentTimestamp()); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the timestamp did not trigger the requested state observable", 4, observer.getEvents().size()); + assertEquals(4, observer.getEvents().size(), "Changes to the timestamp did not trigger the requested state observable"); powerStateRequestedBuilder.getResponsibleActionBuilder().setActionId("actionId"); observable.notifyObservers(builder.build()); - Assert.assertEquals("Changes to the responsible action did not trigger the requested state observable", 5, observer.getEvents().size()); + assertEquals(5, observer.getEvents().size(), "Changes to the responsible action did not trigger the requested state observable"); } private UnitDataFilteredObservable createObservable(final ServiceTempus serviceTempus) throws CouldNotPerformException { diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/connection/ConnectionRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/connection/ConnectionRemoteTest.java index e6ccd8ed14..33111975f8 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/connection/ConnectionRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/connection/ConnectionRemoteTest.java @@ -48,14 +48,9 @@ public class ConnectionRemoteTest extends AbstractBCOLocationManagerTest { private static ConnectionRemote connectionRemote; - public ConnectionRemoteTest() { - } - @BeforeAll - public static void setUpClass() throws Throwable { + public static void loadUnits() throws Throwable { try { - AbstractBCOLocationManagerTest.setUpClass(); - connectionRemote = Units.getUnit(Registries.getUnitRegistry().getUnitConfigsByUnitType(UnitType.CONNECTION).get(0), true, ConnectionRemote.class); connectionRemote.waitForConnectionState(ConnectionState.State.CONNECTED); } catch (Throwable ex) { @@ -63,15 +58,6 @@ public static void setUpClass() throws Throwable { } } - @BeforeEach - public void setUp() throws InitializationException, InvalidStateException { - - } - - @AfterEach - public void tearDown() throws CouldNotPerformException { - } - /** * Test if changes in unitControllers are published to a connection remote. * @@ -105,7 +91,7 @@ public void tearDown() throws CouldNotPerformException { // System.out.println("current temp: " + connectionRemote.getDoorState().getValue() + " waiting for: " + DoorState.State.CLOSED); // Thread.sleep(10); // } -// Assert.assertEquals("Doorstate of the connection has not been updated!", DoorState.State.CLOSED, connectionRemote.getDoorState().getValue()); +// assertEquals("Doorstate of the connection has not been updated!", DoorState.State.CLOSED, connectionRemote.getDoorState().getValue()); // // ContactState openState = ContactState.newBuilder().setValue(ContactState.State.OPEN).build(); // for (ReedContactController reedContact : reedContactControllerList) { @@ -122,6 +108,6 @@ public void tearDown() throws CouldNotPerformException { // System.out.println("current temp: " + connectionRemote.getDoorState().getValue() + " waiting for: " + DoorState.State.OPEN); // Thread.sleep(10); // } -// Assert.assertEquals("Doorstate of the connection has not been updated!", DoorState.State.OPEN, connectionRemote.getDoorState().getValue()); +// assertEquals("Doorstate of the connection has not been updated!", DoorState.State.OPEN, connectionRemote.getDoorState().getValue()); // } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DalRegisterDeviceTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DalRegisterDeviceTest.java index 799b914bec..e5c9e0672a 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DalRegisterDeviceTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DalRegisterDeviceTest.java @@ -52,8 +52,8 @@ import java.util.List; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.*; /** * @author Divine Threepwood @@ -67,10 +67,6 @@ public class DalRegisterDeviceTest extends AbstractBCODeviceManagerTest { public DalRegisterDeviceTest() { } - @BeforeEach - public void setUp() throws InitializationException, InstantiationException { - } - /** * Test registering a new device while the device test is running. * @@ -98,7 +94,7 @@ public void testRegisterDeviceWhileRunning() throws Exception { // test if the state of the light can be changed waitForExecution(colorableLightRemote.setPowerState(PowerState.State.ON)); - assertEquals("Power state has not been set in time!", PowerState.State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(PowerState.State.ON, colorableLightRemote.getData().getPowerState().getValue(), "Power state has not been set in time!"); // add the previously removed unit template config again deviceClassBuilder = deviceClass.toBuilder(); @@ -124,8 +120,8 @@ public void testRegisterDeviceWhileRunning() throws Exception { // test if both unit remotes can be used final RemoteAction action = waitForExecution(powerSwitchRemote.setPowerState(State.ON)); waitForExecution(colorableLightRemote.setPowerState(PowerState.State.OFF)); - assertEquals("Power state has not been set in time!", PowerState.State.ON, powerSwitchRemote.getData().getPowerState().getValue()); - assertEquals("Power state has not been set in time!", PowerState.State.OFF, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(PowerState.State.ON, powerSwitchRemote.getData().getPowerState().getValue(), "Power state has not been set in time!"); + assertEquals(PowerState.State.OFF, colorableLightRemote.getData().getPowerState().getValue(), "Power state has not been set in time!"); // cancel action because cancellation is not possible afterwards action.cancel().get(); @@ -141,28 +137,28 @@ public void testRegisterDeviceWhileRunning() throws Exception { while (Registries.getUnitRegistry().getUnitConfigById(deviceUnitConfig.getId()).getDeviceConfig().getUnitIdCount() != deviceClass.getUnitTemplateConfigCount() && (System.currentTimeMillis() - currentTime) < 500) { Thread.sleep(10); } - assertTrue("Unit registry still contains the unit config which should have been removed", !Registries.getUnitRegistry().containsUnitConfigById(powerSwitchConfig.getId())); + assertFalse(Registries.getUnitRegistry().containsUnitConfigById(powerSwitchConfig.getId()), "Unit registry still contains the unit config which should have been removed"); // wait up to half a second for the unit controller to be removed from the device test currentTime = System.currentTimeMillis(); while (deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().contains(powerSwitchConfig.getId()) && (System.currentTimeMillis() - currentTime) < 500) { Thread.sleep(10); } - assertTrue("DeviceManager still contains removed unit controller", !deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().contains(powerSwitchConfig.getId())); + assertTrue(!deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().contains(powerSwitchConfig.getId()), "DeviceManager still contains removed unit controller"); // test if the colorable light can still be used waitForExecution(colorableLightRemote.setPowerState(PowerState.State.OFF)); - assertEquals("Power state has not been set in time!", PowerState.State.OFF, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(PowerState.State.OFF, colorableLightRemote.getData().getPowerState().getValue(), "Power state has not been set in time!"); // test if the power switch remote has lost its connection powerSwitchRemote.waitForConnectionState(ConnectionState.State.DISCONNECTED, 1000); - assertEquals("Remote has not disconnected even though its config should have been removed!", ConnectionState.State.DISCONNECTED, powerSwitchRemote.getConnectionState()); + assertEquals(ConnectionState.State.DISCONNECTED, powerSwitchRemote.getConnectionState(), "Remote has not disconnected even though its config should have been removed!"); } private boolean running = true; @Test - @Timeout(6) + @Timeout(10) public void testRegisteringManyDevices() throws Exception { System.out.println("testRegisteringManyDevices"); @@ -210,7 +206,7 @@ public void testRegisteringManyDevices() throws Exception { String serialNumber = productNumber + "-" + i; System.out.println("Register device"); final UnitConfig deviceUnitConfig = Registries.getUnitRegistry().registerUnitConfig(MockRegistry.generateDeviceConfig(deviceConfigLabel + "_" + i, serialNumber, deviceClass)).get(); - assertTrue("DeviceUnitConfig[" + LabelProcessor.getBestMatch(deviceUnitConfig.getLabel()) + "] is not available after registration!", Registries.getUnitRegistry().containsUnitConfigById(deviceUnitConfig.getId())); + assertTrue(Registries.getUnitRegistry().containsUnitConfigById(deviceUnitConfig.getId()), "DeviceUnitConfig[" + LabelProcessor.getBestMatch(deviceUnitConfig.getLabel()) + "] is not available after registration!"); final UnitConfig colorableLightConfig1 = Registries.getUnitRegistry().getUnitConfigById(deviceUnitConfig.getDeviceConfig().getUnitId(0)); final UnitConfig colorableLightConfig2 = Registries.getUnitRegistry().getUnitConfigById(deviceUnitConfig.getDeviceConfig().getUnitId(1)); final UnitConfig powerSwitchConfig = Registries.getUnitRegistry().getUnitConfigById(deviceUnitConfig.getDeviceConfig().getUnitId(2)); @@ -244,9 +240,9 @@ public void testRegisteringManyDevices() throws Exception { waitForExecution(colorableLightRemote2.setPowerState(PowerState.State.OFF)); System.out.println("SetPowerState3"); waitForExecution(powerSwitchRemote.setPowerState(PowerState.State.ON)); - assertEquals("Power state has not been set in time!", PowerState.State.ON, colorableLightRemote1.getData().getPowerState().getValue()); - assertEquals("Power state has not been set in time!", PowerState.State.OFF, colorableLightRemote2.getData().getPowerState().getValue()); - assertEquals("Power state has not been set in time!", PowerState.State.ON, powerSwitchRemote.getData().getPowerState().getValue()); + assertEquals(PowerState.State.ON, colorableLightRemote1.getData().getPowerState().getValue(), "Power state has not been set in time!"); + assertEquals(PowerState.State.OFF, colorableLightRemote2.getData().getPowerState().getValue(), "Power state has not been set in time!"); + assertEquals(PowerState.State.ON, powerSwitchRemote.getData().getPowerState().getValue(), "Power state has not been set in time!"); } } catch (CouldNotPerformException | ExecutionException | InterruptedException ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DeviceManagerLauncherTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DeviceManagerLauncherTest.java index 7a3a1c12d7..14b1e1cfba 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DeviceManagerLauncherTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/device/DeviceManagerLauncherTest.java @@ -39,23 +39,6 @@ public class DeviceManagerLauncherTest extends AbstractBCOTest { private static final Logger LOGGER = LoggerFactory.getLogger(DeviceManagerLauncherTest.class); - public DeviceManagerLauncherTest() { - } - - @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCOTest.setUpClass(); - } - - @AfterAll - public static void tearDownClass() throws Throwable { - AbstractBCOTest.tearDownClass(); - } - - @BeforeEach - public void setUp() throws InitializationException, org.openbase.jul.exception.InstantiationException { - } - /** * Test of deactivate method, of class DeviceManagerLauncher. * diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/AbstractBCOLocationManagerTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/AbstractBCOLocationManagerTest.java index 4c0e4c6ef8..ee7c1fd551 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/AbstractBCOLocationManagerTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/AbstractBCOLocationManagerTest.java @@ -47,10 +47,8 @@ public class AbstractBCOLocationManagerTest extends AbstractBCOTest { protected static UserManagerLauncher userManagerLauncher; @BeforeAll - public static void setUpClass() throws Throwable { + public static void setupLocationManager() throws Throwable { try { - AbstractBCOTest.setUpClass(); - deviceManagerLauncher = new DeviceManagerLauncher(); deviceManagerLauncher.launch().get(); @@ -65,7 +63,7 @@ public static void setUpClass() throws Throwable { } @AfterAll - public static void tearDownClass() throws Throwable { + public static void tearDownLocationManager() throws Throwable { try { if (userManagerLauncher != null) { userManagerLauncher.shutdown(); @@ -76,7 +74,6 @@ public static void tearDownClass() throws Throwable { if (locationManagerLauncher != null) { locationManagerLauncher.shutdown(); } - AbstractBCOTest.tearDownClass(); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, log); } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/LocationRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/LocationRemoteTest.java index 8eaa0fd0e3..47c5146091 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/LocationRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/LocationRemoteTest.java @@ -23,7 +23,7 @@ */ import com.google.protobuf.Message; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -82,8 +82,6 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.*; - /** * @author Tamino Huxohl */ @@ -97,9 +95,8 @@ public LocationRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { + public static void loadUnits() throws Throwable { try { - AbstractBCOLocationManagerTest.setUpClass(); rootLocationRemote = Units.getUnit(Registries.getUnitRegistry().getRootLocationConfig(), true, Units.LOCATION); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); @@ -134,12 +131,12 @@ public void testLocationToUnitPipeline() throws Exception { waitForExecution(rootLocationRemote.setPowerState(powerOn)); for (PowerStateOperationService powerStateService : powerServiceList) { - assertEquals("PowerState of unit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the locationRemote!", powerOn.getValue(), powerStateService.getPowerState().getValue()); + assertEquals(powerOn.getValue(), powerStateService.getPowerState().getValue(), "PowerState of unit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the locationRemote!"); } waitForExecution(rootLocationRemote.setPowerState(powerOff)); for (PowerStateOperationService powerStateService : powerServiceList) { - assertEquals("PowerState of unit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the locationRemote!", powerOff.getValue(), powerStateService.getPowerState().getValue()); + assertEquals(powerOff.getValue(), powerStateService.getPowerState().getValue(), "PowerState of unit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the locationRemote!"); } } catch (CouldNotPerformException | InterruptedException ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); @@ -199,12 +196,12 @@ public void testUnitToLocationPipeline() throws Exception { System.out.println("current temp: " + rootLocationRemote.getTemperatureState().getTemperature() + " waiting for: " + temperature); Thread.sleep(10); } - assertEquals("Temperature of the location has not been updated!", temperature, rootLocationRemote.getTemperatureState().getTemperature(), 0.01); + assertEquals(temperature, rootLocationRemote.getTemperatureState().getTemperature(), 0.01, "Temperature of the location has not been updated!"); while (rootLocationRemote.getTargetTemperatureState().getTemperature() != targetTemperature) { System.out.println("current target temp: " + rootLocationRemote.getTargetTemperatureState().getTemperature() + " waiting for: " + targetTemperature); Thread.sleep(10); } - assertEquals("TargetTemperature of the location has not been updated!", targetTemperature, rootLocationRemote.getTargetTemperatureState().getTemperature(), 0.01); + assertEquals(targetTemperature, rootLocationRemote.getTargetTemperatureState().getTemperature(), 0.01, "TargetTemperature of the location has not been updated!"); System.out.println("PowerConsumptionSensors: " + powerConsumptionSensorList.size()); PowerConsumptionState powerConsumptionState = PowerConsumptionState.newBuilder().setVoltage(240).setConsumption(10).setCurrent(1).build(); @@ -217,9 +214,9 @@ public void testUnitToLocationPipeline() throws Exception { System.out.println("Waiting for locationRemote powerConsumptionState update!"); Thread.sleep(10); } - assertEquals("Voltage of location has not been updated!", powerConsumptionState.getVoltage(), rootLocationRemote.getPowerConsumptionState().getVoltage(), 0.01); - assertEquals("Current of location has not been updated!", powerConsumptionState.getCurrent(), rootLocationRemote.getPowerConsumptionState().getCurrent(), 0.01); - assertEquals("Consumption of location has not been updated!", powerConsumptionState.getConsumption() * powerConsumptionSensorList.size(), rootLocationRemote.getPowerConsumptionState().getConsumption(), 0.01); + assertEquals(powerConsumptionState.getVoltage(), rootLocationRemote.getPowerConsumptionState().getVoltage(), 0.01, "Voltage of location has not been updated!"); + assertEquals(powerConsumptionState.getCurrent(), rootLocationRemote.getPowerConsumptionState().getCurrent(), 0.01, "Current of location has not been updated!"); + assertEquals(powerConsumptionState.getConsumption() * powerConsumptionSensorList.size(), rootLocationRemote.getPowerConsumptionState().getConsumption(), 0.01, "Consumption of location has not been updated!"); } @Test @@ -258,10 +255,10 @@ public void testRecordAndRestoreSnapshots() throws Exception { waitForExecution(rootLocationRemote.setPowerState(newPowerState)); waitForExecution(rootLocationRemote.setTargetTemperatureState(newTemperatureState)); - assertTrue("BlindState of location has not changed!", rootLocationRemote.getBlindState(UnitType.UNKNOWN).getValue() != snapshotBlindState.getValue()); - assertTrue("ColorState of location has not changed!", !rootLocationRemote.getColorState(UnitType.UNKNOWN).getColor().getHsbColor().equals(snapshotColorState.getColor().getHsbColor())); - assertTrue("PowerState of location has not changed!", rootLocationRemote.getPowerState(UnitType.UNKNOWN).getValue() != snapshotPowerState.getValue()); - assertTrue("TargetTemperatureState of location has not changed!", rootLocationRemote.getTargetTemperatureState(UnitType.UNKNOWN).getTemperature() != snapshotTemperatureState.getTemperature()); + assertTrue(rootLocationRemote.getBlindState(UnitType.UNKNOWN).getValue() != snapshotBlindState.getValue(), "BlindState of location has not changed!"); + assertTrue(!rootLocationRemote.getColorState(UnitType.UNKNOWN).getColor().getHsbColor().equals(snapshotColorState.getColor().getHsbColor()), "ColorState of location has not changed!"); + assertTrue(rootLocationRemote.getPowerState(UnitType.UNKNOWN).getValue() != snapshotPowerState.getValue(), "PowerState of location has not changed!"); + assertTrue(rootLocationRemote.getTargetTemperatureState(UnitType.UNKNOWN).getTemperature() != snapshotTemperatureState.getTemperature(), "TargetTemperatureState of location has not changed!"); logger.info("Restore snapshot"); @@ -285,10 +282,10 @@ public void testRecordAndRestoreSnapshots() throws Exception { return targetTemperature == data.getTargetTemperatureState().getTemperature(); }); - assertEquals("BlindState of location has not been restored through snapshot!", snapshotBlindState.getValue(), rootLocationRemote.getBlindState(UnitType.UNKNOWN).getValue()); - assertEquals("ColorState of location has not been restored through snapshot!", snapshotColorState.getColor().getHsbColor(), rootLocationRemote.getColorState(UnitType.UNKNOWN).getColor().getHsbColor()); - assertEquals("PowerState of location has not been restored through snapshot!", snapshotPowerState.getValue(), rootLocationRemote.getPowerState(UnitType.UNKNOWN).getValue()); - assertEquals("TargetTemperatureState of location has not been restored through snapshot!", snapshotTemperatureState.getTemperature(), rootLocationRemote.getTargetTemperatureState(UnitType.UNKNOWN).getTemperature(), 0.5); + assertEquals(snapshotBlindState.getValue(), rootLocationRemote.getBlindState(UnitType.UNKNOWN).getValue(), "BlindState of location has not been restored through snapshot!"); + assertEquals(snapshotColorState.getColor().getHsbColor(), rootLocationRemote.getColorState(UnitType.UNKNOWN).getColor().getHsbColor(), "ColorState of location has not been restored through snapshot!"); + assertEquals(snapshotPowerState.getValue(), rootLocationRemote.getPowerState(UnitType.UNKNOWN).getValue(), "PowerState of location has not been restored through snapshot!"); + assertEquals(snapshotTemperatureState.getTemperature(), rootLocationRemote.getTargetTemperatureState(UnitType.UNKNOWN).getTemperature(), 0.5, "TargetTemperatureState of location has not been restored through snapshot!"); } @Test @@ -299,9 +296,9 @@ public void testManipulatingByUnitType() throws Exception { try { List lightTypes = Registries.getTemplateRegistry().getSubUnitTypes(UnitType.LIGHT); lightTypes.add(UnitType.LIGHT); - assertTrue("UnitType not found as subType of LIGHT!", lightTypes.contains(UnitType.LIGHT)); - assertTrue("UnitType not found as subType of LIGHT!", lightTypes.contains(UnitType.DIMMABLE_LIGHT)); - assertTrue("UnitType not found as subType of LIGHT!", lightTypes.contains(UnitType.COLORABLE_LIGHT)); + assertTrue(lightTypes.contains(UnitType.LIGHT), "UnitType not found as subType of LIGHT!"); + assertTrue(lightTypes.contains(UnitType.DIMMABLE_LIGHT), "UnitType not found as subType of LIGHT!"); + assertTrue(lightTypes.contains(UnitType.COLORABLE_LIGHT), "UnitType not found as subType of LIGHT!"); List powerServiceList = new ArrayList<>(); for (UnitConfig dalUnitConfig : Registries.getUnitRegistry().getDalUnitConfigs()) { @@ -320,12 +317,12 @@ public void testManipulatingByUnitType() throws Exception { waitForExecution(rootLocationRemote.setPowerState(powerOn, UnitType.LIGHT)); for (PowerStateOperationService powerStateService : powerServiceList) { - assertEquals("PowerState of lightUnit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the loationRemote!", powerOn.getValue(), powerStateService.getPowerState().getValue()); + assertEquals(powerOn.getValue(), powerStateService.getPowerState().getValue(), "PowerState of lightUnit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the loationRemote!"); } waitForExecution(rootLocationRemote.setPowerState(powerOff)); for (PowerStateOperationService powerStateService : powerServiceList) { - assertEquals("PowerState of lightUnit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the loationRemote!", powerOff.getValue(), powerStateService.getPowerState().getValue()); + assertEquals(powerOff.getValue(), powerStateService.getPowerState().getValue(), "PowerState of lightUnit [" + ((UnitController) powerStateService).getLabel() + "] has not been updated by the loationRemote!"); } for (PowerStateOperationService powerStateOperationService : powerServiceList) { @@ -335,7 +332,7 @@ public void testManipulatingByUnitType() throws Exception { System.out.println("Waiting for locationRemote update!"); Thread.sleep(10); } - assertEquals("PowerState of location has not been updated!", powerOn.getValue(), rootLocationRemote.getPowerState(UnitType.LIGHT).getValue()); + assertEquals(powerOn.getValue(), rootLocationRemote.getPowerState(UnitType.LIGHT).getValue(), "PowerState of location has not been updated!"); for (PowerStateOperationService powerStateOperationService : powerServiceList) { powerStateOperationService.setPowerState(powerOff).get(); @@ -345,7 +342,7 @@ public void testManipulatingByUnitType() throws Exception { System.out.println("Waiting for locationRemote update!"); Thread.sleep(10); } - assertEquals("PowerState of location has not been updated!", powerOff.getValue(), rootLocationRemote.getPowerState(UnitType.LIGHT).getValue()); + assertEquals(powerOff.getValue(), rootLocationRemote.getPowerState(UnitType.LIGHT).getValue(), "PowerState of location has not been updated!"); } catch (CouldNotPerformException | InterruptedException | ExecutionException ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); } @@ -370,7 +367,7 @@ public void testPresenceState() throws Exception { } if (motionDetectorController == null) { - Assert.fail("Mock registry does not contain a motionDetector!"); + fail("Mock registry does not contain a motionDetector!"); return; } @@ -380,7 +377,7 @@ public void testPresenceState() throws Exception { System.out.println("Waiting for locationRemote presenceState update!"); Thread.sleep(10); } - assertEquals("PresenceState of location has not been updated!", PresenceState.State.PRESENT, rootLocationRemote.getPresenceState().getValue()); + assertEquals(PresenceState.State.PRESENT, rootLocationRemote.getPresenceState().getValue(), "PresenceState of location has not been updated!"); motionDetectorController.applyServiceState(MotionState.newBuilder().setValue(MotionState.State.NO_MOTION).build(), ServiceType.MOTION_STATE_SERVICE); @@ -389,7 +386,7 @@ public void testPresenceState() throws Exception { System.out.println("Waiting for locationRemote presenceState update!"); Thread.sleep(10); } - assertEquals("PresenceState of location has not been updated!", PresenceState.State.ABSENT, rootLocationRemote.getPresenceState().getValue()); + assertEquals(PresenceState.State.ABSENT, rootLocationRemote.getPresenceState().getValue(), "PresenceState of location has not been updated!"); } catch (CouldNotPerformException ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); } @@ -420,7 +417,7 @@ public void testColorableLightControlViaLocation() throws Exception { // found = true; // } // } -// Assert.assertTrue(colorableLightRemote + " is not included in light list of same loction.", found); +// assertTrue(colorableLightRemote + " is not included in light list of same loction.", found); // } // ==== TEST POWER ON SYNC @@ -431,13 +428,13 @@ public void testColorableLightControlViaLocation() throws Exception { // validate colorable light remote states for (ColorableLightRemote colorableLightRemote : colorableLightRemotes) { colorableLightRemote.requestData().get(); - assertEquals("Power has not been set in time!", State.ON, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, colorableLightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } // validate light remote states for (LightRemote lightRemote : lightRemotes) { lightRemote.requestData().get(); - assertEquals("Power has not been set in time!", State.ON, lightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, lightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } // ==== TEST COLOR SYNC @@ -448,13 +445,13 @@ public void testColorableLightControlViaLocation() throws Exception { // validate at colorable light remote for (ColorableLightRemote colorableLightRemote : colorableLightRemotes) { colorableLightRemote.requestData().get(); - assertEquals("Color has not been set in time!", States.Color.RED.getColor().getHsbColor(), colorableLightRemote.getData().getColorState().getColor().getHsbColor()); + assertEquals(States.Color.RED.getColor().getHsbColor(), colorableLightRemote.getData().getColorState().getColor().getHsbColor(), "Color has not been set in time!"); } // validate light remote states for (LightRemote lightRemote : lightRemotes) { lightRemote.requestData().get(); - assertEquals("Power has not been set in time!", State.ON, lightRemote.getData().getPowerState().getValue()); + assertEquals(State.ON, lightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } // ==== TEST POWER OFF SYNC @@ -465,13 +462,13 @@ public void testColorableLightControlViaLocation() throws Exception { // validate colorable light remote states for (ColorableLightRemote colorableLightRemote : colorableLightRemotes) { colorableLightRemote.requestData().get(); - assertEquals("Power has not been set in time!", State.OFF, colorableLightRemote.getData().getPowerState().getValue()); + assertEquals(State.OFF, colorableLightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } // validate light remote states for (LightRemote lightRemote : lightRemotes) { lightRemote.requestData().get(); - assertEquals("Power has not been set in time!", State.OFF, lightRemote.getData().getPowerState().getValue()); + assertEquals(State.OFF, lightRemote.getData().getPowerState().getValue(), "Power has not been set in time!"); } } @@ -494,7 +491,7 @@ public void testIlluminanceState() throws Exception { } if (lightSensorControllerList.isEmpty()) { - Assert.fail("Mock registry does not contain a lightSensor!"); + fail("Mock registry does not contain a lightSensor!"); return; } @@ -507,7 +504,7 @@ public void testIlluminanceState() throws Exception { System.out.println("Waiting for locationRemote illuminance update!"); Thread.sleep(10); } - assertEquals("IlluminationState of location has not been updated!", illuminance, rootLocationRemote.getIlluminanceState().getIlluminance(), 1.0); + assertEquals(illuminance, rootLocationRemote.getIlluminanceState().getIlluminance(), 1.0, "IlluminationState of location has not been updated!"); illuminance = 10000.0; for (LightSensorController lightSensorController : lightSensorControllerList) { @@ -518,7 +515,7 @@ public void testIlluminanceState() throws Exception { System.out.println("Waiting for locationRemote illuminance update!"); Thread.sleep(10); } - assertEquals("IlluminationState of location has not been updated!", illuminance, rootLocationRemote.getIlluminanceState().getIlluminance(), 1.0); + assertEquals(illuminance, rootLocationRemote.getIlluminanceState().getIlluminance(), 1.0, "IlluminationState of location has not been updated!"); } catch (CouldNotPerformException ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); @@ -565,8 +562,7 @@ public void testActionCancellation() throws Exception { final List colorableLightRemotes = rootLocationRemote.getUnits(UnitType.COLORABLE_LIGHT, false, Units.COLORABLE_LIGHT); // validate that location has at least one unit of the type used in this test - assertTrue("Cannot execute test if location does not have a colorable light!", - colorableLightRemotes.size() > 0); + assertTrue(colorableLightRemotes.size() > 0, "Cannot execute test if location does not have a colorable light!"); for (int i = 0; i < 10; i++) { final PowerState.State powerState = (i % 2 == 0) ? State.ON : State.OFF; @@ -584,7 +580,7 @@ public void testActionCancellation() throws Exception { break; } } - assertTrue("Location action is not running on unit[" + colorableLightRemote + "]", actionRunning); + assertTrue(actionRunning, "Location action is not running on unit[" + colorableLightRemote + "]"); } // cancel the action @@ -607,7 +603,7 @@ public void testActionCancellation() throws Exception { fail("Caused action on unit[" + colorableLightRemote + "]could not be found!"); } - assertEquals("Action on unit[" + colorableLightRemote + "] was not cancelled!", ActionStateType.ActionState.State.CANCELED, causedAction.getActionState().getValue()); + assertEquals(ActionStateType.ActionState.State.CANCELED, causedAction.getActionState().getValue(), "Action on unit[" + colorableLightRemote + "] was not cancelled!"); } } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/scene/SceneRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/scene/SceneRemoteTest.java index 7396be4019..d33ee5cbb6 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/scene/SceneRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/scene/SceneRemoteTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; import org.junit.jupiter.api.Test; import org.openbase.bco.authentication.lib.SessionManager; @@ -89,9 +89,6 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - /** * * @author Tamino Huxohl */ @@ -151,9 +148,8 @@ public SceneRemoteTest() { } @BeforeAll - public static void setUpClass() throws Throwable { + public static void setupSceneTest() throws Throwable { try { - AbstractBCOTest.setUpClass(); //JPService.registerProperty(JPLogLevel.class, LogLevel.DEBUG); JPService.setupJUnitTestMode(); @@ -180,7 +176,7 @@ public static void setUpClass() throws Throwable { } @AfterAll - public static void tearDownClass() throws Throwable { + public static void tearDownSceneTest() throws Throwable { try { if (sceneManagerLauncher != null) { sceneManagerLauncher.shutdown(); @@ -197,8 +193,6 @@ public static void tearDownClass() throws Throwable { if (deviceManagerLauncher != null) { deviceManagerLauncher.shutdown(); } - - AbstractBCOTest.tearDownClass(); } catch (Exception ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); } @@ -406,12 +400,12 @@ public void testTriggerScenePerRemote() throws Exception { powerStateServiceRemote.requestData().get(); colorStateServiceRemote.requestData().get(); - assertEquals("PowerState has not been updated by scene!", POWER_ON, powerStateServiceRemote.getPowerState().getValue()); + assertEquals(POWER_ON, powerStateServiceRemote.getPowerState().getValue(), "PowerState has not been updated by scene!"); // the colorStateServiceRemote computes an average in the rgb space which is why the values have to be compared with a tolerance - assertEquals("Brightness has not been updated by scene!", COLOR_VALUE.getBrightness(), colorStateServiceRemote.getColorState().getColor().getHsbColor().getBrightness(), 0.01); - assertEquals("Hue has not been updated by scene!", COLOR_VALUE.getHue(), colorStateServiceRemote.getColorState().getColor().getHsbColor().getHue(), 0.2); - assertEquals("Saturation has not been updated by scene!", COLOR_VALUE.getSaturation(), colorStateServiceRemote.getColorState().getColor().getHsbColor().getSaturation(), 0.01); + assertEquals(COLOR_VALUE.getBrightness(), colorStateServiceRemote.getColorState().getColor().getHsbColor().getBrightness(), 0.01, "Brightness has not been updated by scene!"); + assertEquals(COLOR_VALUE.getHue(), colorStateServiceRemote.getColorState().getColor().getHsbColor().getHue(), 0.2, "Hue has not been updated by scene!"); + assertEquals(COLOR_VALUE.getSaturation(), colorStateServiceRemote.getColorState().getColor().getHsbColor().getSaturation(), 0.01, "Saturation has not been updated by scene!"); } /** @@ -425,7 +419,7 @@ public void testTriggerSceneWithLocationActionPerRemote() throws Exception { System.out.println("testTriggerSceneWithLocationActionPerRemote"); LocationRemote locationRemote = Units.getUnit(Registries.getUnitRegistry().getRootLocationConfig(), true, LocationRemote.class); - assertTrue("LocationState has the correct temperature to begin with!", locationRemote.getTargetTemperatureState().getTemperature() != TEMPERATURE); + assertTrue(locationRemote.getTargetTemperatureState().getTemperature() != TEMPERATURE, "LocationState has the correct temperature to begin with!"); final SceneRemote sceneRemote = Units.getUnitsByLabel(SCENE_ROOT_LOCATION, true, Units.SCENE).get(0); waitForExecution(sceneRemote.setActivationState(State.ACTIVE)); @@ -436,7 +430,7 @@ public void testTriggerSceneWithLocationActionPerRemote() throws Exception { Thread.sleep(50); } - assertEquals("TemperatureState has not been updated in location by scene!", TEMPERATURE, locationRemote.getTargetTemperatureState().getTemperature(), 0.1); + assertEquals(TEMPERATURE, locationRemote.getTargetTemperatureState().getTemperature(), 0.1, "TemperatureState has not been updated in location by scene!"); } /** @@ -459,7 +453,7 @@ public void testTriggerUnitGroupByScene() throws Exception { waitForExecution(sceneRemote.setActivationState(State.ACTIVE)); for (ColorableLightRemote colorableLightRemote : colorableLightRemotes) { - assertEquals("ColorState has not been set for light[" + colorableLightRemote.getLabel() + "]", GROUP_COLOR_VALUE, colorableLightRemote.getColorState().getColor().getHsbColor()); + assertEquals(GROUP_COLOR_VALUE, colorableLightRemote.getColorState().getColor().getHsbColor(), "ColorState has not been set for light[" + colorableLightRemote.getLabel() + "]"); } while (!(unitGroupRemote.getColorState().getColor().getHsbColor().getBrightness() > GROUP_COLOR_VALUE.getBrightness() - 0.001 && unitGroupRemote.getColorState().getColor().getHsbColor().getBrightness() < GROUP_COLOR_VALUE.getBrightness() + 0.001)) { @@ -469,9 +463,9 @@ public void testTriggerUnitGroupByScene() throws Exception { unitGroupRemote.requestData().get(); // for the group the values can be slightly modified because of computing averages - assertEquals("Brightness in unitGroupRemote has not been set", GROUP_COLOR_VALUE.getBrightness(), unitGroupRemote.getColorState().getColor().getHsbColor().getBrightness(), 0.01); - assertEquals("Hue in unitGroupRemote has not been set", GROUP_COLOR_VALUE.getHue(), unitGroupRemote.getColorState().getColor().getHsbColor().getHue(), 0.01); - assertEquals("Saturation in unitGroupRemote has not been set", GROUP_COLOR_VALUE.getSaturation(), unitGroupRemote.getColorState().getColor().getHsbColor().getSaturation(), 0.01); + assertEquals(GROUP_COLOR_VALUE.getBrightness(), unitGroupRemote.getColorState().getColor().getHsbColor().getBrightness(), 0.01,"Brightness in unitGroupRemote has not been set"); + assertEquals(GROUP_COLOR_VALUE.getHue(), unitGroupRemote.getColorState().getColor().getHsbColor().getHue(), 0.01, "Hue in unitGroupRemote has not been set"); + assertEquals(GROUP_COLOR_VALUE.getSaturation(), unitGroupRemote.getColorState().getColor().getHsbColor().getSaturation(), 0.01, "Saturation in unitGroupRemote has not been set"); } /** @@ -490,16 +484,16 @@ public void testTriggerSceneWithAllDevicesOfLocationActionPerRemoteAndVerifiesUn waitForExecution(internalLight.setPowerState(POWER_ON)); waitForExecution(internalPowerSwitch.setPowerState(POWER_ON)); - assertTrue("internalLight has not switched on!", internalLight.getPowerState().getValue() == POWER_ON); - assertTrue("internalPowerSwitch has not switched on!", internalPowerSwitch.getPowerState().getValue() == POWER_ON); + assertTrue(internalLight.getPowerState().getValue() == POWER_ON, "internalLight has not switched on!"); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_ON, "internalPowerSwitch has not switched on!"); LocationRemote locationRemote = Units.getUnit(Registries.getUnitRegistry().getRootLocationConfig(), true, LocationRemote.class); waitForExecution(locationRemote.setPowerState(POWER_OFF)); internalLight.requestData().get(); internalPowerSwitch.requestData().get(); - assertTrue("internalLight has not switched off!", internalLight.getPowerState().getValue() == POWER_OFF); - assertTrue("internalPowerSwitch has not switched off!", internalPowerSwitch.getPowerState().getValue() == POWER_OFF); + assertTrue(internalLight.getPowerState().getValue() == POWER_OFF, "internalLight has not switched off!"); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_OFF, "internalPowerSwitch has not switched off!"); final SceneRemote sceneRemoteDevicesOn = Units.getUnitsByLabel(SCENE_ROOT_LOCATION_ALL_DEVICES_ON, true, Units.SCENE).get(0); final SceneRemote sceneRemoteDevicesOff = Units.getUnitsByLabel(SCENE_ROOT_LOCATION_ALL_DEVICES_OFF, true, Units.SCENE).get(0); @@ -515,21 +509,21 @@ public void testTriggerSceneWithAllDevicesOfLocationActionPerRemoteAndVerifiesUn waitForExecution(sceneRemoteDevicesOn.setActivationState(State.ACTIVE, SCENE_ACTION_PARAM)); internalLight.requestData().get(); internalPowerSwitch.requestData().get(); - assertTrue("internalLight has not switched on!", internalLight.getPowerState().getValue() == POWER_ON); - assertTrue("internalPowerSwitch has not switched on!", internalPowerSwitch.getPowerState().getValue() == POWER_ON); - assertEquals("Devices on scene is not active", State.ACTIVE, sceneRemoteDevicesOn.getActivationState().getValue()); - assertEquals("Devices off scene is not inactive", State.INACTIVE, sceneRemoteDevicesOff.getActivationState().getValue()); + assertSame(internalLight.getPowerState().getValue(), POWER_ON, "internalLight has not switched on!"); + assertSame(internalPowerSwitch.getPowerState().getValue(), POWER_ON, "internalPowerSwitch has not switched on!"); + assertEquals(State.ACTIVE, sceneRemoteDevicesOn.getActivationState().getValue(), "Devices on scene is not active"); + assertEquals(State.INACTIVE, sceneRemoteDevicesOff.getActivationState().getValue(), "Devices off scene is not inactive"); System.out.println("----------------- set off"); waitForExecution(sceneRemoteDevicesOff.setActivationState(State.ACTIVE, SCENE_ACTION_PARAM)); internalLight.requestData().get(); internalPowerSwitch.requestData().get(); - assertTrue("internalLight has not switched off at interaction "+i, internalLight.getPowerState().getValue() == POWER_OFF); - assertTrue("internalPowerSwitch has not switched off at interaction "+i, internalPowerSwitch.getPowerState().getValue() == POWER_OFF); + assertTrue(internalLight.getPowerState().getValue() == POWER_OFF, "internalLight has not switched off at interaction "+i); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_OFF, "internalPowerSwitch has not switched off at interaction "+i); - assertEquals("Devices off scene is not active at interaction "+i, State.ACTIVE, sceneRemoteDevicesOff.getActivationState().getValue()); - assertEquals("Devices on scene is not inactive at interaction "+i, State.INACTIVE, sceneRemoteDevicesOn.getActivationState().getValue()); + assertEquals(State.ACTIVE, sceneRemoteDevicesOff.getActivationState().getValue(), "Devices off scene is not active at interaction "+i); + assertEquals(State.INACTIVE, sceneRemoteDevicesOn.getActivationState().getValue(), "Devices on scene is not inactive at interaction "+i); System.out.println("=== " + (int) (((double) i / (double) TEST_ITERATIONS) * 100d) + "% passed with iteration " + i + " of location on off test."); } @@ -541,7 +535,7 @@ public void testTriggerSceneWithAllDevicesOfLocationActionPerRemoteAndVerifiesUn * @throws Exception */ @Test - @Timeout(20) + @Timeout(60) public void testTriggerSceneWithLocationActionPerRemoteAndVerifiesUnitModification() throws Exception { System.out.println("testTriggerSceneWithLocationActionPerRemoteAndVerifiesUnitModification"); @@ -553,16 +547,16 @@ public void testTriggerSceneWithLocationActionPerRemoteAndVerifiesUnitModificati internalLight.requestData().get(); internalPowerSwitch.requestData().get(); - assertTrue("internalLight has not switched on!", internalLight.getPowerState().getValue() == POWER_ON); - assertTrue("internalPowerSwitch has not switched on!", internalPowerSwitch.getPowerState().getValue() == POWER_ON); + assertTrue(internalLight.getPowerState().getValue() == POWER_ON, "internalLight has not switched on!"); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_ON, "internalPowerSwitch has not switched on!"); LocationRemote locationRemote = Units.getUnit(Registries.getUnitRegistry().getRootLocationConfig(), true, LocationRemote.class); waitForExecution(locationRemote.setPowerState(POWER_OFF)); internalLight.requestData().get(); internalPowerSwitch.requestData().get(); - assertTrue("internalLight has not switched off!", internalLight.getPowerState().getValue() == POWER_OFF); - assertTrue("internalPowerSwitch has not switched off!", internalPowerSwitch.getPowerState().getValue() == POWER_OFF); + assertTrue(internalLight.getPowerState().getValue() == POWER_OFF, "internalLight has not switched off!"); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_OFF, "internalPowerSwitch has not switched off!"); final SceneRemote sceneRemoteOn = Units.getUnitsByLabel(SCENE_ROOT_LOCATION_ON, true, Units.SCENE).get(0); final SceneRemote sceneRemoteOff = Units.getUnitsByLabel(SCENE_ROOT_LOCATION_OFF, true, Units.SCENE).get(0); @@ -570,7 +564,7 @@ public void testTriggerSceneWithLocationActionPerRemoteAndVerifiesUnitModificati waitForExecution(sceneRemoteOn.setActivationState(State.INACTIVE, SCENE_ACTION_PARAM)); waitForExecution(sceneRemoteOff.setActivationState(State.INACTIVE, SCENE_ACTION_PARAM)); - int TEST_ITERATIONS = 3; + int TEST_ITERATIONS = 20; for (int i = 0; i <= TEST_ITERATIONS; i++) { System.out.println("Current iteration: " + i); @@ -581,10 +575,10 @@ public void testTriggerSceneWithLocationActionPerRemoteAndVerifiesUnitModificati sceneRemoteOn.requestData().get(); sceneRemoteOff.requestData().get(); - assertTrue("internalLight has not switched on!", internalLight.getPowerState().getValue() == POWER_ON); - assertTrue("internalPowerSwitch has not switched on!", internalPowerSwitch.getPowerState().getValue() == POWER_ON); - assertEquals("Location on scene is not active", State.ACTIVE, sceneRemoteOn.getActivationState().getValue()); - assertEquals("Location off scene is not inactive", State.INACTIVE, sceneRemoteOff.getActivationState().getValue()); + assertSame(internalLight.getPowerState().getValue(), POWER_ON, "internalLight has not switched on!"); + assertSame(internalPowerSwitch.getPowerState().getValue(), POWER_ON, "internalPowerSwitch has not switched on!"); + assertEquals(State.ACTIVE, sceneRemoteOn.getActivationState().getValue(), "Location on scene is not active"); + assertEquals(State.INACTIVE, sceneRemoteOff.getActivationState().getValue(), "Location off scene is not inactive"); waitForExecution(sceneRemoteOff.setActivationState(State.ACTIVE, SCENE_ACTION_PARAM)); @@ -593,10 +587,10 @@ public void testTriggerSceneWithLocationActionPerRemoteAndVerifiesUnitModificati sceneRemoteOn.requestData().get(); sceneRemoteOff.requestData().get(); - assertTrue("internalLight has not switched off!", internalLight.getPowerState().getValue() == POWER_OFF); - assertTrue("internalPowerSwitch has not switched off!", internalPowerSwitch.getPowerState().getValue() == POWER_OFF); - assertEquals("Location on scene is not inactive", State.INACTIVE, sceneRemoteOn.getActivationState().getValue()); - assertEquals("Location off scene is not active", State.ACTIVE, sceneRemoteOff.getActivationState().getValue()); + assertTrue(internalLight.getPowerState().getValue() == POWER_OFF, "internalLight has not switched off!"); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_OFF, "internalPowerSwitch has not switched off!"); + assertEquals(State.INACTIVE, sceneRemoteOn.getActivationState().getValue(), "Location on scene is not inactive"); + assertEquals(State.ACTIVE, sceneRemoteOff.getActivationState().getValue(), "Location off scene is not active"); System.out.println("=== " + (int) (((double) i / (double) TEST_ITERATIONS) * 100d) + "% passed with iteration " + i + " of location on off test."); } @@ -621,14 +615,14 @@ public void testIntermediaryActionCancellationOnSceneDeactivation() throws Excep internalLight.requestData().get(); internalPowerSwitch.requestData().get(); - assertTrue("internalLight has not switched on!", internalLight.getPowerState().getValue() == POWER_ON); - assertTrue("internalPowerSwitch has not switched on!", internalPowerSwitch.getPowerState().getValue() == POWER_ON); + assertTrue(internalLight.getPowerState().getValue() == POWER_ON, "internalLight has not switched on!"); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_ON, "internalPowerSwitch has not switched on!"); final SceneRemote sceneRemoteOff = Units.getUnitsByLabel(SCENE_ROOT_LOCATION_OFF, true, Units.SCENE).get(0); final RemoteAction sceneAction = waitForExecution(sceneRemoteOff.setActivationState(State.ACTIVE, SCENE_ACTION_PARAM)); - Assert.assertEquals("Scene action is marked as intermediary one!", false, sceneAction.getActionDescription().getIntermediary()); - Assert.assertNotEquals("Scene did not impact any action!", 0, sceneAction.getActionDescription().getActionImpactList().size()); + assertEquals(false, sceneAction.getActionDescription().getIntermediary(), "Scene action is marked as intermediary one!"); + assertNotEquals(0, sceneAction.getActionDescription().getActionImpactList().size(), "Scene did not impact any action!"); // resolve action impact List actionImpactList = new ArrayList<>(); @@ -642,17 +636,17 @@ public void testIntermediaryActionCancellationOnSceneDeactivation() throws Excep for (RemoteAction actionImpact : actionImpactList) { actionImpact.waitForActionState(ActionState.State.EXECUTING); - Assert.assertEquals("Impacted action not executing!", ActionStateType.ActionState.State.EXECUTING, actionImpact.getActionState()); + assertEquals(ActionStateType.ActionState.State.EXECUTING, actionImpact.getActionState(), "Impacted action not executing!"); } - assertTrue("internalLight has not switched off by scene!", internalLight.getPowerState().getValue() == POWER_OFF); - assertTrue("internalPowerSwitch has not switched off by scene!", internalPowerSwitch.getPowerState().getValue() == POWER_OFF); + assertTrue(internalLight.getPowerState().getValue() == POWER_OFF, "internalLight has not switched off by scene!"); + assertTrue(internalPowerSwitch.getPowerState().getValue() == POWER_OFF, "internalPowerSwitch has not switched off by scene!"); waitForExecution(sceneRemoteOff.setActivationState(State.INACTIVE, SCENE_ACTION_PARAM)); for (RemoteAction actionImpact : actionImpactList) { actionImpact.waitUntilDone(); - Assert.assertEquals("Impacted " + actionImpact + " not canceled!", ActionStateType.ActionState.State.CANCELED, actionImpact.getActionState()); + assertEquals(ActionStateType.ActionState.State.CANCELED, actionImpact.getActionState(), "Impacted " + actionImpact + " not canceled!"); } for (ActionDescriptionType.ActionDescription actionDescription : internalLight.getActionList()) { @@ -663,7 +657,7 @@ public void testIntermediaryActionCancellationOnSceneDeactivation() throws Excep } LOGGER.error("Action on stack: " + actionDescription.getActionState().getValue().name() + " = " + MultiLanguageTextProcessor.getBestMatch(actionDescription.getDescription())); - assertTrue("internalLight has an ongoing action on its stack!", new RemoteAction(actionDescription).isDone()); + assertTrue(new RemoteAction(actionDescription).isDone(), "internalLight has an ongoing action on its stack!"); } for (ActionDescriptionType.ActionDescription actionDescription : internalPowerSwitch.getActionList()) { @@ -674,7 +668,7 @@ public void testIntermediaryActionCancellationOnSceneDeactivation() throws Excep } LOGGER.error("Action on stack: " + actionDescription.getActionState().getValue().name() + " = " + MultiLanguageTextProcessor.getBestMatch(actionDescription.getDescription())); - assertTrue("internalPowerSwitch has an ongoing action on its stack!", new RemoteAction(actionDescription).isDone()); + assertTrue(new RemoteAction(actionDescription).isDone(), "internalPowerSwitch has an ongoing action on its stack!"); } } @@ -703,7 +697,7 @@ public void testActionCancellationViaScene() throws Exception { // validate that all lights are initially off for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light still on!", Power.OFF.getValue(), colorableLight.getPowerState().getValue()); + assertEquals(Power.OFF.getValue(), colorableLight.getPowerState().getValue(), "Light still on!"); } // switch all lights on via another authority @@ -720,26 +714,26 @@ public void testActionCancellationViaScene() throws Exception { adminsColorableLightRemote.shutdown(); } - Assert.assertTrue("Manual color action does not exist!", colorableLightRedRemoteAction != null); - Assert.assertEquals("Manual color action not executing!", ActionState.State.EXECUTING, colorableLightRedRemoteAction.getActionState()); + assertTrue(colorableLightRedRemoteAction != null, "Manual color action does not exist!"); + assertEquals(ActionState.State.EXECUTING, colorableLightRedRemoteAction.getActionState(), "Manual color action not executing!"); // validate cancellation and make sure all lights are RED for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Color not restored!", States.Color.RED.getColor(), colorableLight.getColorState().getColor()); + assertEquals(States.Color.RED.getColor(), colorableLight.getColorState().getColor(), "Color not restored!"); } // switch all off via scene final RemoteAction allOffSceneAction = waitForExecution(allOffScene.setActivationState(Activation.ACTIVE)); - Assert.assertEquals("Manual color action not executing!", ActionState.State.SCHEDULED, colorableLightRedRemoteAction.getActionState()); + assertEquals(ActionState.State.SCHEDULED, colorableLightRedRemoteAction.getActionState(), "Manual color action not executing!"); // validate all off and store responsible action final ArrayList allOffActionDescriptionList = new ArrayList<>(); for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); final PowerState powerState = colorableLight.getPowerState(); - Assert.assertEquals("Light still on!", Power.OFF.getValue(), powerState.getValue()); + assertEquals(Power.OFF.getValue(), powerState.getValue(), "Light still on!"); allOffActionDescriptionList.add(powerState.getResponsibleAction()); } @@ -751,21 +745,21 @@ public void testActionCancellationViaScene() throws Exception { found = true; } } - Assert.assertTrue("Impact not registered!", found); + assertTrue(found, "Impact not registered!"); } - Assert.assertEquals("Manual color action not executing!", ActionState.State.SCHEDULED, colorableLightRedRemoteAction.getActionState()); + assertEquals(ActionState.State.SCHEDULED, colorableLightRedRemoteAction.getActionState(), "Manual color action not executing!"); // cancel all off allOffSceneAction.cancel().get(); colorableLightRedRemoteAction.waitForActionState(ActionState.State.EXECUTING); - Assert.assertEquals("Manual color action not executing!", ActionState.State.EXECUTING, colorableLightRedRemoteAction.getActionState()); + assertEquals(ActionState.State.EXECUTING, colorableLightRedRemoteAction.getActionState(), "Manual color action not executing!"); // validate cancellation and make sure all lights are RED again for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Color not restored! Current action is: "+MultiLanguageTextProcessor.getBestMatch(colorableLight.getColorState().getResponsibleAction().getDescription()) , States.Color.RED.getColor(), colorableLight.getColorState().getColor()); + assertEquals(States.Color.RED.getColor(), colorableLight.getColorState().getColor(), "Color not restored! Current action is: "+MultiLanguageTextProcessor.getBestMatch(colorableLight.getColorState().getResponsibleAction().getDescription())); } session.logout(); } @@ -784,13 +778,13 @@ public void testThatScenesDoNotInterfereEachOther() throws Exception { // validate that all lights are initially off for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light is not off but: "+ MultiLanguageTextProcessor.getBestMatch(colorableLight.getColorState().getResponsibleAction().getDescription(), "?"), Power.OFF.getValue(), colorableLight.getPowerState().getValue()); + assertEquals(Power.OFF.getValue(), colorableLight.getPowerState().getValue(), "Light is not off but: "+ MultiLanguageTextProcessor.getBestMatch(colorableLight.getColorState().getResponsibleAction().getDescription(), "?")); } // validate that the room is initially off Thread.sleep(AGGREGATION_TIME); // let us wait some time to let the aggregation takes place. rootLocationRemote.requestData().get(); - Assert.assertEquals("Room is not off!", Power.OFF.getValue(), rootLocationRemote.getPowerState().getValue()); + assertEquals(Power.OFF.getValue(), rootLocationRemote.getPowerState().getValue(), "Room is not off!"); // activate blue observe(blueSceneRemote.setActivationState(Activation.ACTIVE)).waitForActionState(ActionState.State.EXECUTING); @@ -798,13 +792,13 @@ public void testThatScenesDoNotInterfereEachOther() throws Exception { // validate that all lights are blue for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light is not blue!", Color.BLUE.getColor(), colorableLight.getColorState().getColor()); + assertEquals(Color.BLUE.getColor(), colorableLight.getColorState().getColor(), "Light is not blue!"); } // validate the room is blue Thread.sleep(AGGREGATION_TIME); // let us wait some time to let the aggregation takes place. rootLocationRemote.requestData().get(); - Assert.assertTrue("Scene does not apply its color, expected: " + Color.BLUE.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!", ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.BLUE)); + assertTrue(ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.BLUE), "Scene does not apply its color, expected: " + Color.BLUE.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!"); // activate red observe(redSceneRemote.setActivationState(Activation.ACTIVE)).waitForActionState(ActionState.State.EXECUTING); @@ -812,13 +806,13 @@ public void testThatScenesDoNotInterfereEachOther() throws Exception { // validate that all lights are red for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light is not red!", Color.RED.getColor(), colorableLight.getColorState().getColor()); + assertEquals(Color.RED.getColor(), colorableLight.getColorState().getColor(), "Light is not red!"); } // validate the room is red Thread.sleep(AGGREGATION_TIME); // let us wait some time to let the aggregation takes place. rootLocationRemote.requestData().get(); - Assert.assertTrue("Scene does not apply its color, expected: " + Color.RED.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!", ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.RED)); + assertTrue(ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.RED), "Scene does not apply its color, expected: " + Color.RED.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!"); // deactivate blue observe(blueSceneRemote.setActivationState(Activation.INACTIVE)).waitForActionState(ActionState.State.EXECUTING); @@ -826,13 +820,13 @@ public void testThatScenesDoNotInterfereEachOther() throws Exception { // validate that all lights are still red for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light is not red!", Color.RED.getColor(), colorableLight.getColorState().getColor()); + assertEquals(Color.RED.getColor(), colorableLight.getColorState().getColor(), "Light is not red!"); } // validate the room is still red Thread.sleep(AGGREGATION_TIME); // let us wait some time to let the aggregation takes place. rootLocationRemote.requestData().get(); - Assert.assertTrue("Scene does not apply its color, expected: " + Color.RED.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!", ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.RED)); + assertTrue(ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.RED), "Scene does not apply its color, expected: " + Color.RED.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!"); // activate blue observe(blueSceneRemote.setActivationState(Activation.ACTIVE)).waitForActionState(ActionState.State.EXECUTING); @@ -840,13 +834,17 @@ public void testThatScenesDoNotInterfereEachOther() throws Exception { // validate that all lights are blue for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light is not blue!", Color.BLUE.getColor(), colorableLight.getColorState().getColor()); + assertEquals(Color.BLUE.getColor(), colorableLight.getColorState().getColor(), "Light is not blue!"); } // validate the room is blue Thread.sleep(AGGREGATION_TIME); // let us wait some time to let the aggregation takes place. rootLocationRemote.requestData().get(); - Assert.assertTrue("Scene does not apply its color, expected: " + Color.BLUE.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!", ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.BLUE)); + assertTrue( + ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), + Color.BLUE), + "Scene does not apply its color, expected: " + Color.BLUE.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!" + ); // deactivate blue observe(blueSceneRemote.setActivationState(Activation.INACTIVE)).waitForActionState(ActionState.State.EXECUTING); @@ -854,13 +852,13 @@ public void testThatScenesDoNotInterfereEachOther() throws Exception { // validate that all lights are red again for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light is not red but: "+ MultiLanguageTextProcessor.getBestMatch(colorableLight.getColorState().getResponsibleAction().getDescription(), "?"), Color.RED.getColor(), colorableLight.getColorState().getColor()); + assertEquals(Color.RED.getColor(), colorableLight.getColorState().getColor(), "Light is not red but: "+ MultiLanguageTextProcessor.getBestMatch(colorableLight.getColorState().getResponsibleAction().getDescription(), "?")); } // validate the room is red again Thread.sleep(AGGREGATION_TIME); // let us wait some time to let the aggregation takes place. rootLocationRemote.requestData().get(); - Assert.assertTrue("Scene does not apply its color, expected: " + Color.RED.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!", ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.RED)); + assertTrue(ColorStateProviderService.equalServiceStates(rootLocationRemote.getColorState(), Color.RED), "Scene does not apply its color, expected: " + Color.RED.getColor() + " but was: " + rootLocationRemote.getColorState().getColor() + "!"); // deactivate red and validate the room is off @@ -869,12 +867,12 @@ public void testThatScenesDoNotInterfereEachOther() throws Exception { // validate that all lights are off again for (ColorableLightRemote colorableLight : colorableLights) { colorableLight.requestData().get(); - Assert.assertEquals("Light is not off!", Power.OFF.getValue(), colorableLight.getPowerState().getValue()); + assertEquals(Power.OFF.getValue(), colorableLight.getPowerState().getValue(), "Light is not off!"); } // validate that the room is off Thread.sleep(AGGREGATION_TIME); // let us wait some time to let the aggregation takes place. rootLocationRemote.requestData().get(); - Assert.assertEquals("Room is not off!", Power.OFF.getValue(), rootLocationRemote.getPowerState().getValue()); + assertEquals(Power.OFF.getValue(), rootLocationRemote.getPowerState().getValue(), "Room is not off!"); } } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/unitgroup/UnitGroupRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/unitgroup/UnitGroupRemoteTest.java index 3455d8eb05..1dacf9accd 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/unitgroup/UnitGroupRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/unitgroup/UnitGroupRemoteTest.java @@ -59,8 +59,7 @@ import java.util.*; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Tamino Huxohl @@ -73,9 +72,7 @@ public class UnitGroupRemoteTest extends AbstractBCOLocationManagerTest { private static final List UNIT_LIST = new ArrayList<>(); @BeforeAll - public static void setUpClass() throws Throwable { - AbstractBCOLocationManagerTest.setUpClass(); - + public static void loadUnits() throws Throwable { try { UnitConfig unitGroupConfig = registerUnitGroup(); unitGroupRemote = Units.getUnit(unitGroupConfig, true, UnitGroupRemote.class); @@ -128,16 +125,6 @@ private static boolean allServiceTemplatesImplementedByUnit(UnitGroupConfig.Buil return true; } - @BeforeEach - public void setUp() throws InitializationException, InvalidStateException { - - } - - @AfterEach - public void tearDown() throws CouldNotPerformException { - - } - /** * Test of setPowerState method, of class UnitGroupRemote. * @@ -152,13 +139,13 @@ public void testSetPowerState() throws Exception { waitForExecution(unitGroupRemote.setPowerState(state)); for (final Unit unit : UNIT_LIST) { - assertEquals("Power state of unit [" + unit.getConfig().getId() + "] has not been set on!", state.getValue(), ((PowerStateOperationService) unit).getPowerState().getValue()); + assertEquals(state.getValue(), ((PowerStateOperationService) unit).getPowerState().getValue(), "Power state of unit [" + unit.getConfig().getId() + "] has not been set on!"); } state = PowerState.newBuilder().setValue(PowerState.State.OFF).build(); waitForExecution(unitGroupRemote.setPowerState(state)); for (final Unit unit : UNIT_LIST) { - assertEquals("Power state of unit [" + unit.getConfig().getId() + "] has not been set on!", state.getValue(), ((PowerStateOperationService) unit).getPowerState().getValue()); + assertEquals(state.getValue(), ((PowerStateOperationService) unit).getPowerState().getValue(), "Power state of unit [" + unit.getConfig().getId() + "] has not been set on!"); } } @@ -174,7 +161,7 @@ public void testGetPowerState() throws Exception { unitGroupRemote.waitForData(); PowerState state = PowerState.newBuilder().setValue(PowerState.State.OFF).build(); waitForExecution(unitGroupRemote.setPowerState(state)); - assertEquals("Power state has not been set in time or the return value from the getter is different!", state.getValue(), unitGroupRemote.getPowerState().getValue()); + assertEquals(state.getValue(), unitGroupRemote.getPowerState().getValue(), "Power state has not been set in time or the return value from the getter is different!"); } /** diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/AbstractBCOUserManagerTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/AbstractBCOUserManagerTest.java index 47135cddf6..ff21d646da 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/AbstractBCOUserManagerTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/AbstractBCOUserManagerTest.java @@ -42,10 +42,8 @@ public class AbstractBCOUserManagerTest extends AbstractBCOTest { protected static UserManagerLauncher userManagerLauncher; @BeforeAll - public static void setUpClass() throws Throwable { + public static void setupUserManager() throws Throwable { try { - AbstractBCOTest.setUpClass(); - userManagerLauncher = new UserManagerLauncher(); userManagerLauncher.launch().get(); @@ -56,12 +54,11 @@ public static void setUpClass() throws Throwable { } @AfterAll - public static void tearDownClass() throws Throwable { + public static void tearDownUserManager() throws Throwable { try { if (userManagerLauncher != null) { userManagerLauncher.shutdown(); } - AbstractBCOTest.tearDownClass(); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); } diff --git a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/UserRemoteTest.java b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/UserRemoteTest.java index afb188c184..026cf8a75d 100644 --- a/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/UserRemoteTest.java +++ b/module/dal/test/src/test/java/org/openbase/bco/dal/test/layer/unit/user/UserRemoteTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -38,8 +39,6 @@ import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate.UnitType; import org.slf4j.LoggerFactory; -import static org.junit.Assert.*; - /** * Integration test of controlling a user controller using a user remote. * @@ -52,10 +51,8 @@ public class UserRemoteTest extends AbstractBCOUserManagerTest { private static UserRemote userRemote; @BeforeAll - public static void setUpClass() throws Throwable { + public static void loadUnits() throws Throwable { try { - AbstractBCOUserManagerTest.setUpClass(); - userRemote = Units.getUnit(MockRegistry.testUser, true, UserRemote.class); } catch (CouldNotPerformException | InterruptedException ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, LOGGER); @@ -65,14 +62,13 @@ public static void setUpClass() throws Throwable { /** * Test of getUsername method, of class UserRemote. * - * @throws java.lang.Exception */ @Test @Timeout(10) public void testGetUserName() throws Exception { System.out.println("testGetUserName"); userRemote.requestData().get(); - assertEquals("The user created in the test has a different user name than the one registered!", MockRegistry.USER_NAME, userRemote.getUserName()); + assertEquals(MockRegistry.USER_NAME, userRemote.getUserName(), "The user created in the test has a different user name than the one registered!"); } /** @@ -86,13 +82,13 @@ public void testSetPresenceState() throws Exception { System.out.println("testSetPresenceState"); waitForExecution(userRemote.setPresenceState(State.PRESENT)); - assertEquals("User presence state has not updated as expected", State.PRESENT, userRemote.getPresenceState().getValue()); - assertTrue("Local position state has not updated as expected", - userRemote.getLocalPositionState().getLocationIdList().contains(Registries.getUnitRegistry().getRootLocationConfig().getId())); + assertEquals(State.PRESENT, userRemote.getPresenceState().getValue(), "User presence state has not updated as expected"); + assertTrue(userRemote.getLocalPositionState().getLocationIdList().contains(Registries.getUnitRegistry().getRootLocationConfig().getId()), + "Local position state has not updated as expected"); waitForExecution(userRemote.setPresenceState(State.ABSENT)); - assertEquals("User presence state has not updated as expected", State.ABSENT, userRemote.getPresenceState().getValue()); - assertTrue("Local position state has not updated as expected", userRemote.getLocalPositionState().getLocationIdList().isEmpty()); + assertEquals(State.ABSENT, userRemote.getPresenceState().getValue(), "User presence state has not updated as expected"); + assertTrue(userRemote.getLocalPositionState().getLocationIdList().isEmpty(), "Local position state has not updated as expected"); } /** @@ -110,18 +106,18 @@ public void testSetMultiActivityState() throws Exception { // test setting an activity waitForExecution(userRemote.setActivityMultiState(activityMultiState)); - assertTrue("Activity multi state does not contain the expected activity id", userRemote.getActivityMultiState().getActivityIdList().contains(activityId)); - assertEquals("User performs an unexpected number of activities", 1, userRemote.getActivityMultiState().getActivityIdCount()); + assertTrue(userRemote.getActivityMultiState().getActivityIdList().contains(activityId), "Activity multi state does not contain the expected activity id"); + assertEquals(1, userRemote.getActivityMultiState().getActivityIdCount(), "User performs an unexpected number of activities"); // test if duplicates will be removed, so nothing should change doing this waitForExecution(userRemote.addActivityState(activityId)); - assertTrue("Activity multi state does not contain the expected activity id", userRemote.getActivityMultiState().getActivityIdList().contains(activityId)); - assertEquals("User performs an unexpected number of activities", 1, userRemote.getActivityMultiState().getActivityIdCount()); + assertTrue(userRemote.getActivityMultiState().getActivityIdList().contains(activityId), "Activity multi state does not contain the expected activity id"); + assertEquals(1, userRemote.getActivityMultiState().getActivityIdCount(), "User performs an unexpected number of activities"); // test removing the activity waitForExecution(userRemote.removeActivityState(activityId)); - assertFalse("Activity multi state does contains an unexpected activity id", userRemote.getActivityMultiState().getActivityIdList().contains(activityId)); - assertEquals("User performs more activities than expected", 0, userRemote.getActivityMultiState().getActivityIdCount()); + assertFalse(userRemote.getActivityMultiState().getActivityIdList().contains(activityId), "Activity multi state does contains an unexpected activity id"); + assertEquals(0, userRemote.getActivityMultiState().getActivityIdCount(), "User performs more activities than expected"); } /** @@ -135,15 +131,15 @@ public void testUserTransitState() throws Exception { System.out.println("testUserTransitState"); waitForExecution(userRemote.setUserTransitState(UserTransitState.State.LONG_TERM_ABSENT)); - assertEquals("User transit state has not updated as expected", UserTransitState.State.LONG_TERM_ABSENT, userRemote.getUserTransitState().getValue()); - assertEquals("User presence state has not updated as expected", State.ABSENT, userRemote.getPresenceState().getValue()); - assertTrue("Local position state has not updated as expected", userRemote.getLocalPositionState().getLocationIdList().isEmpty()); + assertEquals(UserTransitState.State.LONG_TERM_ABSENT, userRemote.getUserTransitState().getValue(), "User transit state has not updated as expected"); + assertEquals(State.ABSENT, userRemote.getPresenceState().getValue(), "User presence state has not updated as expected"); + assertTrue(userRemote.getLocalPositionState().getLocationIdList().isEmpty(), "Local position state has not updated as expected"); waitForExecution(userRemote.setUserTransitState(UserTransitState.State.SOON_ABSENT)); - assertEquals("User transit state has not updated as expected", UserTransitState.State.SOON_ABSENT, userRemote.getUserTransitState().getValue()); - assertEquals("User presence state has not updated as expected", State.PRESENT, userRemote.getPresenceState().getValue()); - assertTrue("Local position state has not updated as expected", - userRemote.getLocalPositionState().getLocationIdList().contains(Registries.getUnitRegistry().getRootLocationConfig().getId())); + assertEquals(UserTransitState.State.SOON_ABSENT, userRemote.getUserTransitState().getValue(), "User transit state has not updated as expected"); + assertEquals(State.PRESENT, userRemote.getPresenceState().getValue(), "User presence state has not updated as expected"); + assertTrue(userRemote.getLocalPositionState().getLocationIdList().contains(Registries.getUnitRegistry().getRootLocationConfig().getId()), + "Local position state has not updated as expected"); } /** @@ -160,14 +156,14 @@ public void testLocalPositionState() throws Exception { // create state with random location localPositionState = LocalPositionState.newBuilder().addLocationId(Registries.getUnitRegistry().getUnitConfigsByUnitType(UnitType.LOCATION).get(0).getId()).build(); waitForExecution(userRemote.setLocalPositionState(localPositionState)); - assertTrue("Local position state has not updated as expected", - userRemote.getLocalPositionState().getLocationIdList().contains(localPositionState.getLocationId(0))); - assertEquals("User presence state has not updated as expected", State.PRESENT, userRemote.getPresenceState().getValue()); + assertTrue(userRemote.getLocalPositionState().getLocationIdList().contains(localPositionState.getLocationId(0)), + "Local position state has not updated as expected"); + assertEquals(State.PRESENT, userRemote.getPresenceState().getValue(), "User presence state has not updated as expected"); // create state without location localPositionState = localPositionState.toBuilder().clearLocationId().build(); waitForExecution(userRemote.setLocalPositionState(localPositionState)); - assertTrue("Local position state has not updated as expected", userRemote.getLocalPositionState().getLocationIdList().isEmpty()); - assertEquals("User presence state has not updated as expected", State.ABSENT, userRemote.getPresenceState().getValue()); + assertTrue(userRemote.getLocalPositionState().getLocationIdList().isEmpty(), "Local position state has not updated as expected"); + assertEquals(State.ABSENT, userRemote.getPresenceState().getValue(), "User presence state has not updated as expected"); } } diff --git a/module/device/openhab/src/test/org/openbase/bco/device/openhab/manager/transform/ServiceTypeCommandMappingTest.java b/module/device/openhab/src/test/org/openbase/bco/device/openhab/manager/transform/ServiceTypeCommandMappingTest.java index 8810542e0d..457e906866 100644 --- a/module/device/openhab/src/test/org/openbase/bco/device/openhab/manager/transform/ServiceTypeCommandMappingTest.java +++ b/module/device/openhab/src/test/org/openbase/bco/device/openhab/manager/transform/ServiceTypeCommandMappingTest.java @@ -42,12 +42,12 @@ public class ServiceTypeCommandMappingTest { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceTypeCommandMappingTest.class); - // @BeforeClass + // @BeforeAll // public static void setUpClass() throws InstantiationException { // MockRegistryHolder.newMockRegistry(); // } // -// @AfterClass +// @AfterAll // public static void tearDownClass() { // MockRegistryHolder.shutdownMockRegistry(); // } diff --git a/module/registry/remote/src/main/java/org/openbase/bco/registry/remote/Registries.java b/module/registry/remote/src/main/java/org/openbase/bco/registry/remote/Registries.java index fbb1d5db15..eaaf4a79ac 100644 --- a/module/registry/remote/src/main/java/org/openbase/bco/registry/remote/Registries.java +++ b/module/registry/remote/src/main/java/org/openbase/bco/registry/remote/Registries.java @@ -324,6 +324,19 @@ public static void prepare() throws CouldNotPerformException { CachedTemplateRegistryRemote.prepare(); } + public static Future requestData() { + try { + return FutureProcessor.allOf( + CachedUnitRegistryRemote.getRegistry().requestData(), + CachedActivityRegistryRemote.getRegistry().requestData(), + CachedClassRegistryRemote.getRegistry().requestData(), + CachedTemplateRegistryRemote.getRegistry().requestData() + ); + } catch (NotAvailableException ex) { + return FutureProcessor.canceledFuture(ex); + } + } + /** * Method only returns if all available registries are synchronized. * diff --git a/module/registry/unit-registry/test/build.gradle.kts b/module/registry/unit-registry/test/build.gradle.kts index 16571ba177..e288583d6f 100644 --- a/module/registry/unit-registry/test/build.gradle.kts +++ b/module/registry/unit-registry/test/build.gradle.kts @@ -1,3 +1,4 @@ + /* * This file was generated by the Gradle 'init' task. */ diff --git a/module/registry/unit-registry/test/src/main/java/org/openbase/bco/registry/unit/test/AbstractBCORegistryTest.java b/module/registry/unit-registry/test/src/main/java/org/openbase/bco/registry/unit/test/AbstractBCORegistryTest.java index d8aa96a242..969ae4db89 100644 --- a/module/registry/unit-registry/test/src/main/java/org/openbase/bco/registry/unit/test/AbstractBCORegistryTest.java +++ b/module/registry/unit-registry/test/src/main/java/org/openbase/bco/registry/unit/test/AbstractBCORegistryTest.java @@ -22,8 +22,8 @@ * #L% */ -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.openbase.bco.authentication.mock.MqttIntegrationTest; import org.openbase.bco.registry.mock.MockRegistryHolder; import org.openbase.bco.registry.remote.Registries; @@ -55,17 +55,18 @@ public abstract class AbstractBCORegistryTest extends MqttIntegrationTest { final Logger logger = LoggerFactory.getLogger(getClass()); - @Before - public void setUp() throws Exception { + @BeforeEach + public void setupMockRegistry() throws Exception { try { MockRegistryHolder.newMockRegistry(); + Registries.waitForData(); } catch (Exception ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); } } - @After - public void tearDown() throws Exception { + @AfterEach + public void tearDownMockRegistry() throws Exception { try { MockRegistryHolder.shutdownMockRegistry(); } catch (Exception ex) { diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/DeviceRegistryTest.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/DeviceRegistryTest.java index 63bfb1b543..c6507f7372 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/DeviceRegistryTest.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/DeviceRegistryTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.registry.mock.MockRegistry; @@ -37,6 +38,7 @@ import org.openbase.type.domotic.service.ServiceTemplateConfigType.ServiceTemplateConfig; import org.openbase.type.domotic.service.ServiceTemplateType.ServiceTemplate.ServiceType; import org.openbase.type.domotic.state.EnablingStateType.EnablingState; +import org.openbase.type.domotic.state.EnablingStateType.EnablingState.State; import org.openbase.type.domotic.state.InventoryStateType.InventoryState; import org.openbase.type.domotic.unit.UnitConfigType.UnitConfig; import org.openbase.type.domotic.unit.UnitTemplateConfigType.UnitTemplateConfig; @@ -54,8 +56,6 @@ import java.util.List; import java.util.Locale; -import static junit.framework.TestCase.*; - /** * @author Divine Threepwood */ @@ -96,12 +96,12 @@ public void testRegisterUnitConfigWithUnits() throws Exception { String deviceScope = "/" + Registries.getUnitRegistry().getRootLocationConfig().getAlias(0).toLowerCase() + "/" + "device" + "/"+motionSensorConfig.getAlias(0).toLowerCase(); String expectedUnitScope = "/" + Registries.getUnitRegistry().getRootLocationConfig().getAlias(0).toLowerCase() + "/" + UnitType.BATTERY.name().toLowerCase() + "/" + batteryUnitConfig.getAlias(0).toLowerCase(); - assertEquals("Device scope is not set properly", deviceScope, ScopeProcessor.generateStringRep(motionSensorConfig.getScope())); - assertEquals("Device has not the correct number of units", 1, motionSensorConfig.getDeviceConfig().getUnitIdCount()); + assertEquals(deviceScope, ScopeProcessor.generateStringRep(motionSensorConfig.getScope()), "Device scope is not set properly"); + assertEquals(1, motionSensorConfig.getDeviceConfig().getUnitIdCount(), "Device has not the correct number of units"); UnitConfig batteryUnit = Registries.getUnitRegistry().getUnitConfigById(motionSensorConfig.getDeviceConfig().getUnitId(0)); - assertEquals("Unit scope is not set properly", expectedUnitScope, ScopeProcessor.generateStringRep(batteryUnit.getScope())); - assertEquals("Device id is not set in unit", motionSensorConfig.getId(), batteryUnit.getUnitHostId()); + assertEquals(expectedUnitScope, ScopeProcessor.generateStringRep(batteryUnit.getScope()), "Unit scope is not set properly"); + assertEquals(motionSensorConfig.getId(), batteryUnit.getUnitHostId(), "Device id is not set in unit"); } /** @@ -122,9 +122,9 @@ public void testRegisteredDeviceConfigWithoutLabel() throws Exception { UnitConfig deviceWithoutLabel = generateDeviceUnitConfig("", serialNumber, deviceClass).toBuilder().clearLabel().build(); deviceWithoutLabel = Registries.getUnitRegistry().registerUnitConfig(deviceWithoutLabel).get(); - assertEquals("The device label is not set as the id if it is empty!", - LabelProcessor.format(deviceClass.getCompany() + " " + LabelProcessor.getBestMatch(deviceClass.getLabel()) + " " + deviceWithoutLabel.getAlias(0)), - LabelProcessor.getBestMatch(deviceWithoutLabel.getLabel())); + assertEquals(LabelProcessor.format(deviceClass.getCompany() + " " + LabelProcessor.getBestMatch(deviceClass.getLabel()) + " " + deviceWithoutLabel.getAlias(0)), + LabelProcessor.getBestMatch(deviceWithoutLabel.getLabel()), + "The device label is not set as the id if it is empty!"); } @Test @@ -141,9 +141,9 @@ public void testUnitConfigUnitTemplateConsistencyHandler() throws Exception { unitTemplate = Registries.getTemplateRegistry().getUnitTemplateByType(UnitType.COLORABLE_LIGHT); unitTemplate = unitTemplate.toBuilder().addServiceDescription(batteryTemplate).addServiceDescription(colorTemplate).build(); unitTemplate = Registries.getTemplateRegistry().updateUnitTemplate(unitTemplate).get(); - assertTrue(unitTemplate.getServiceDescriptionList().get(0).getServiceType() == ServiceType.BATTERY_STATE_SERVICE); - assertTrue(unitTemplate.getServiceDescriptionList().get(1).getServiceType() == ServiceType.COLOR_STATE_SERVICE); - assertTrue(unitTemplate.getUnitType() == UnitType.COLORABLE_LIGHT); + assertSame(unitTemplate.getServiceDescriptionList().get(0).getServiceType(), ServiceType.BATTERY_STATE_SERVICE); + assertSame(unitTemplate.getServiceDescriptionList().get(1).getServiceType(), ServiceType.COLOR_STATE_SERVICE); + assertSame(unitTemplate.getUnitType(), UnitType.COLORABLE_LIGHT); UnitTemplateConfig unitTemplateConfig = UnitTemplateConfig.newBuilder().setUnitType(unitTemplate.getUnitType()).build(); String serialNumber1 = "5073"; @@ -157,10 +157,10 @@ public void testUnitConfigUnitTemplateConsistencyHandler() throws Exception { UnitConfig localDeviceConfig = generateDeviceUnitConfig(deviceLabel, serialNumber1, clazz); localDeviceConfig = Registries.getUnitRegistry().registerUnitConfig(localDeviceConfig).get(); - assertTrue("DeviceConfig does not contain the correct amount of units", localDeviceConfig.getDeviceConfig().getUnitIdCount() == 1); + assertTrue(localDeviceConfig.getDeviceConfig().getUnitIdCount() == 1, "DeviceConfig does not contain the correct amount of units"); UnitConfig registeredUnit = Registries.getUnitRegistry().getUnitConfigById(localDeviceConfig.getDeviceConfig().getUnitId(0)); - assertEquals("The amount of service configs for the unit is not correct", 2, registeredUnit.getServiceConfigCount()); + assertEquals(2, registeredUnit.getServiceConfigCount(), "The amount of service configs for the unit is not correct"); assertTrue(registeredUnit.getServiceConfig(0).getServiceDescription().getServiceType() == ServiceType.BATTERY_STATE_SERVICE || registeredUnit.getServiceConfig(0).getServiceDescription().getServiceType() == ServiceType.COLOR_STATE_SERVICE); assertTrue(registeredUnit.getServiceConfig(1).getServiceDescription().getServiceType() == ServiceType.BATTERY_STATE_SERVICE || registeredUnit.getServiceConfig(1).getServiceDescription().getServiceType() == ServiceType.COLOR_STATE_SERVICE); @@ -209,7 +209,7 @@ public void testDeviceClassDeviceConfigUnitConsistencyHandler() throws Exception logger.info(unitTemplateConfigList.get(0) + ", " + unitTemplateConfigList.get(1)); UnitConfig config = Registries.getUnitRegistry().registerUnitConfig(generateDeviceUnitConfig("DeviceConfigWhereUnitsShallBeSetViaConsistency", "randomSerial14972", clazz)).get(); - assertEquals("Units in device config were not set according to the device classes unit templates", clazz.getUnitTemplateConfigCount(), config.getDeviceConfig().getUnitIdCount()); + assertEquals(clazz.getUnitTemplateConfigCount(), config.getDeviceConfig().getUnitIdCount(), "Units in device config were not set according to the device classes unit templates"); boolean containsLight = false; boolean containsHandlseSensor = false; List dalUnitConfigs = new ArrayList<>(); @@ -219,17 +219,17 @@ public void testDeviceClassDeviceConfigUnitConsistencyHandler() throws Exception for (UnitConfig unit : dalUnitConfigs) { if (unit.getUnitType().equals(unitTemplateConfig1.getUnitType())) { containsLight = true; - assertEquals("The light unit contains more or less services than the template config", unit.getServiceConfigCount(), unitTemplateConfig1.getServiceTemplateConfigCount()); - assertTrue("The service type of the light unit does not match", unit.getServiceConfig(0).getServiceDescription().getServiceType().equals(serviceTemplate1.getServiceType())); + assertEquals(unit.getServiceConfigCount(), unitTemplateConfig1.getServiceTemplateConfigCount(), "The light unit contains more or less services than the template config"); + assertTrue(unit.getServiceConfig(0).getServiceDescription().getServiceType().equals(serviceTemplate1.getServiceType()), "The service type of the light unit does not match"); } else if (unit.getUnitType().equals(unitTemplateConfig2.getUnitType())) { containsHandlseSensor = true; - assertEquals("The handle sensor unit contains more or less services than the template config", unitTemplateConfig2.getServiceTemplateConfigCount(), unit.getServiceConfigCount()); - assertEquals("The service type of the handle sensor unit does not match", unit.getServiceConfig(0).getServiceDescription().getServiceType(), serviceTemplate2.getServiceType()); - assertEquals("The service type of the handle sensor unit does not match", unit.getServiceConfig(1).getServiceDescription().getServiceType(), serviceTemplate3.getServiceType()); + assertEquals(unitTemplateConfig2.getServiceTemplateConfigCount(), unit.getServiceConfigCount(), "The handle sensor unit contains more or less services than the template config"); + assertEquals(unit.getServiceConfig(0).getServiceDescription().getServiceType(), serviceTemplate2.getServiceType(), "The service type of the handle sensor unit does not match"); + assertEquals(unit.getServiceConfig(1).getServiceDescription().getServiceType(), serviceTemplate3.getServiceType(), "The service type of the handle sensor unit does not match"); } } - assertTrue("The device config does not contain a light unit even though the device class has an according unit template", containsLight); - assertTrue("The device config does not contain a handle sensor unit even though the device class has an according unit template", containsHandlseSensor); + assertTrue(containsLight, "The device config does not contain a light unit even though the device class has an according unit template"); + assertTrue(containsHandlseSensor, "The device config does not contain a handle sensor unit even though the device class has an according unit template"); ServiceTemplateConfig serviceTemplate4 = ServiceTemplateConfig.newBuilder().setServiceType(ServiceType.BUTTON_STATE_SERVICE).build(); UnitTemplateConfig unitTemplateConfig3 = UnitTemplateConfig.newBuilder().setUnitType(UnitType.BUTTON).addServiceTemplateConfig(serviceTemplate1).build(); @@ -239,33 +239,35 @@ public void testDeviceClassDeviceConfigUnitConsistencyHandler() throws Exception System.out.println("Updating deviceClass..."); clazz = Registries.getClassRegistry().updateDeviceClass(clazz.toBuilder().addUnitTemplateConfig(unitTemplateConfig3).build()).get(); + + Registries.waitUntilReady(); + Registries.requestData(); + config = Registries.getUnitRegistry().getUnitConfigById(config.getId()); - // the update is not synced immediately to the device config, thus this waits and fails if the timeout is exceeded - while (config.getDeviceConfig().getUnitIdCount() != clazz.getUnitTemplateConfigCount()) { - Thread.sleep(100); - config = Registries.getUnitRegistry().getUnitConfigById(config.getId()); - } - assertEquals("Unit configs and templates differ after the update of the device class", config.getDeviceConfig().getUnitIdCount(), clazz.getUnitTemplateConfigCount()); - Registries.getUnitRegistry().waitUntilReady(); + + + assertEquals(config.getDeviceConfig().getUnitIdCount(), clazz.getUnitTemplateConfigCount(), "Unit configs and templates differ after the update of the device class"); + Registries.waitUntilReady(); + Registries.requestData(); dalUnitConfigs.clear(); for (String unitId : config.getDeviceConfig().getUnitIdList()) { dalUnitConfigs.add(Registries.getUnitRegistry().getUnitConfigById(unitId)); } - assertEquals("Device config does not contain the right unit config", dalUnitConfigs.get(2).getUnitType(), unitTemplateConfig3.getUnitType()); - assertEquals("Unit config does not contain the right service", dalUnitConfigs.get(2).getServiceConfig(0).getServiceDescription().getServiceType(), serviceTemplate4.getServiceType()); + assertEquals(dalUnitConfigs.get(2).getUnitType(), unitTemplateConfig3.getUnitType(), "Device config does not contain the right unit config"); + assertEquals(dalUnitConfigs.get(2).getServiceConfig(0).getServiceDescription().getServiceType(), serviceTemplate4.getServiceType(), "Unit config does not contain the right service"); int sizeBefore = Registries.getUnitRegistry().getDalUnitConfigs().size(); UnitConfig.Builder configBuilder = config.toBuilder().clearLabel(); LabelProcessor.addLabel(configBuilder.getLabelBuilder(), Locale.ENGLISH, "newDeviceLabel"); config = Registries.getUnitRegistry().updateUnitConfig(configBuilder.build()).get(); - assertTrue("More dal units registered after device renaming!", Registries.getUnitRegistry().getDalUnitConfigs().size() == sizeBefore); - assertTrue("More units in device config after renaming!", config.getDeviceConfig().getUnitIdCount() == 3); + assertTrue(Registries.getUnitRegistry().getDalUnitConfigs().size() == sizeBefore, "More dal units registered after device renaming!"); + assertTrue(config.getDeviceConfig().getUnitIdCount() == 3, "More units in device config after renaming!"); //test if dal units are also removed when a device is removed Registries.getUnitRegistry().removeUnitConfig(config).get(); for (UnitConfig dalUnitConfig : dalUnitConfigs) { - assertTrue("DalUnit [" + dalUnitConfig.getLabel() + "] still registered even though its device has been removed!", !Registries.getUnitRegistry().containsUnitConfig(dalUnitConfig)); + assertTrue(!Registries.getUnitRegistry().containsUnitConfig(dalUnitConfig), "DalUnit [" + dalUnitConfig.getLabel() + "] still registered even though its device has been removed!"); } } @@ -294,7 +296,7 @@ public void testBoundingBoxConsistencyHandler() throws Exception { builder.setHeight((float) (0.0)); builder.setWidth((float) (5.0)); builder.setLeftFrontBottom(Translation.newBuilder().setX(0.1).setY(0).setZ(0)); - assertEquals("Bounding box has not been updated!", builder.build(), updatedUnit.getPlacementConfig().getShape().getBoundingBox()); + assertEquals(builder.build(), updatedUnit.getPlacementConfig().getShape().getBoundingBox(), "Bounding box has not been updated!"); } /** @@ -323,13 +325,13 @@ public void testOwnerRemoval() throws Exception { UnitConfig deviceUnitConfig = Registries.getUnitRegistry().registerUnitConfig(deviceUnitConfigBuilder.build()).get(); // test that owner id is still set after registration - assertEquals("The device does not have the correct owner id!", owner.getId(), deviceUnitConfig.getPermissionConfig().getOwnerId()); + assertEquals(owner.getId(), deviceUnitConfig.getPermissionConfig().getOwnerId(), "The device does not have the correct owner id!"); // remove the owner from the registry Registries.getUnitRegistry().removeUnitConfig(owner).get(); // validate that owner got removed - assertTrue("The owner did not get removed!", !Registries.getUnitRegistry().containsUnitConfig(owner)); + assertFalse(Registries.getUnitRegistry().containsUnitConfig(owner), "The owner did not get removed!"); // validate that owner has been removed from device unit config deviceUnitConfig = Registries.getUnitRegistry().getUnitConfigById(deviceUnitConfig.getId()); @@ -358,9 +360,9 @@ public void testInventoryEnablingStateConnection() throws Exception { device = Registries.getUnitRegistry().registerUnitConfig(device.build()).get().toBuilder(); UnitConfig dalUnit = Registries.getUnitRegistry().getUnitConfigById(device.getDeviceConfig().getUnitId(0)); - assertTrue("DeviceUnitConfig is not Enabled", device.getEnablingState().getValue() == EnablingState.State.ENABLED); - assertTrue("DalUnitConfig is not Enabled", device.getEnablingState().getValue() == dalUnit.getEnablingState().getValue()); - assertEquals("DeviceUnitConfig and DalUnitConfig have different labels", device.getLabel(), dalUnit.getLabel()); + assertSame(device.getEnablingState().getValue(), State.ENABLED, "DeviceUnitConfig is not Enabled"); + assertSame(device.getEnablingState().getValue(), dalUnit.getEnablingState().getValue(), "DalUnitConfig is not Enabled"); + assertEquals(device.getLabel(), dalUnit.getLabel(), "DeviceUnitConfig and DalUnitConfig have different labels"); label = label + "-2"; UnitConfig.Builder deviceBuilder = device.clearLabel(); @@ -374,18 +376,18 @@ public void testInventoryEnablingStateConnection() throws Exception { inventoryState.setValue(InventoryState.State.IN_STOCK); device = Registries.getUnitRegistry().updateUnitConfig(device.build()).get().toBuilder(); dalUnit = Registries.getUnitRegistry().getUnitConfigById(device.getDeviceConfig().getUnitId(0)); - assertTrue("DeviceUnitConfig inventory state is not IN_STOCK", device.getDeviceConfig().getInventoryState().getValue() == InventoryState.State.IN_STOCK); - assertTrue("DeviceUnitConfig is not Disabled", device.getEnablingState().getValue() == EnablingState.State.DISABLED); - assertTrue("DalUnitConfig is not Disabled", device.getEnablingState().getValue() == dalUnit.getEnablingState().getValue()); + assertSame(device.getDeviceConfig().getInventoryState().getValue(), InventoryState.State.IN_STOCK, "DeviceUnitConfig inventory state is not IN_STOCK"); + assertSame(device.getEnablingState().getValue(), State.DISABLED, "DeviceUnitConfig is not Disabled"); + assertSame(device.getEnablingState().getValue(), dalUnit.getEnablingState().getValue(), "DalUnitConfig is not Disabled"); deviceConfig = device.getDeviceConfigBuilder(); inventoryState = deviceConfig.getInventoryStateBuilder(); inventoryState.setValue(InventoryState.State.INSTALLED); device = Registries.getUnitRegistry().updateUnitConfig(device.build()).get().toBuilder(); dalUnit = Registries.getUnitRegistry().getUnitConfigById(device.getDeviceConfig().getUnitId(0)); - assertTrue("DeviceUnitConfig inventory state is not INSTALLED", device.getDeviceConfig().getInventoryState().getValue() == InventoryState.State.INSTALLED); - assertTrue("DeviceUnitConfig is not Enabled", device.getEnablingState().getValue() == EnablingState.State.ENABLED); - assertTrue("DalUnitConfig is not Enabled", device.getEnablingState().getValue() == dalUnit.getEnablingState().getValue()); + assertSame(device.getDeviceConfig().getInventoryState().getValue(), InventoryState.State.INSTALLED, "DeviceUnitConfig inventory state is not INSTALLED"); + assertSame(device.getEnablingState().getValue(), State.ENABLED, "DeviceUnitConfig is not Enabled"); + assertSame(device.getEnablingState().getValue(), dalUnit.getEnablingState().getValue(), "DalUnitConfig is not Enabled"); unitTemplate = Registries.getTemplateRegistry().getUnitTemplateByType(UnitType.LIGHT).toBuilder().clearServiceDescription().build(); Registries.getTemplateRegistry().updateUnitTemplate(unitTemplate).get(); @@ -407,7 +409,7 @@ public void testLocationIdInInventoryState() throws Exception { testLocationIdInInventoryStateDevice = testLocationIdInInventoryStateDevice.toBuilder().setDeviceConfig(tmp).build(); testLocationIdInInventoryStateDevice = Registries.getUnitRegistry().registerUnitConfig(testLocationIdInInventoryStateDevice).get(); - assertEquals("The location id in the inventory state has not been set for an installed device!", Registries.getUnitRegistry().getRootLocationConfig().getId(), testLocationIdInInventoryStateDevice.getDeviceConfig().getInventoryState().getLocationId()); + assertEquals(Registries.getUnitRegistry().getRootLocationConfig().getId(), testLocationIdInInventoryStateDevice.getDeviceConfig().getInventoryState().getLocationId(), "The location id in the inventory state has not been set for an installed device!"); } /** @@ -440,7 +442,7 @@ public void testRegistrationErrorHandling() throws Exception { Registries.getUnitRegistry().registerUnitConfig(newDeviceUnitConfig.toBuilder().clearId().build()).get(); fail("No exception thrown after updating a device with to have the same label as another"); } catch (Exception ex) { - assertEquals("DeviceConfig has been changed event though the update has been rejected", newDeviceUnitConfig, Registries.getUnitRegistry().getUnitConfigById(newDeviceUnitConfig.getId())); + assertEquals(newDeviceUnitConfig, Registries.getUnitRegistry().getUnitConfigById(newDeviceUnitConfig.getId()), "DeviceConfig has been changed event though the update has been rejected"); } finally { ExceptionPrinter.setBeQuit(Boolean.FALSE); } diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRegistryTest.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRegistryTest.java index b350e895f9..f2a7196690 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRegistryTest.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRegistryTest.java @@ -22,7 +22,7 @@ * #L% */ -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.registry.remote.Registries; @@ -38,9 +38,6 @@ import java.util.Arrays; import java.util.Locale; import java.util.concurrent.ExecutionException; - -import static org.junit.Assert.*; - /** * @author Divine Threepwood */ @@ -87,8 +84,8 @@ public void testRootLocationConsistency() throws Exception { String rootLocationLabel = "NewRootLocation"; UnitConfig.Builder newRootLocation = Registries.getUnitRegistry().registerUnitConfig(getLocationUnitBuilder(LocationType.ZONE, rootLocationLabel).build()).get().toBuilder(); // validate that newRootLocation is not yet root and put under the old root location - assertFalse("New location should not have been registered as root directly", newRootLocation.getLocationConfig().getRoot()); - assertEquals("New location should be put under the old root location", previousRootLocation.getId(), newRootLocation.getPlacementConfig().getLocationId()); + assertFalse(newRootLocation.getLocationConfig().getRoot(), "New location should not have been registered as root directly"); + assertEquals(previousRootLocation.getId(), newRootLocation.getPlacementConfig().getLocationId(), "New location should be put under the old root location"); // put previous root location under the new root location previousRootLocation.getPlacementConfigBuilder().setLocationId(newRootLocation.getId()); @@ -96,10 +93,10 @@ public void testRootLocationConsistency() throws Exception { // retrieve updated new root location newRootLocation = Registries.getUnitRegistry().getUnitConfigById(newRootLocation.getId()).toBuilder(); // validate that previous root location is not root anymore and that the new one is - assertFalse("Previous root location is still root", previousRootLocation.getLocationConfig().getRoot()); - assertEquals("Previous root location should be put under the new one", newRootLocation.getId(), previousRootLocation.getPlacementConfig().getLocationId()); - assertTrue("New root location did not become root", newRootLocation.getLocationConfig().getRoot()); - assertEquals("New root location should have itself as placement", newRootLocation.getId(), newRootLocation.getPlacementConfig().getLocationId()); + assertFalse(previousRootLocation.getLocationConfig().getRoot(), "Previous root location is still root"); + assertEquals(newRootLocation.getId(), previousRootLocation.getPlacementConfig().getLocationId(), "Previous root location should be put under the new one"); + assertTrue(newRootLocation.getLocationConfig().getRoot(), "New root location did not become root"); + assertEquals(newRootLocation.getId(), newRootLocation.getPlacementConfig().getLocationId(), "New root location should have itself as placement"); // try to do the change back again newRootLocation.getPlacementConfigBuilder().setLocationId(previousRootLocation.getId()); @@ -107,10 +104,10 @@ public void testRootLocationConsistency() throws Exception { // retrieve updated previous root previousRootLocation = Registries.getUnitRegistry().getUnitConfigById(previousRootLocation.getId()).toBuilder(); // test if all changes have been reverted - assertFalse("New root location is still root", newRootLocation.getLocationConfig().getRoot()); - assertEquals("New root location should be put under the previous one", previousRootLocation.getId(), newRootLocation.getPlacementConfig().getLocationId()); - assertTrue("Previous root location did not become root again", previousRootLocation.getLocationConfig().getRoot()); - assertEquals("Previous root location should have itself as placement", previousRootLocation.getId(), previousRootLocation.getPlacementConfig().getLocationId()); + assertFalse(newRootLocation.getLocationConfig().getRoot(), "New root location is still root"); + assertEquals(previousRootLocation.getId(), newRootLocation.getPlacementConfig().getLocationId(), "New root location should be put under the previous one"); + assertTrue(previousRootLocation.getLocationConfig().getRoot(), "Previous root location did not become root again"); + assertEquals(previousRootLocation.getId(), previousRootLocation.getPlacementConfig().getLocationId(), "Previous root location should have itself as placement"); } /** @@ -138,9 +135,9 @@ public void testParentChildConsistency() throws Exception { zone2 = Registries.getUnitRegistry().getUnitConfigById(zone2.getId()).toBuilder(); // validate that child location is placed under zone1, that zone1 contains it as a child and that zone2 does not - assertEquals("Child has not been placed under the correct location", zone1.getId(), childLocation.getPlacementConfig().getLocationId()); - assertTrue("Zone1 does not contain child location id", zone1.getLocationConfig().getChildIdList().contains(childLocation.getId())); - assertFalse("Zone2 contains child location id event though it should not", zone2.getLocationConfig().getChildIdList().contains(childLocation.getId())); + assertEquals(zone1.getId(), childLocation.getPlacementConfig().getLocationId(), "Child has not been placed under the correct location"); + assertTrue(zone1.getLocationConfig().getChildIdList().contains(childLocation.getId()), "Zone1 does not contain child location id"); + assertFalse(zone2.getLocationConfig().getChildIdList().contains(childLocation.getId()), "Zone2 contains child location id event though it should not"); // move child under zone2 childLocation.getPlacementConfigBuilder().setLocationId(zone2.getId()); @@ -151,9 +148,9 @@ public void testParentChildConsistency() throws Exception { zone2 = Registries.getUnitRegistry().getUnitConfigById(zone2.getId()).toBuilder(); // validate that child location is placed under zone2, that zone2 contains it as a child and that zone1 does not - assertEquals("Child has not been placed under the correct location", zone2.getId(), childLocation.getPlacementConfig().getLocationId()); - assertTrue("Zone2 does not contain child location id", zone2.getLocationConfig().getChildIdList().contains(childLocation.getId())); - assertFalse("Zone1 contains child location id event though it should not", zone1.getLocationConfig().getChildIdList().contains(childLocation.getId())); + assertEquals(zone2.getId(), childLocation.getPlacementConfig().getLocationId(), "Child has not been placed under the correct location"); + assertTrue(zone2.getLocationConfig().getChildIdList().contains(childLocation.getId()), "Zone2 does not contain child location id"); + assertFalse(zone1.getLocationConfig().getChildIdList().contains(childLocation.getId()), "Zone1 contains child location id event though it should not"); } /** @@ -182,7 +179,7 @@ public void testLoopConsistency() throws Exception { // push loop to registry zone1 = Registries.getUnitRegistry().updateUnitConfig(zone1.build()).get().toBuilder(); // fail if no exception has been thrown - Assert.fail("No exception when registering a loop"); + fail("No exception when registering a loop"); } catch (ExecutionException ex) { // if an execution exception is thrown the loop could not be registered } finally { @@ -217,7 +214,7 @@ public void testConnectionTilesConsistency() throws Exception { // try to register the connection which should fail Registries.getUnitRegistry().registerUnitConfig(failingConnectionConfig.build()).get(); // fail of no exception has been thrown - Assert.fail("Registered connection with less than one tile"); + fail("Registered connection with less than one tile"); } catch (ExecutionException ex) { // if an execution exception is thrown the connection could not be registered } finally { @@ -242,9 +239,9 @@ public void testConnectionTilesConsistency() throws Exception { connection = Registries.getUnitRegistry().registerUnitConfig(connection.build()).get().toBuilder(); // verify that only the two tile ids remain in the tile id list - assertEquals("Tile id list has not been reduced by removing fakes and duplicates", 2, connection.getConnectionConfig().getTileIdCount()); - assertTrue("The tile list does not contain the expected tile", connection.getConnectionConfig().getTileIdList().contains(tile1.getId())); - assertTrue("The tile list does not contain the expected tile", connection.getConnectionConfig().getTileIdList().contains(tile2.getId())); + assertEquals(2, connection.getConnectionConfig().getTileIdCount(), "Tile id list has not been reduced by removing fakes and duplicates"); + assertTrue(connection.getConnectionConfig().getTileIdList().contains(tile1.getId()), "The tile list does not contain the expected tile"); + assertTrue(connection.getConnectionConfig().getTileIdList().contains(tile2.getId()), "The tile list does not contain the expected tile"); } /** @@ -262,7 +259,7 @@ public void testLocationTypeConsistency() throws Exception { UnitConfig.Builder root = Registries.getUnitRegistry().getRootLocationConfig().toBuilder(); root.getLocationConfigBuilder().clearLocationType(); root = Registries.getUnitRegistry().updateUnitConfig(root.build()).get().toBuilder(); - assertEquals("Location type zone has not been recovered for root location", LocationType.ZONE, root.getLocationConfig().getLocationType()); + assertEquals(LocationType.ZONE, root.getLocationConfig().getLocationType(), "Location type zone has not been recovered for root location"); // register a tile UnitConfig.Builder tile = Registries.getUnitRegistry().registerUnitConfig(getLocationUnitBuilder(LocationType.TILE, "Tile", root.getId()).build()).get().toBuilder(); @@ -271,13 +268,13 @@ public void testLocationTypeConsistency() throws Exception { UnitConfig.Builder region = getLocationUnitBuilder("Region"); region.getPlacementConfigBuilder().setLocationId(tile.getId()); region = Registries.getUnitRegistry().registerUnitConfig(region.build()).get().toBuilder(); - assertEquals("Type has not been detected for region", LocationType.REGION, region.getLocationConfig().getLocationType()); + assertEquals(LocationType.REGION, region.getLocationConfig().getLocationType(), "Type has not been detected for region"); // now the tile has a zone as its parent and a region as its child, therefore the consistency handler should be // able to recover its type tile.getLocationConfigBuilder().setLocationType(LocationType.ZONE); tile = Registries.getUnitRegistry().updateUnitConfig(tile.build()).get().toBuilder(); - assertEquals("Type of tile has not been recovered", LocationType.TILE, tile.getLocationConfig().getLocationType()); + assertEquals(LocationType.TILE, tile.getLocationConfig().getLocationType(), "Type of tile has not been recovered"); } /** @@ -291,6 +288,6 @@ public void testGetLocationUnitConfigByScope() throws Exception { System.out.println("testGetLocationUnitConfigByScope"); final UnitConfig rootLocation = Registries.getUnitRegistry().getRootLocationConfig(); - assertEquals("Could not resolve locationUnitConfig by its scope", rootLocation, Registries.getUnitRegistry().getUnitConfigByScope(rootLocation.getScope())); + assertEquals(rootLocation, Registries.getUnitRegistry().getUnitConfigByScope(rootLocation.getScope()), "Could not resolve locationUnitConfig by its scope"); } } diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRemovalTest.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRemovalTest.java index 467b68cfda..5cba128d1e 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRemovalTest.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/LocationRemovalTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.registry.remote.Registries; @@ -35,8 +36,6 @@ import java.util.Random; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.assertFalse; - /** * In this test the MockRegistry is started and all its locations except the root are * removed in a random order. @@ -78,7 +77,7 @@ public void removeAllLocationsTest() throws Exception { Registries.getUnitRegistry().removeUnitConfig(locationConfig).get(); // test if removal really worked - assertFalse("LocationRegistry still contains locationConfig[" + locationConfig.getLabel() + "] after removal", Registries.getUnitRegistry().containsUnitConfig(locationConfig)); + assertFalse(Registries.getUnitRegistry().containsUnitConfig(locationConfig), "LocationRegistry still contains locationConfig[" + locationConfig.getLabel() + "] after removal"); logger.info("Removed location[" + ScopeProcessor.generateStringRep(locationConfig.getScope()) + "] successfully. " + locationConfigList.size() + " location[s] remaining."); } } catch (InterruptedException | ExecutionException | CouldNotPerformException ex) { diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/RegistryFilteringTest.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/RegistryFilteringTest.java index b35d107b77..f62d7825e9 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/RegistryFilteringTest.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/RegistryFilteringTest.java @@ -45,8 +45,8 @@ import java.util.Base64; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.*; /** * @author Tamino Huxohl @@ -55,7 +55,6 @@ public class RegistryFilteringTest extends AbstractBCORegistryTest { @AfterEach public void tearDown() throws Exception { - super.tearDown(); SessionManager.getInstance().completeLogout(); } @@ -114,12 +113,12 @@ public void testUnitFiltering() throws Exception { Registries.getUnitRegistry().updateUnitConfig(unitConfig.build()).get(); // test if location does not contain unit ids and child ids anymore anymore - assertTrue("Unit id list of location has not been filtered without access and read permissions", Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getUnitIdList().isEmpty()); - assertTrue("Child id list of location has not been filtered without access and read permissions", Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getChildIdList().isEmpty()); + assertTrue(Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getUnitIdList().isEmpty(), "Unit id list of location has not been filtered without access and read permissions"); + assertTrue(Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getChildIdList().isEmpty(), "Child id list of location has not been filtered without access and read permissions"); // test if unit configuration cannot be read anymore try { Registries.getUnitRegistry().getUnitConfigById(unitConfig.getLocationConfig().getUnitId(0)); - assertTrue("Unit configuration can still be seen even though other has no read and access permissions on its location", false); + fail("Unit configuration can still be seen even though other has no read and access permissions on its location"); } catch (NotAvailableException ex) { // this should happen } @@ -129,37 +128,41 @@ public void testUnitFiltering() throws Exception { Registries.getUnitRegistry().updateUnitConfig(unitConfig.build()).get(); // test if unit ids and child ids are back - assertEquals("Unit id list of location not available with read permissions", + assertEquals( unitConfig.getLocationConfig().getUnitIdCount(), - Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getUnitIdCount()); - assertEquals("Child id list of location not available with read permissions", + Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getUnitIdCount(), + "Unit id list of location not available with read permissions"); + assertEquals( unitConfig.getLocationConfig().getChildIdCount(), - Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getChildIdCount()); + Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getChildIdCount(), + "Child id list of location not available with read permissions"); // test if unit configurations are still not available try { Registries.getUnitRegistry().getUnitConfigById(unitConfig.getLocationConfig().getUnitId(0)); } catch (NotAvailableException ex) { - assertTrue("Unit configuration cannot be seen even though other has read permissions on its location", false); + assertTrue(false, "Unit configuration cannot be seen even though other has read permissions on its location"); } // give only access permissions unitConfig.getPermissionConfigBuilder().getOtherPermissionBuilder().setAccess(true).setRead(false); Registries.getUnitRegistry().updateUnitConfig(unitConfig.build()).get(); - assertTrue("Location does not provide read permission while providing access permissions", Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getPermissionConfig().getOtherPermission().getRead()); + assertTrue(Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getPermissionConfig().getOtherPermission().getRead(), "Location does not provide read permission while providing access permissions"); // test if unit ids and child ids are back - assertEquals("Unit id list of location not available with access permissions", + assertEquals( unitConfig.getLocationConfig().getUnitIdCount(), - Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getUnitIdCount()); - assertEquals("Child id list of location not available with access permissions", + Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getUnitIdCount(), + "Unit id list of location not available with access permissions"); + assertEquals( unitConfig.getLocationConfig().getChildIdCount(), - Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getChildIdCount()); + Registries.getUnitRegistry().getUnitConfigById(unitConfig.getId()).getLocationConfig().getChildIdCount(), + "Child id list of location not available with access permissions"); // test if unit configurations are still not available try { Registries.getUnitRegistry().getUnitConfigById(unitConfig.getLocationConfig().getUnitId(0)); } catch (NotAvailableException ex) { - assertTrue("Unit configuration cannot be seen even though other has read and access permissions on its location", false); + assertTrue(false, "Unit configuration cannot be seen even though other has read and access permissions on its location"); } } @@ -180,6 +183,6 @@ public void testRequestingAuthorizationToken() throws Exception { final AuthorizationToken decrypted = EncryptionHelper.decryptSymmetric( ByteString.copyFrom(Base64.getDecoder().decode(token)), AuthenticatedServerManager.getInstance().getServiceServerSecretKey(), AuthorizationToken.class); - assertEquals("Returned authorization token does not match", authorizationToken.build(), decrypted); + assertEquals(authorizationToken.build(), decrypted, "Returned authorization token does not match"); } } diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestBoundToDeviceFlag.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestBoundToDeviceFlag.java index 1d04e9a332..8b84368c47 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestBoundToDeviceFlag.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestBoundToDeviceFlag.java @@ -22,6 +22,7 @@ * #L% */ +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.registry.remote.Registries; @@ -36,8 +37,8 @@ import java.util.Random; import java.util.concurrent.ExecutionException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.*; /** * @@ -59,10 +60,8 @@ public class TestBoundToDeviceFlag extends AbstractBCORegistryTest { private Pose poseLightTwo; private Pose poseLightThree; - @Override - public void setUp() throws Exception { - super.setUp(); - + @BeforeEach + public void setupTest() throws Exception { try { deviceClass = Registries.getClassRegistry().registerDeviceClass(generateDeviceClass("Label", "Product Number", "Company", unitTypes)).get(); PlacementConfig placement = generatePlacementConfig(); @@ -149,7 +148,7 @@ public void testDeviceBoundAndUnitsNotBound() throws Exception { logger.info("testDeviceBoundAndUnitsNotBound"); // change bound to host flag in device - Registries.getUnitRegistry().updateUnitConfig(deviceUnitConfig.toBuilder().setBoundToUnitHost(true).build()).get(); + Registries.getUnitRegistry(true).updateUnitConfig(deviceUnitConfig.toBuilder().setBoundToUnitHost(true).build()).get(); getUpdatedConfigs(); assertTrue(deviceUnitConfig.getBoundToUnitHost()); @@ -203,14 +202,12 @@ public void testDeviceNotBoundAndUnitsBound() throws Exception { assertEquals(newPoseLightOne, poseDevice); assertEquals(newPoseLightOne, poseLightTwo); assertEquals(oldPoseLightThree, poseLightThree); - assertTrue(!poseLightThree.equals(poseLightOne)); + assertNotEquals(poseLightThree, poseLightOne); } /** * Test what happens when the flag is set in the device and * its unit. - * - * @throws Exception */ @Test @Timeout(10) diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestWaitUntilReady.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestWaitUntilReady.java index c9458342dc..8c3f794e2b 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestWaitUntilReady.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/TestWaitUntilReady.java @@ -23,7 +23,7 @@ */ import org.junit.jupiter.api.AfterAll; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -125,7 +125,7 @@ public void testWaitUntilReady() throws Exception { Registries.getUnitRegistry().addDataObserver((DataProvider source, UnitRegistryData data) -> { if (waitedUntilReady) { - Assert.assertTrue("Received an update even though waitUntilReady has returned!", false); + assertTrue(false, "Received an update even though waitUntilReady has returned!"); } }); @@ -154,7 +154,10 @@ public void testWaitUntilReady() throws Exception { // System.out.println("wait"); Registries.waitUntilReady(); // System.out.println("continue"); - Assert.assertTrue("Test failed because registry is not consistent after wait until done returned.", Registries.getUnitRegistry().getData().getUnitConfigRegistryConsistent()); + assertTrue( + Registries.getUnitRegistry().getData().getUnitConfigRegistryConsistent(), + "Test failed because registry is not consistent after wait until done returned." + ); long time = System.currentTimeMillis(); try { // registrationFuture.get(); @@ -162,7 +165,7 @@ public void testWaitUntilReady() throws Exception { LOGGER.info("Get after waitUntil ready took: " + (System.currentTimeMillis() - time) + "ms"); } catch (TimeoutException ex) { LOGGER.warn("Get after waitUntil ready took: " + (System.currentTimeMillis() - time) + "ms"); - Assert.assertTrue("Test failed because registration result is not available", false); + assertTrue(false, "Test failed because registration result is not available"); } waitedUntilReady = true; } diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/UnitGroupRegistryTest.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/UnitGroupRegistryTest.java index b1b2eff2a2..587a2fa292 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/UnitGroupRegistryTest.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/UnitGroupRegistryTest.java @@ -22,6 +22,7 @@ * #L% */ +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.openbase.bco.registry.mock.MockRegistry; @@ -34,7 +35,7 @@ import java.util.Locale; -import static org.junit.Assert.assertEquals; + /** * @author Tamino Huxohl @@ -64,6 +65,6 @@ public void testPlacementChange() throws Exception { UnitConfig registeredGroup = Registries.getUnitRegistry().registerUnitConfig(unitConfig.build()).get(); - assertEquals("BoundingBox was not generated!", registeredGroup.getPlacementConfig().getShape().getBoundingBox(), MockRegistry.DEFAULT_BOUNDING_BOX); + assertEquals(registeredGroup.getPlacementConfig().getShape().getBoundingBox(), MockRegistry.DEFAULT_BOUNDING_BOX, "BoundingBox was not generated!"); } } diff --git a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/VirtualRegistrySyncTest.java b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/VirtualRegistrySyncTest.java index 71285ac2e0..3fdf23714d 100644 --- a/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/VirtualRegistrySyncTest.java +++ b/module/registry/unit-registry/test/src/test/java/org/openbase/bco/registry/unit/test/VirtualRegistrySyncTest.java @@ -48,7 +48,7 @@ public class VirtualRegistrySyncTest { // // private static AuthenticatorController authenticatorController; // -// @BeforeClass +// @BeforeAll // public static void setUpClass() throws Exception { // try { // JPService.setupJUnitTestMode(); @@ -159,7 +159,7 @@ public class VirtualRegistrySyncTest { // } // } // -// @AfterClass +// @AfterAll // public static void tearDownClass() throws Exception { // try { // if (unitRegistry != null) { diff --git a/module/registry/util/src/test/java/org/openbase/bco/registry/mock/RemoteTest.java b/module/registry/util/src/test/java/org/openbase/bco/registry/mock/RemoteTest.java index feae168132..2a74f4d4d3 100644 --- a/module/registry/util/src/test/java/org/openbase/bco/registry/mock/RemoteTest.java +++ b/module/registry/util/src/test/java/org/openbase/bco/registry/mock/RemoteTest.java @@ -23,7 +23,7 @@ */ import org.junit.jupiter.api.*; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.openbase.bco.registry.clazz.remote.ClassRegistryRemote; @@ -33,8 +33,6 @@ import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState; import org.slf4j.LoggerFactory; -import java.util.concurrent.TimeUnit; - /** * * @author Tamino Huxohl @@ -87,7 +85,7 @@ public void testRestartingDeviceRegistryRemotes() throws Exception { deviceRemoteToggle.deactivate(); deviceRemoteToggle.waitForConnectionState(ConnectionState.State.DISCONNECTED); - assertEquals("Remote has been shutdown with another in the [" + i + "]s try!", ConnectionStateType.ConnectionState.State.CONNECTED, deviceRemoteAlwaysOn.getConnectionState()); + assertEquals(ConnectionStateType.ConnectionState.State.CONNECTED, deviceRemoteAlwaysOn.getConnectionState(), "Remote has been shutdown with another in the [" + i + "]s try!"); deviceRemoteAlwaysOn.requestData().get(); deviceRemoteToggle.activate(); diff --git a/versions.properties b/versions.properties index d6c8610e0e..b287925b0a 100644 --- a/versions.properties +++ b/versions.properties @@ -9,6 +9,8 @@ version.com.graphql-java-kickstart..graphql-spring-boot-starter=12.0.1-SNAPSHOT +version.io.quarkus..quarkus-junit4-mock=2.9.1.Final + ## unused version.junit.jupiter=[5.8,5.9-alpha) @@ -111,6 +113,10 @@ version.com.google.guava..guava=28.0-jre ## # available=31.0.1-android ## # available=31.0.1-jre +version.org.openbase..jul.transformation=3.2-SNAPSHOT + +version.org.testcontainers..junit-jupiter=1.17.2 + version.org.testcontainers..testcontainers=1.17.1 version.org.springframework.boot..spring-boot-starter-webflux=2.6.3 @@ -204,3 +210,5 @@ version.org.openbase..jul.visual.swing=3.2-SNAPSHOT ## # available=3.0.0 ## # available=3.0.1 ## # available=3.0.2 + +version.rxjava2.rxjava=2.2.21