brooklyn-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From aleds...@apache.org
Subject [5/8] brooklyn-server git commit: Improve TestEffector etc tests
Date Tue, 09 Aug 2016 19:44:39 GMT
Improve TestEffector etc tests

- Make code more concise and clearer
- Make it a lot faster by tweaking timeouts


Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/04a561cb
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/04a561cb
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/04a561cb

Branch: refs/heads/master
Commit: 04a561cbceab459d81451405454456324429a54e
Parents: e1c310f
Author: Aled Sage <aled.sage@gmail.com>
Authored: Tue Jul 26 13:40:14 2016 +0100
Committer: Aled Sage <aled.sage@gmail.com>
Committed: Wed Aug 3 20:56:01 2016 +0100

----------------------------------------------------------------------
 .../framework/TargetableTestComponentImpl.java  |  12 ++
 .../test/framework/TestEffectorImpl.java        |   9 +-
 .../framework/TestEndpointReachableImpl.java    |   9 +-
 .../test/framework/TestHttpCallImpl.java        |   9 +-
 .../brooklyn/test/framework/TestSensorImpl.java |   9 +-
 .../test/framework/TestSshCommandImpl.java      |   5 -
 .../test/framework/TestEffectorTest.java        |  96 ++++++-------
 .../framework/TestFrameworkAssertionsTest.java  |   8 +-
 .../brooklyn/test/framework/TestSensorTest.java | 142 +++++++------------
 9 files changed, 128 insertions(+), 171 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/main/java/org/apache/brooklyn/test/framework/TargetableTestComponentImpl.java
----------------------------------------------------------------------
diff --git a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TargetableTestComponentImpl.java
b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TargetableTestComponentImpl.java
index 7c011c4..fcfecab 100644
--- a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TargetableTestComponentImpl.java
+++ b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TargetableTestComponentImpl.java
@@ -19,6 +19,7 @@
 package org.apache.brooklyn.test.framework;
 
 import static com.google.common.base.Preconditions.checkNotNull;
+import static org.apache.brooklyn.core.entity.lifecycle.ServiceStateLogic.setExpectedState;
 
 import java.util.concurrent.Callable;
 import java.util.concurrent.atomic.AtomicReference;
@@ -29,6 +30,7 @@ import org.apache.brooklyn.api.mgmt.Task;
 import org.apache.brooklyn.camp.brooklyn.spi.dsl.methods.DslComponent;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.entity.AbstractEntity;
+import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.util.core.task.Tasks;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.repeat.Repeater;
@@ -116,4 +118,14 @@ public abstract class TargetableTestComponentImpl extends AbstractEntity
impleme
     protected <T> T getRequiredConfig(ConfigKey<T> key) {
         return checkNotNull(config().get(key), "config %s must not be null", key);
     }
+
+    protected void setUpAndRunState(boolean up, Lifecycle status) {
+        if (up) {
+            sensors().set(SERVICE_UP, up);
+            setExpectedState(this, status);
+        } else {
+            setExpectedState(this, status);
+            sensors().set(SERVICE_UP, up);
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEffectorImpl.java
----------------------------------------------------------------------
diff --git a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEffectorImpl.java
b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEffectorImpl.java
index 1cdf473..fc62aa3 100644
--- a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEffectorImpl.java
+++ b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEffectorImpl.java
@@ -85,11 +85,9 @@ public class TestEffectorImpl extends TargetableTestComponentImpl implements
Tes
 
             //Add result of effector to sensor
             sensors().set(EFFECTOR_RESULT, effectorResult);
-            sensors().set(SERVICE_UP, true);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
+            setUpAndRunState(true, Lifecycle.RUNNING);
         } catch (Throwable t) {
-            sensors().set(SERVICE_UP, false);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
+            setUpAndRunState(false, Lifecycle.ON_FIRE);
             throw Exceptions.propagate(t);
         }
     }
@@ -98,8 +96,7 @@ public class TestEffectorImpl extends TargetableTestComponentImpl implements
Tes
      * {@inheritDoc}
      */
     public void stop() {
-        ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
-        sensors().set(SERVICE_UP, false);
+        setUpAndRunState(false, Lifecycle.STOPPED);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEndpointReachableImpl.java
----------------------------------------------------------------------
diff --git a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEndpointReachableImpl.java
b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEndpointReachableImpl.java
index 913be27..7f4c6fe 100644
--- a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEndpointReachableImpl.java
+++ b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestEndpointReachableImpl.java
@@ -108,13 +108,11 @@ public class TestEndpointReachableImpl extends TargetableTestComponentImpl
imple
                     Asserts.assertNotNull(val);
                     assertSucceeds(assertions, val);
                 }});
-            sensors().set(Attributes.SERVICE_UP, true);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
+            setUpAndRunState(true, Lifecycle.RUNNING);
 
         } catch (Throwable t) {
             LOG.info("{} [{}] test failed", this, endpoint != null ? endpoint : endpointSensor);
-            sensors().set(Attributes.SERVICE_UP, false);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
+            setUpAndRunState(false, Lifecycle.ON_FIRE);
             throw Exceptions.propagate(t);
         }
     }
@@ -207,8 +205,7 @@ public class TestEndpointReachableImpl extends TargetableTestComponentImpl
imple
      * {@inheritDoc}
      */
     public void stop() {
-        ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
-        sensors().set(Attributes.SERVICE_UP, false);
+        setUpAndRunState(false, Lifecycle.STOPPED);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestHttpCallImpl.java
----------------------------------------------------------------------
diff --git a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestHttpCallImpl.java
b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestHttpCallImpl.java
index 45b04d0..cb1c313 100644
--- a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestHttpCallImpl.java
+++ b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestHttpCallImpl.java
@@ -61,13 +61,11 @@ public class TestHttpCallImpl extends TargetableTestComponentImpl implements
Tes
 
         try {
             doRequestAndCheckAssertions(ImmutableMap.of("timeout", timeout), assertions,
target, url);
-            sensors().set(Attributes.SERVICE_UP, true);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
+            setUpAndRunState(true, Lifecycle.RUNNING);
 
         } catch (Throwable t) {
             LOG.info("{} Url [{}] test failed", this, url);
-            sensors().set(Attributes.SERVICE_UP, false);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
+            setUpAndRunState(false, Lifecycle.ON_FIRE);
             throw Exceptions.propagate(t);
         }
     }
@@ -107,8 +105,7 @@ public class TestHttpCallImpl extends TargetableTestComponentImpl implements
Tes
      * {@inheritDoc}
      */
     public void stop() {
-        ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
-        sensors().set(Attributes.SERVICE_UP, false);
+        setUpAndRunState(false, Lifecycle.STOPPED);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSensorImpl.java
----------------------------------------------------------------------
diff --git a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSensorImpl.java
b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSensorImpl.java
index df50064..8952f62 100644
--- a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSensorImpl.java
+++ b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSensorImpl.java
@@ -71,12 +71,10 @@ public class TestSensorImpl extends TargetableTestComponentImpl implements
TestS
                 }
             });
 
-            sensors().set(SERVICE_UP, true);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
+            setUpAndRunState(true, Lifecycle.RUNNING);
         } catch (Throwable t) {
             LOG.debug("Sensor [{}] test failed", sensor);
-            sensors().set(SERVICE_UP, false);
-            ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
+            setUpAndRunState(false, Lifecycle.ON_FIRE);
             throw Exceptions.propagate(t);
         }
     }
@@ -86,8 +84,7 @@ public class TestSensorImpl extends TargetableTestComponentImpl implements
TestS
      * {@inheritDoc}
      */
     public void stop() {
-        ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
-        sensors().set(SERVICE_UP, false);
+        setUpAndRunState(false, Lifecycle.STOPPED);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSshCommandImpl.java
----------------------------------------------------------------------
diff --git a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSshCommandImpl.java
b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSshCommandImpl.java
index 19f8589..be7098a 100644
--- a/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSshCommandImpl.java
+++ b/test-framework/src/main/java/org/apache/brooklyn/test/framework/TestSshCommandImpl.java
@@ -89,11 +89,6 @@ public class TestSshCommandImpl extends TargetableTestComponentImpl implements
T
         execute();
     }
 
-    private void setUpAndRunState(boolean up, Lifecycle status) {
-        sensors().set(SERVICE_UP, up);
-        setExpectedState(this, status);
-    }
-
     private static class Result {
         int exitCode;
         String stdout;

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestEffectorTest.java
----------------------------------------------------------------------
diff --git a/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestEffectorTest.java
b/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestEffectorTest.java
index c5ccafd..b7a341b 100644
--- a/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestEffectorTest.java
+++ b/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestEffectorTest.java
@@ -25,60 +25,52 @@ import static org.assertj.core.api.Assertions.assertThat;
 import java.util.List;
 import java.util.Map;
 
+import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.core.entity.Attributes;
 import org.apache.brooklyn.core.entity.Entities;
+import org.apache.brooklyn.core.entity.EntityAsserts;
+import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.test.framework.entity.TestEntity;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
 import org.apache.brooklyn.util.text.Identifiers;
-import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
+import com.google.common.base.Predicates;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
 
-public class TestEffectorTest {
+public class TestEffectorTest extends BrooklynAppUnitTestSupport {
 
-    private TestApplication app;
-    private ManagementContext managementContext;
-    @SuppressWarnings("unused")
-    private LocalhostMachineProvisioningLocation loc;
+    private List<Location> locs = ImmutableList.of();
     private String testId;
 
-    @BeforeMethod
-    public void setup() {
-        testId = Identifiers.makeRandomId(8);
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        managementContext = app.getManagementContext();
-
-        loc = managementContext.getLocationManager()
-                .createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
-                .configure("name", testId));
-
-    }
-
+    private TestCase testCase;
+    private TestEntity testEntity;
 
-    @AfterMethod(alwaysRun = true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        testId = Identifiers.makeRandomId(8);
+        testCase = app.createAndManageChild(EntitySpec.create(TestCase.class));
+        testEntity = testCase.addChild(EntitySpec.create(TestEntity.class));
     }
 
-
     @Test
-    public void testSimpleEffector() {
-        final TestCase testCase = app.createAndManageChild(EntitySpec.create(TestCase.class));
-        final TestEntity testEntity = testCase.addChild(EntitySpec.create(TestEntity.class));
-
-
+    public void testSimpleEffector() throws Exception {
         final TestEffector testEffector = testCase.addChild(EntitySpec.create(TestEffector.class)
                 .configure(TestEffector.TARGET_ENTITY, testEntity)
                 .configure(TestEffector.EFFECTOR_NAME, "simpleEffector"));
 
-        app.start(ImmutableList.of(app.newSimulatedLocation()));
+        app.start(locs);
 
         assertThat(testEntity.sensors().get(TestEntity.SIMPLE_EFFECTOR_INVOKED)).isNotNull();
         assertThat(testEntity.sensors().get(TestEntity.SIMPLE_EFFECTOR_INVOKED)).isTrue();
@@ -87,10 +79,7 @@ public class TestEffectorTest {
     }
 
     @Test
-    public void testEffectorPositiveAssertions() {
-        final TestCase testCase = app.createAndManageChild(EntitySpec.create(TestCase.class));
-        final TestEntity testEntity = testCase.addChild(EntitySpec.create(TestEntity.class));
-
+    public void testEffectorPositiveAssertions() throws Exception {
         String stringToReturn = "Hello World!";
 
         Map<String, String> effectorParams = ImmutableMap.of("stringToReturn", stringToReturn);
@@ -106,17 +95,14 @@ public class TestEffectorTest {
                 .configure(TestEffector.EFFECTOR_PARAMS, effectorParams)
                 .configure(TestEffector.ASSERTIONS, assertions));
 
-        app.start(ImmutableList.of(app.newSimulatedLocation()));
+        app.start(locs);
 
         assertThat(testEffector.sensors().get(TestEffector.EFFECTOR_RESULT)).isEqualTo(stringToReturn);
         assertThat(testEffector.sensors().get(SERVICE_UP)).isTrue().withFailMessage("Service
should be up");
     }
 
     @Test
-    public void testEffectorNegativeAssertions() {
-        final TestCase testCase = app.createAndManageChild(EntitySpec.create(TestCase.class));
-        final TestEntity testEntity = testCase.addChild(EntitySpec.create(TestEntity.class));
-
+    public void testEffectorNegativeAssertions() throws Exception {
         String stringToReturn = "Goodbye World!";
 
         Map<String, String> effectorParams = ImmutableMap.of("stringToReturn", stringToReturn);
@@ -132,21 +118,12 @@ public class TestEffectorTest {
                 .configure(TestEffector.EFFECTOR_PARAMS, effectorParams)
                 .configure(TestEffector.ASSERTIONS, assertions));
 
-        try {
-            app.start(ImmutableList.of(app.newSimulatedLocation()));
-            Asserts.shouldHaveFailedPreviously();
-        } catch (Throwable throwable) {
-            Asserts.expectedFailureOfType(throwable, AssertionError.class);
-        }
-
+        assertStartFails(app, AssertionError.class);
         assertThat(testEffector.sensors().get(SERVICE_UP)).isFalse().withFailMessage("Service
should not be up");
     }
 
     @Test
-    public void testComplexffector() {
-        final TestCase testCase = app.createAndManageChild(EntitySpec.create(TestCase.class));
-        final TestEntity testEntity = testCase.addChild(EntitySpec.create(TestEntity.class));
-
+    public void testComplexffector() throws Exception {
         final long expectedLongValue = System.currentTimeMillis();
         final boolean expectedBooleanValue = expectedLongValue % 2 == 0;
 
@@ -158,7 +135,7 @@ public class TestEffectorTest {
                         "booleanValue", expectedBooleanValue,
                         "longValue", expectedLongValue)));
 
-        app.start(ImmutableList.of(app.newSimulatedLocation()));
+        app.start(locs);
 
         assertThat(testEntity.sensors().get(TestEntity.SIMPLE_EFFECTOR_INVOKED)).isNull();
         assertThat(testEntity.sensors().get(TestEntity.COMPLEX_EFFECTOR_INVOKED)).isNotNull();
@@ -183,4 +160,19 @@ public class TestEffectorTest {
 
     }
 
+    protected void assertStartFails(TestApplication app, Class<? extends Throwable>
clazz) {
+        try {
+            app.start(locs);
+            Asserts.shouldHaveFailedPreviously();
+        } catch (PropagatedRuntimeException pre) {
+            final Throwable throwable = Exceptions.getFirstThrowableOfType(pre, clazz);
+            assertThat(throwable).isNotNull().as("A "+clazz.getSimpleName()+" should have
been thrown");
+        } catch (Throwable throwable) {
+            Asserts.expectedFailureOfType(throwable, AssertionError.class);
+        }
+        
+        Entity entity = Iterables.find(Entities.descendantsWithoutSelf(app), Predicates.instanceOf(TestEffector.class));
+        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL,
Lifecycle.ON_FIRE);
+        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, false);
+    }
 }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestFrameworkAssertionsTest.java
----------------------------------------------------------------------
diff --git a/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestFrameworkAssertionsTest.java
b/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestFrameworkAssertionsTest.java
index f0c3157..c1ef79b 100644
--- a/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestFrameworkAssertionsTest.java
+++ b/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestFrameworkAssertionsTest.java
@@ -122,8 +122,12 @@ public class TestFrameworkAssertionsTest {
                 return data;
             }
         };
+        
+        // It should always try at least once, so we can use a very small timeout
+        Duration timeout = Duration.millis(1);
+        
         try {
-            TestFrameworkAssertions.checkAssertions(ImmutableMap.of("timeout", new Duration(2L,
TimeUnit.SECONDS)), assertions, Objects.toString(data), supplier);
+            TestFrameworkAssertions.checkAssertions(ImmutableMap.of("timeout", timeout),
assertions, Objects.toString(data), supplier);
             Asserts.shouldHaveFailedPreviously();
         } catch (AssertionError e) {
             Asserts.expectedFailureContains(e, Objects.toString(data), condition, expected.toString());
@@ -145,7 +149,7 @@ public class TestFrameworkAssertionsTest {
             }
         };
         try {
-            TestFrameworkAssertions.checkAssertions(ImmutableMap.of("timeout", new Duration(2L,
TimeUnit.SECONDS)), assertions, "anyTarget", supplier);
+            TestFrameworkAssertions.checkAssertions(ImmutableMap.of("timeout", Duration.millis(1)),
assertions, "anyTarget", supplier);
             Asserts.shouldHaveFailedPreviously();
         } catch (Throwable e) {
             Asserts.expectedFailureOfType(e, AssertionError.class);

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/04a561cb/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestSensorTest.java
----------------------------------------------------------------------
diff --git a/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestSensorTest.java
b/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestSensorTest.java
index bb376cf..34bbd73 100644
--- a/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestSensorTest.java
+++ b/test-framework/src/test/java/org/apache/brooklyn/test/framework/TestSensorTest.java
@@ -19,54 +19,52 @@
 
 package org.apache.brooklyn.test.framework;
 
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.entity.Attributes;
 import org.apache.brooklyn.core.entity.Entities;
+import org.apache.brooklyn.core.entity.EntityAsserts;
+import org.apache.brooklyn.core.entity.lifecycle.Lifecycle;
 import org.apache.brooklyn.core.sensor.AttributeSensorAndConfigKey;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestApplication;
-import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
+import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.exceptions.Exceptions;
 import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
 import org.apache.brooklyn.util.text.Identifiers;
+import org.apache.brooklyn.util.time.Duration;
 import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import static org.assertj.core.api.Assertions.assertThat;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
 
-public class TestSensorTest {
+public class TestSensorTest extends BrooklynAppUnitTestSupport {
 
     private static final AttributeSensorAndConfigKey<Boolean, Boolean> BOOLEAN_SENSOR
= ConfigKeys.newSensorAndConfigKey(Boolean.class, "boolean-sensor", "Boolean Sensor");
     private static final AttributeSensorAndConfigKey<String, String> STRING_SENSOR
= ConfigKeys.newSensorAndConfigKey(String.class, "string-sensor", "String Sensor");
     private static final AttributeSensorAndConfigKey<Integer, Integer> INTEGER_SENSOR
= ConfigKeys.newIntegerSensorAndConfigKey("integer-sensor", "Integer Sensor");
     private static final AttributeSensorAndConfigKey<Object, Object> OBJECT_SENSOR
= ConfigKeys.newSensorAndConfigKey(Object.class, "object-sensor", "Object Sensor");
 
-    private TestApplication app;
-    private ManagementContext managementContext;
-    private LocalhostMachineProvisioningLocation loc;
+    private List<Location> locs = ImmutableList.of();
     private String testId;
 
-    @BeforeMethod
-    public void setup() {
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
         testId = Identifiers.makeRandomId(8);
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        managementContext = app.getManagementContext();
-        loc = managementContext.getLocationManager().createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
-                .configure("name", testId));
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
     }
 
     @Test
@@ -98,53 +96,34 @@ public class TestSensorTest {
         //Set STRING sensor to random string
         app.sensors().set(STRING_SENSOR, testId);
 
-        app.start(ImmutableList.of(loc));
+        app.start(locs);
 
     }
 
     @Test
     public void testAssertEqualFailure() {
-        boolean booleanAssertFailed = false;
-
         //Add Sensor Test for BOOLEAN sensor
         app.createAndManageChild(EntitySpec.create(TestSensor.class)
+                .configure(TestSensor.TIMEOUT, Duration.millis(10))
                 .configure(TestSensor.TARGET_ENTITY, app)
                 .configure(TestSensor.SENSOR_NAME, BOOLEAN_SENSOR.getName())
                 .configure(TestSensor.ASSERTIONS, newMapAssertion("equals", true)));
 
         //Set BOOLEAN Sensor to false
         app.sensors().set(BOOLEAN_SENSOR, Boolean.FALSE);
-
-        try {
-            app.start(ImmutableList.of(loc));
-        } catch (final PropagatedRuntimeException pre) {
-            final AssertionError assertionError = Exceptions.getFirstThrowableOfType(pre,
AssertionError.class);
-            assertThat(assertionError).isNotNull();
-            booleanAssertFailed = true;
-        } finally {
-            assertThat(booleanAssertFailed).isTrue();
-        }
+        assertStartFails(app, AssertionError.class);
     }
 
     @Test
     public void testAssertEqualOnNullSensor() {
-        boolean booleanAssertFailed = false;
-
         //Add Sensor Test for BOOLEAN sensor
         app.createAndManageChild(EntitySpec.create(TestSensor.class)
+                .configure(TestSensor.TIMEOUT, Duration.millis(10))
                 .configure(TestSensor.TARGET_ENTITY, app)
                 .configure(TestSensor.SENSOR_NAME, BOOLEAN_SENSOR.getName())
                 .configure(TestSensor.ASSERTIONS, newListAssertion("equals", false)));
 
-        try {
-            app.start(ImmutableList.of(loc));
-        } catch (final PropagatedRuntimeException pre) {
-            final AssertionError assertionError = Exceptions.getFirstThrowableOfType(pre,
AssertionError.class);
-            assertThat(assertionError).isNotNull().as("An assertion error should have been
thrown");
-            booleanAssertFailed = true;
-        } finally {
-            assertThat(booleanAssertFailed).isTrue().as("Equals assert should have failed
as the sensor is NULL");
-        }
+        assertStartFails(app, AssertionError.class);
     }
 
     @Test
@@ -163,34 +142,23 @@ public class TestSensorTest {
         //Set STRING sensor to random string
         app.sensors().set(STRING_SENSOR, testId);
 
-        app.start(ImmutableList.of(loc));
+        app.start(locs);
 
     }
 
 
     @Test
     public void testAssertNullFail() {
-        boolean sensorTestFail = false;
         //Add Sensor Test for STRING sensor
         app.createAndManageChild(EntitySpec.create(TestSensor.class)
+                .configure(TestSensor.TIMEOUT, Duration.millis(10))
                 .configure(TestSensor.TARGET_ENTITY, app)
                 .configure(TestSensor.SENSOR_NAME, STRING_SENSOR.getName())
                 .configure(TestSensor.ASSERTIONS, newMapAssertion("isNull", true)));
 
         //Set STRING sensor to random string
         app.sensors().set(STRING_SENSOR, testId);
-
-
-        try {
-            app.start(ImmutableList.of(loc));
-        } catch (final PropagatedRuntimeException pre) {
-            final AssertionError assertionError = Exceptions.getFirstThrowableOfType(pre,
AssertionError.class);
-            assertThat(assertionError).isNotNull().as("An assertion error should have been
thrown");
-            sensorTestFail = true;
-        } finally {
-            assertThat(sensorTestFail).isTrue().as("isNull assert should have failed as the
sensor has been set");
-        }
-
+        assertStartFails(app, AssertionError.class);
     }
 
     @Test
@@ -213,51 +181,35 @@ public class TestSensorTest {
         app.sensors().set(BOOLEAN_SENSOR, true);
 
 
-        app.start(ImmutableList.of(loc));
+        app.start(locs);
     }
 
     @Test
-    public void testAssertmatchesFail() {
-        boolean sensorTestFail = false;
+    public void testAssertMatchesFail() {
         final String sensorValue = String.format("%s%s%s", Identifiers.makeRandomId(8), System.currentTimeMillis(),
Identifiers.makeRandomId(8));
 
         //Add Sensor Test for STRING sensor
         app.createAndManageChild(EntitySpec.create(TestSensor.class)
+                .configure(TestSensor.TIMEOUT, Duration.millis(10))
                 .configure(TestSensor.TARGET_ENTITY, app)
                 .configure(TestSensor.SENSOR_NAME, STRING_SENSOR.getName())
                 .configure(TestSensor.ASSERTIONS, newListAssertion("matches", String.format(".*%s.*",
Identifiers.makeRandomId(8)))));
 
         //Set STRING sensor
         app.sensors().set(STRING_SENSOR, sensorValue);
-        try {
-            app.start(ImmutableList.of(loc));
-        } catch (final PropagatedRuntimeException pre) {
-            final AssertionError assertionError = Exceptions.getFirstThrowableOfType(pre,
AssertionError.class);
-            assertThat(assertionError).isNotNull().as("An assertion error should have been
thrown");
-            sensorTestFail = true;
-        } finally {
-            assertThat(sensorTestFail).isTrue().as("matches assert should have failed");
-        }
+        assertStartFails(app, AssertionError.class);
     }
 
     @Test
-    public void testAssertmatchesOnNullSensor() {
-        boolean sensorTestFail = false;
+    public void testAssertMatchesOnNullSensor() {
         //Add Sensor Test for STRING sensor
         app.createAndManageChild(EntitySpec.create(TestSensor.class)
+                .configure(TestSensor.TIMEOUT, Duration.millis(10))
                 .configure(TestSensor.TARGET_ENTITY, app)
                 .configure(TestSensor.SENSOR_NAME, STRING_SENSOR.getName())
                 .configure(TestSensor.ASSERTIONS, newMapAssertion("matches", String.format(".*%s.*",
Identifiers.makeRandomId(8)))));
 
-        try {
-            app.start(ImmutableList.of(loc));
-        } catch (final PropagatedRuntimeException pre) {
-            final AssertionError assertionError = Exceptions.getFirstThrowableOfType(pre,
AssertionError.class);
-            assertThat(assertionError).isNotNull().as("An assertion error should have been
thrown");
-            sensorTestFail = true;
-        } finally {
-            assertThat(sensorTestFail).isTrue().as("matches assert should have failed");
-        }
+        assertStartFails(app, AssertionError.class);
     }
 
 
@@ -271,10 +223,24 @@ public class TestSensorTest {
 
         app.sensors().set(OBJECT_SENSOR, new TestObject());
 
-        app.start(ImmutableList.of(loc));
+        app.start(locs);
 
     }
 
+    protected void assertStartFails(TestApplication app, Class<? extends Throwable>
clazz) {
+        try {
+            app.start(locs);
+            Asserts.shouldHaveFailedPreviously();
+        } catch (final PropagatedRuntimeException pre) {
+            final Throwable throwable = Exceptions.getFirstThrowableOfType(pre, clazz);
+            assertThat(throwable).isNotNull().as("A "+clazz.getSimpleName()+" should have
been thrown");
+        }
+        
+        Entity entity = Iterables.find(Entities.descendantsWithoutSelf(app), Predicates.instanceOf(TestSensor.class));
+        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL,
Lifecycle.ON_FIRE);
+        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, false);
+    }
+    
     private List<Map<String, Object>> newListAssertion(final String assertionKey,
final Object assertionValue) {
         final List<Map<String, Object>> result = new ArrayList<>();
         result.add(ImmutableMap.<String, Object>of(assertionKey, assertionValue));


Mime
View raw message