brooklyn-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From drigod...@apache.org
Subject [3/5] brooklyn-server git commit: Rewrite tests: don’t rely on entity constructors
Date Wed, 17 May 2017 13:43:28 GMT
Rewrite tests: don’t rely on entity constructors


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

Branch: refs/heads/master
Commit: 9a83a59858a7f89a6e392f0b4fa0d6dee6280855
Parents: 2a39400
Author: Aled Sage <aled.sage@gmail.com>
Authored: Mon May 15 08:07:14 2017 +0100
Committer: Aled Sage <aled.sage@gmail.com>
Committed: Mon May 15 13:49:26 2017 +0100

----------------------------------------------------------------------
 .../brooklyn/core/entity/AttributeTest.java     |  31 +-
 .../brooklyn/core/entity/EntitySpecTest.java    |   2 +-
 .../drivers/BasicEntityDriverManagerTest.java   |  33 +--
 .../drivers/EntityDriverRegistryTest.java       |  35 +--
 .../ReflectiveEntityDriverFactoryTest.java      |  63 ++--
 .../RegistryEntityDriverFactoryTest.java        |  31 +-
 .../proxying/InternalEntityFactoryTest.java     |  32 ++-
 .../core/mgmt/osgi/OsgiStandaloneTest.java      |   2 +-
 .../mgmt/osgi/OsgiVersionMoreEntityTest.java    |  28 +-
 .../brooklyn/core/test/entity/TestEntity.java   |   4 +
 .../core/test/entity/TestEntityImpl.java        |  14 +
 .../YamlRollingTimeWindowMeanEnricherTest.java  |  23 +-
 .../brooklyn/entity/group/DynamicGroupTest.java | 285 +++++++++++--------
 .../AbstractFollowTheSunPolicyTest.java         |  42 ++-
 .../followthesun/FollowTheSunModelTest.java     |  43 +--
 .../AbstractLoadBalancingPolicyTest.java        |  19 +-
 .../loadbalancing/LoadBalancingModelTest.java   |  28 +-
 .../LoadBalancingPolicyConcurrencyTest.java     |   8 +-
 .../loadbalancing/MockItemEntityImpl.java       |   5 +-
 .../java/org/apache/brooklyn/cli/CliTest.java   |  18 +-
 .../base/SoftwareProcessEntityTest.java         |   5 +-
 .../MachineLifecycleEffectorTasksTest.java      |  16 +-
 22 files changed, 419 insertions(+), 348 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/entity/AttributeTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/entity/AttributeTest.java b/core/src/test/java/org/apache/brooklyn/core/entity/AttributeTest.java
index 8c4c3a0..e4e5699 100644
--- a/core/src/test/java/org/apache/brooklyn/core/entity/AttributeTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/entity/AttributeTest.java
@@ -21,46 +21,47 @@ package org.apache.brooklyn.core.entity;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertNull;
 
+import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.core.sensor.BasicAttributeSensor;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.core.test.entity.TestEntityImpl;
-import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-public class AttributeTest {
+public class AttributeTest extends BrooklynAppUnitTestSupport {
     static AttributeSensor<String> COLOR = new BasicAttributeSensor<String>(String.class, "my.color");
 
-    TestEntityImpl e;
+    TestEntity entity;
+    TestEntityImpl entityImpl;
     
     @BeforeMethod(alwaysRun=true)
+    @Override
     public void setUp() throws Exception {
-        e = new TestEntityImpl();
-    }
-
-    @AfterMethod(alwaysRun = true)
-    public void tearDown(){
-        // nothing to tear down; entity was not managed (i.e. had no management context)
+        super.setUp();
+        entity = app.addChild(EntitySpec.create(TestEntity.class));
+        entityImpl = (TestEntityImpl) Entities.deproxy(entity);
     }
 
     @Test
     public void canGetAndSetAttribute() {
-        e.sensors().set(COLOR, "red");
-        assertEquals(e.getAttribute(COLOR), "red");
+        entity.sensors().set(COLOR, "red");
+        assertEquals(entity.getAttribute(COLOR), "red");
     }
     
     @Test
     public void missingAttributeIsNull() {
-        assertEquals(e.getAttribute(COLOR), null);
+        assertEquals(entity.getAttribute(COLOR), null);
     }
     
     @Test
     public void canGetAttributeByNameParts() {
         // Initially null
-        assertNull(e.getAttributeByNameParts(COLOR.getNameParts()));
+        assertNull(entityImpl.getAttributeByNameParts(COLOR.getNameParts()));
         
         // Once set, returns val
-        e.sensors().set(COLOR, "red");
-        assertEquals(e.getAttributeByNameParts(COLOR.getNameParts()), "red");
+        entity.sensors().set(COLOR, "red");
+        assertEquals(entityImpl.getAttributeByNameParts(COLOR.getNameParts()), "red");
     }
 }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/entity/EntitySpecTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/entity/EntitySpecTest.java b/core/src/test/java/org/apache/brooklyn/core/entity/EntitySpecTest.java
index fd693b4..fb84693 100644
--- a/core/src/test/java/org/apache/brooklyn/core/entity/EntitySpecTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/entity/EntitySpecTest.java
@@ -149,7 +149,7 @@ public class EntitySpecTest extends BrooklynAppUnitTestSupport {
 
     @Test
     public void testCallsConfigureAfterConstruction() throws Exception {
-        AbstractEntityLegacyTest.MyEntity entity = app.createAndManageChild(EntitySpec.create(AbstractEntityLegacyTest.MyEntity.class));
+        TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
 
         assertEquals(entity.getConfigureCount(), 1);
         assertEquals(entity.getConfigureDuringConstructionCount(), 0);

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/entity/drivers/BasicEntityDriverManagerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/BasicEntityDriverManagerTest.java b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/BasicEntityDriverManagerTest.java
index d42ccb9..589d199 100644
--- a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/BasicEntityDriverManagerTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/BasicEntityDriverManagerTest.java
@@ -20,53 +20,50 @@ package org.apache.brooklyn.core.entity.drivers;
 
 import static org.testng.Assert.assertTrue;
 
-import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
-import org.apache.brooklyn.core.entity.drivers.BasicEntityDriverManager;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactoryTest.MyDriver;
 import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactoryTest.MyDriverDependentEntity;
 import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactoryTest.MySshDriver;
 import org.apache.brooklyn.core.entity.drivers.RegistryEntityDriverFactoryTest.MyOtherSshDriver;
 import org.apache.brooklyn.core.location.SimulatedLocation;
-import org.testng.annotations.AfterMethod;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
 
-public class BasicEntityDriverManagerTest {
+public class BasicEntityDriverManagerTest extends BrooklynAppUnitTestSupport {
 
     private BasicEntityDriverManager manager;
     private SshMachineLocation sshLocation;
     private SimulatedLocation simulatedLocation;
-
-    @BeforeMethod
+    private MyDriverDependentEntity entity;
+    
+    @BeforeMethod(alwaysRun=true)
+    @Override
     public void setUp() throws Exception {
+        super.setUp();
         manager = new BasicEntityDriverManager();
-        sshLocation = new SshMachineLocation(MutableMap.of("address", "localhost"));
-        simulatedLocation = new SimulatedLocation();
+        sshLocation = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        simulatedLocation = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class));
+        entity = app.addChild(EntitySpec.create(MyDriverDependentEntity.class)
+                .configure(MyDriverDependentEntity.DRIVER_CLASS, MyDriver.class));
     }
 
-    @AfterMethod
-    public void tearDown(){
-        // nothing to tear down; no management context created
-    }
-    
     @Test
     public void testPrefersRegisteredDriver() throws Exception {
-        DriverDependentEntity<MyDriver> entity = new MyDriverDependentEntity<MyDriver>(MyDriver.class);
         manager.registerDriver(MyDriver.class, SshMachineLocation.class, MyOtherSshDriver.class);
         assertTrue(manager.build(entity, sshLocation) instanceof MyOtherSshDriver);
     }
     
     @Test
     public void testFallsBackToReflectiveDriver() throws Exception {
-        DriverDependentEntity<MyDriver> entity = new MyDriverDependentEntity<MyDriver>(MyDriver.class);
         assertTrue(manager.build(entity, sshLocation) instanceof MySshDriver);
     }
     
     @Test
     public void testRespectsLocationWhenDecidingOnDriver() throws Exception {
-        DriverDependentEntity<MyDriver> entity = new MyDriverDependentEntity<MyDriver>(MyDriver.class);
         manager.registerDriver(MyDriver.class, SimulatedLocation.class, MyOtherSshDriver.class);
         assertTrue(manager.build(entity, simulatedLocation) instanceof MyOtherSshDriver);
         assertTrue(manager.build(entity, sshLocation) instanceof MySshDriver);

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/entity/drivers/EntityDriverRegistryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/EntityDriverRegistryTest.java b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/EntityDriverRegistryTest.java
index 977d380..997ae05 100644
--- a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/EntityDriverRegistryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/EntityDriverRegistryTest.java
@@ -20,40 +20,35 @@ package org.apache.brooklyn.core.entity.drivers;
 
 import static org.testng.Assert.assertTrue;
 
-import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.Entities;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.drivers.EntityDriver;
+import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactoryTest.MyDriver;
 import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactoryTest.MyDriverDependentEntity;
 import org.apache.brooklyn.core.entity.drivers.RegistryEntityDriverFactoryTest.MyOtherSshDriver;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.testng.annotations.AfterMethod;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
 
-public class EntityDriverRegistryTest {
+public class EntityDriverRegistryTest extends BrooklynAppUnitTestSupport {
 
-    private ManagementContext managementContext;
     private SshMachineLocation sshLocation;
-
+    private MyDriverDependentEntity entity;
+    
     @BeforeMethod
     public void setUp() throws Exception {
-        managementContext = new LocalManagementContextForTests();
-        sshLocation = new SshMachineLocation(MutableMap.of("address", "localhost"));
-    }
-
-    @AfterMethod
-    public void tearDown(){
-        if (managementContext != null) Entities.destroyAll(managementContext);
+        super.setUp();
+        sshLocation = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        entity = app.addChild(EntitySpec.create(MyDriverDependentEntity.class)
+                .configure(MyDriverDependentEntity.DRIVER_CLASS, MyDriver.class));
     }
 
     @Test
     public void testInstantiatesRegisteredDriver() throws Exception {
-        managementContext.getEntityDriverManager().registerDriver(MyDriver.class, SshMachineLocation.class, MyOtherSshDriver.class);
-        DriverDependentEntity<MyDriver> entity = new MyDriverDependentEntity<MyDriver>(MyDriver.class);
-        MyDriver driver = managementContext.getEntityDriverManager().build(entity, sshLocation);
+        mgmt.getEntityDriverManager().registerDriver(MyDriver.class, SshMachineLocation.class, MyOtherSshDriver.class);
+        EntityDriver driver = mgmt.getEntityDriverManager().build(entity, sshLocation);
         assertTrue(driver instanceof MyOtherSshDriver);
     }
 }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/entity/drivers/ReflectiveEntityDriverFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/ReflectiveEntityDriverFactoryTest.java b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/ReflectiveEntityDriverFactoryTest.java
index 0c7dcd1..889447c 100644
--- a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/ReflectiveEntityDriverFactoryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/ReflectiveEntityDriverFactoryTest.java
@@ -18,46 +18,48 @@
  */
 package org.apache.brooklyn.core.entity.drivers;
 
-import org.apache.brooklyn.location.paas.PaasLocation;
-import org.apache.brooklyn.location.paas.TestPaasLocation;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
+import static org.testng.Assert.assertTrue;
+
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntityLocal;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
 import org.apache.brooklyn.api.entity.drivers.EntityDriver;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.entity.AbstractEntity;
-import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactory;
-import org.testng.annotations.AfterMethod;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.location.paas.PaasLocation;
+import org.apache.brooklyn.location.paas.TestPaasLocation;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-import static org.testng.Assert.assertTrue;
+import com.google.common.reflect.TypeToken;
 
-public class ReflectiveEntityDriverFactoryTest {
+public class ReflectiveEntityDriverFactoryTest extends BrooklynAppUnitTestSupport {
 
     private ReflectiveEntityDriverFactory factory;
     private SshMachineLocation sshLocation;
     private PaasLocation paasLocation;
-    private DriverDependentEntity<MyDriver> entity;
+    private MyDriverDependentEntity entity;
     
     @BeforeMethod
     public void setUp() throws Exception {
+        super.setUp();
+        sshLocation = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        paasLocation = mgmt.getLocationManager().createLocation(LocationSpec.create(TestPaasLocation.class));
         factory = new ReflectiveEntityDriverFactory();
-        sshLocation = new SshMachineLocation(MutableMap.of("address", "localhost"));
-        entity = new MyDriverDependentEntity<MyDriver>(MyDriver.class);
-
-        paasLocation = new TestPaasLocation();
+        entity = app.addChild(EntitySpec.create(MyDriverDependentEntity.class)
+                .configure(MyDriverDependentEntity.DRIVER_CLASS, MyDriver.class));
     }
 
-    @AfterMethod
-    public void tearDown() {
-        // nothing to tear down; no management context created
-    }
-    
     protected void assertDriverIs(Class<?> clazz, Location location) {
-        MyDriver driver = factory.build(entity, location);
+        MyDriver driver = (MyDriver) factory.build(entity, location);
         assertTrue(driver.getClass().equals(clazz), "driver="+driver+"; should be "+clazz);
     }
     
@@ -109,21 +111,24 @@ public class ReflectiveEntityDriverFactoryTest {
         factory.addClassSimpleNameMapping(MyDriver.class.getSimpleName()+"X", MyCustomDriver.class.getSimpleName());
         assertDriverIs(MySshDriver.class, sshLocation);
     }
-    
-    public static class MyDriverDependentEntity<D extends EntityDriver> extends AbstractEntity implements DriverDependentEntity<D> {
-        private final Class<D> clazz;
 
-        public MyDriverDependentEntity(Class<D> clazz) {
-            this.clazz = clazz;
-        }
-        
+    @ImplementedBy(MyDriverDependentEntityImpl.class)
+    public static interface MyDriverDependentEntity extends Entity, DriverDependentEntity<EntityDriver> {
+        @SuppressWarnings("serial")
+        ConfigKey<Class<? extends EntityDriver>> DRIVER_CLASS = ConfigKeys.newConfigKey(
+                new TypeToken<Class<? extends EntityDriver>>() {}, 
+                "driverClass");
+    }
+    
+    public static class MyDriverDependentEntityImpl extends AbstractEntity implements MyDriverDependentEntity {
         @Override
-        public Class<D> getDriverInterface() {
-            return clazz;
+        @SuppressWarnings("unchecked")
+        public Class<EntityDriver> getDriverInterface() {
+            return (Class<EntityDriver>) config().get(DRIVER_CLASS);
         }
         
         @Override
-        public D getDriver() {
+        public EntityDriver getDriver() {
             throw new UnsupportedOperationException();
         }
     }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/entity/drivers/RegistryEntityDriverFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/RegistryEntityDriverFactoryTest.java b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/RegistryEntityDriverFactoryTest.java
index 4f079a1..60f70fa 100644
--- a/core/src/test/java/org/apache/brooklyn/core/entity/drivers/RegistryEntityDriverFactoryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/entity/drivers/RegistryEntityDriverFactoryTest.java
@@ -23,39 +23,37 @@ import static org.testng.Assert.assertTrue;
 
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntityLocal;
-import org.apache.brooklyn.api.entity.drivers.DriverDependentEntity;
+import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.core.entity.drivers.RegistryEntityDriverFactory;
+import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactoryTest.MyDriver;
 import org.apache.brooklyn.core.entity.drivers.ReflectiveEntityDriverFactoryTest.MyDriverDependentEntity;
 import org.apache.brooklyn.core.location.SimulatedLocation;
-import org.testng.annotations.AfterMethod;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
 
-public class RegistryEntityDriverFactoryTest {
+public class RegistryEntityDriverFactoryTest extends BrooklynAppUnitTestSupport {
 
     private RegistryEntityDriverFactory factory;
     private SshMachineLocation sshLocation;
     private SimulatedLocation simulatedLocation;
-
+    private MyDriverDependentEntity entity;
+    
     @BeforeMethod
     public void setUp() throws Exception {
+        super.setUp();
         factory = new RegistryEntityDriverFactory();
-        sshLocation = new SshMachineLocation(MutableMap.of("address", "localhost"));
-        simulatedLocation = new SimulatedLocation();
-    }
-
-    @AfterMethod
-    public void tearDown(){
-        // nothing to tear down; no management context created
+        sshLocation = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure("address", "localhost"));
+        simulatedLocation = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class));
+        entity = app.addChild(EntitySpec.create(MyDriverDependentEntity.class)
+                .configure(MyDriverDependentEntity.DRIVER_CLASS, MyDriver.class));
     }
 
     @Test
     public void testHasDriver() throws Exception {
-        DriverDependentEntity<MyDriver> entity = new MyDriverDependentEntity<MyDriver>(MyDriver.class);
         factory.registerDriver(MyDriver.class, SshMachineLocation.class, MyOtherSshDriver.class);
         assertTrue(factory.hasDriver(entity, sshLocation));
         assertFalse(factory.hasDriver(entity, simulatedLocation));
@@ -63,9 +61,8 @@ public class RegistryEntityDriverFactoryTest {
 
     @Test
     public void testInstantiatesRegisteredDriver() throws Exception {
-        DriverDependentEntity<MyDriver> entity = new MyDriverDependentEntity<MyDriver>(MyDriver.class);
         factory.registerDriver(MyDriver.class, SshMachineLocation.class, MyOtherSshDriver.class);
-        MyDriver driver = factory.build(entity, sshLocation);
+        MyDriver driver = (MyDriver) factory.build(entity, sshLocation);
         assertTrue(driver instanceof MyOtherSshDriver);
     }
 

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/entity/proxying/InternalEntityFactoryTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/entity/proxying/InternalEntityFactoryTest.java b/core/src/test/java/org/apache/brooklyn/core/entity/proxying/InternalEntityFactoryTest.java
index 9cb7060..7439b71 100644
--- a/core/src/test/java/org/apache/brooklyn/core/entity/proxying/InternalEntityFactoryTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/entity/proxying/InternalEntityFactoryTest.java
@@ -43,19 +43,19 @@ import org.testng.annotations.Test;
 
 public class InternalEntityFactoryTest {
 
-    private ManagementContextInternal managementContext;
+    private ManagementContextInternal mgmt;
     private InternalEntityFactory factory;
 
     @BeforeMethod(alwaysRun=true)
     public void setUp() throws Exception {
-        managementContext = new LocalManagementContextForTests();
-        InternalPolicyFactory policyFactory = new InternalPolicyFactory(managementContext);
-        factory = new InternalEntityFactory(managementContext, managementContext.getEntityManager().getEntityTypeRegistry(), policyFactory);
+        mgmt = new LocalManagementContextForTests();
+        InternalPolicyFactory policyFactory = new InternalPolicyFactory(mgmt);
+        factory = new InternalEntityFactory(mgmt, mgmt.getEntityManager().getEntityTypeRegistry(), policyFactory);
     }
     
     @AfterMethod(alwaysRun=true)
     public void tearDown() throws Exception {
-        if (managementContext != null) Entities.destroyAll(managementContext);
+        if (mgmt != null) Entities.destroyAll(mgmt);
     }
     
     @Test
@@ -73,12 +73,19 @@ public class InternalEntityFactoryTest {
     
     @Test
     public void testCreatesProxy() throws Exception {
-        TestApplicationImpl app = new TestApplicationImpl();
         EntitySpec<Application> spec = EntitySpec.create(Application.class).impl(TestApplicationImpl.class);
+        Application app = factory.createEntity(spec);
         Application proxy = factory.createEntityProxy(spec, app);
+        TestApplicationImpl deproxied = (TestApplicationImpl) Entities.deproxy(proxy);
         
-        assertFalse(proxy instanceof TestApplicationImpl, "proxy="+app);
-        assertTrue(proxy instanceof EntityProxy, "proxy="+app);
+        assertTrue(app instanceof TestApplicationImpl, "app="+app);
+        
+        assertFalse(proxy instanceof TestApplicationImpl, "proxy="+proxy);
+        assertTrue(proxy instanceof EntityProxy, "proxy="+proxy);
+        assertTrue(proxy instanceof Application, "proxy="+proxy);
+        
+        assertTrue(deproxied instanceof TestApplicationImpl, "deproxied="+deproxied);
+        assertFalse(deproxied instanceof EntityProxy, "deproxied="+deproxied);
     }
     
     @Test
@@ -92,13 +99,14 @@ public class InternalEntityFactoryTest {
     
     @Test
     public void testCreatesProxyImplementingAdditionalInterfaces() throws Exception {
-        MyApplicationImpl app = new MyApplicationImpl();
         EntitySpec<Application> spec = EntitySpec.create(Application.class).impl(MyApplicationImpl.class).additionalInterfaces(MyInterface.class);
+        Application app = factory.createEntity(spec);
         Application proxy = factory.createEntityProxy(spec, app);
         
-        assertFalse(proxy instanceof MyApplicationImpl, "proxy="+app);
-        assertTrue(proxy instanceof MyInterface, "proxy="+app);
-        assertTrue(proxy instanceof EntityProxy, "proxy="+app);
+        assertFalse(proxy instanceof MyApplicationImpl, "proxy="+proxy);
+        assertTrue(proxy instanceof Application, "proxy="+proxy);
+        assertTrue(proxy instanceof MyInterface, "proxy="+proxy);
+        assertTrue(proxy instanceof EntityProxy, "proxy="+proxy);
     }
     
     public interface MyInterface {

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiStandaloneTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiStandaloneTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiStandaloneTest.java
index 15b9ae9..b21ba28 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiStandaloneTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiStandaloneTest.java
@@ -170,7 +170,7 @@ public class OsgiStandaloneTest extends OsgiTestBase {
     public void testLoadOsgiBundleDependencies() throws Exception {
         Bundle bundle = installFromClasspath(BROOKLYN_TEST_OSGI_ENTITIES_PATH);
         Assert.assertNotNull(bundle);
-        Class<?> aClass = bundle.loadClass("org.apache.brooklyn.test.osgi.entities.SimpleApplicationImpl");
+        Class<?> aClass = bundle.loadClass("org.apache.brooklyn.test.osgi.entities.SimpleObject");
         Object aInst = aClass.newInstance();
         Assert.assertNotNull(aInst);
     }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiVersionMoreEntityTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiVersionMoreEntityTest.java b/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiVersionMoreEntityTest.java
index f19556e..83b48c2 100644
--- a/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiVersionMoreEntityTest.java
+++ b/core/src/test/java/org/apache/brooklyn/core/mgmt/osgi/OsgiVersionMoreEntityTest.java
@@ -18,6 +18,8 @@
  */
 package org.apache.brooklyn.core.mgmt.osgi;
 
+import static org.testng.Assert.assertTrue;
+
 import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.InvocationTargetException;
@@ -35,9 +37,11 @@ import org.apache.brooklyn.core.catalog.internal.CatalogItemBuilder;
 import org.apache.brooklyn.core.catalog.internal.CatalogItemDtoAbstract;
 import org.apache.brooklyn.core.catalog.internal.CatalogUtils;
 import org.apache.brooklyn.core.effector.Effectors;
+import org.apache.brooklyn.core.entity.AbstractEntity;
 import org.apache.brooklyn.core.entity.Entities;
 import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
 import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal;
+import org.apache.brooklyn.core.objs.proxy.EntityProxy;
 import org.apache.brooklyn.core.objs.proxy.InternalEntityFactory;
 import org.apache.brooklyn.core.objs.proxy.InternalPolicyFactory;
 import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
@@ -93,18 +97,17 @@ public class OsgiVersionMoreEntityTest implements OsgiTestResources {
      */
     @Test
     public void testEntityProxy() throws Exception {
+        TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), BROOKLYN_TEST_OSGI_ENTITIES_PATH);
+        
         File storageTempDir = Os.newTempDir("osgi-standalone");
         Framework framework = Osgis.getFramework(storageTempDir.getAbsolutePath(), true);
         
+        ManagementContextInternal managementContext = null;
         try {
-            ManagementContextInternal managementContext;
-            InternalEntityFactory factory;
-
             managementContext = new LocalManagementContextForTests();
             InternalPolicyFactory policyFactory = new InternalPolicyFactory(managementContext);
-            factory = new InternalEntityFactory(managementContext, managementContext.getEntityManager().getEntityTypeRegistry(), policyFactory);
+            InternalEntityFactory factory = new InternalEntityFactory(managementContext, managementContext.getEntityManager().getEntityTypeRegistry(), policyFactory);
 
-            TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), BROOKLYN_TEST_OSGI_ENTITIES_PATH);
             Bundle bundle = Osgis.install(framework, BROOKLYN_TEST_OSGI_ENTITIES_PATH);
             @SuppressWarnings("unchecked")
             Class<? extends Entity> bundleCls = (Class<? extends Entity>) bundle.loadClass("org.apache.brooklyn.test.osgi.entities.SimpleEntityImpl");
@@ -113,12 +116,19 @@ public class OsgiVersionMoreEntityTest implements OsgiTestResources {
 
             @SuppressWarnings("unchecked")
             EntitySpec<Entity> spec = (((EntitySpec<Entity>)EntitySpec.create(bundleInterface))).impl(bundleCls);
-            Entity entity = bundleCls.newInstance();
-            factory.createEntityProxy(spec, entity);
+            AbstractEntity entityImpl = (AbstractEntity) factory.createEntity(spec);
+            Entity entityProxy = factory.createEntityProxy(spec, entityImpl);
+            
+            assertTrue(entityProxy instanceof EntityProxy, "proxy="+entityProxy);
+            assertTrue(entityProxy instanceof Entity, "proxy="+entityProxy);
+            assertTrue(bundleInterface.isInstance(entityProxy), "proxy="+entityProxy);
 
-            if (managementContext != null) Entities.destroyAll(managementContext);
         } finally {
-            OsgiTestBase.tearDownOsgiFramework(framework, storageTempDir);
+            try {
+                if (managementContext != null) Entities.destroyAll(managementContext);
+            } finally {
+                OsgiTestBase.tearDownOsgiFramework(framework, storageTempDir);
+            }
         }
     }
     

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntity.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntity.java b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntity.java
index 85cc9e2..bfada48 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntity.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntity.java
@@ -112,6 +112,10 @@ public interface TestEntity extends Entity, Startable, EntityLocal, EntityIntern
 
     public Map<?,?> getConfigureProperties();
 
+    public int getConfigureCount();
+    
+    public int getConfigureDuringConstructionCount();
+    
     public int getSequenceValue();
 
     public void setSequenceValue(int value);

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntityImpl.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntityImpl.java b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntityImpl.java
index 2331b48..a2a64b9 100644
--- a/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntityImpl.java
+++ b/core/src/test/java/org/apache/brooklyn/core/test/entity/TestEntityImpl.java
@@ -58,6 +58,8 @@ public class TestEntityImpl extends AbstractEntity implements TestEntity {
     protected AtomicInteger counter = new AtomicInteger(0);
     protected Map<?,?> constructorProperties;
     protected Map<?,?> configureProperties;
+    protected int configureCount;
+    protected int configureDuringConstructionCount;
     protected List<String> callHistory = Collections.synchronizedList(Lists.<String>newArrayList());
 
     public TestEntityImpl() {
@@ -69,11 +71,13 @@ public class TestEntityImpl extends AbstractEntity implements TestEntity {
     public TestEntityImpl(Map properties, Entity parent) {
         super(properties, parent);
         this.constructorProperties = properties;
+        this.configureDuringConstructionCount = configureCount;
     }
     
     @Override
     public AbstractEntity configure(Map flags) {
         this.configureProperties = flags;
+        configureCount++;
         return super.configure(flags);
     }
     
@@ -133,6 +137,16 @@ public class TestEntityImpl extends AbstractEntity implements TestEntity {
     }
     
     @Override
+    public int getConfigureCount() {
+        return configureCount;
+    }
+
+    @Override
+    public int getConfigureDuringConstructionCount() {
+        return configureDuringConstructionCount;
+    }
+
+    @Override
     public synchronized int getSequenceValue() {
         return sequenceValue;
     }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/enricher/stock/YamlRollingTimeWindowMeanEnricherTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/enricher/stock/YamlRollingTimeWindowMeanEnricherTest.java b/core/src/test/java/org/apache/brooklyn/enricher/stock/YamlRollingTimeWindowMeanEnricherTest.java
index 58eed85..a6b8208 100644
--- a/core/src/test/java/org/apache/brooklyn/enricher/stock/YamlRollingTimeWindowMeanEnricherTest.java
+++ b/core/src/test/java/org/apache/brooklyn/enricher/stock/YamlRollingTimeWindowMeanEnricherTest.java
@@ -24,22 +24,16 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.mgmt.SubscriptionContext;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.api.sensor.EnricherSpec;
-import org.apache.brooklyn.core.entity.AbstractApplication;
-import org.apache.brooklyn.core.entity.Entities;
 import org.apache.brooklyn.core.sensor.BasicAttributeSensor;
 import org.apache.brooklyn.core.sensor.BasicSensorEvent;
-import org.apache.brooklyn.enricher.stock.YamlRollingTimeWindowMeanEnricher;
-import org.apache.brooklyn.enricher.stock.YamlTimeWeightedDeltaEnricher;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.enricher.stock.YamlRollingTimeWindowMeanEnricher.ConfidenceQualifiedNumber;
 import org.apache.brooklyn.entity.stock.BasicEntity;
 import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
-public class YamlRollingTimeWindowMeanEnricherTest {
-    
-    AbstractApplication app;
+public class YamlRollingTimeWindowMeanEnricherTest extends BrooklynAppUnitTestSupport {
     
     BasicEntity producer;
 
@@ -55,10 +49,10 @@ public class YamlRollingTimeWindowMeanEnricherTest {
     SubscriptionContext subscription;
     
     @SuppressWarnings("unchecked")
-    @BeforeMethod
-    public void before() {
-        app = new AbstractApplication() {};
-        Entities.startManagement(app);
+    @BeforeMethod(alwaysRun=true)
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
         producer = app.addChild(EntitySpec.create(BasicEntity.class));
 
         intSensor = new BasicAttributeSensor<Integer>(Integer.class, "int sensor");
@@ -77,11 +71,6 @@ public class YamlRollingTimeWindowMeanEnricherTest {
                 .configure(YamlRollingTimeWindowMeanEnricher.WINDOW_DURATION, timePeriod));
     }
 
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-    }
-        
     @Test
     public void testDefaultAverageWhenEmpty() {
         ConfidenceQualifiedNumber average = averager.getAverage(0, 0);

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/core/src/test/java/org/apache/brooklyn/entity/group/DynamicGroupTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicGroupTest.java b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicGroupTest.java
index 6fd133b..f785865 100644
--- a/core/src/test/java/org/apache/brooklyn/entity/group/DynamicGroupTest.java
+++ b/core/src/test/java/org/apache/brooklyn/entity/group/DynamicGroupTest.java
@@ -31,17 +31,21 @@ import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.api.sensor.Sensor;
 import org.apache.brooklyn.api.sensor.SensorEvent;
 import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.core.entity.AbstractEntity;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
 import org.apache.brooklyn.core.entity.Entities;
 import org.apache.brooklyn.core.entity.EntityPredicates;
 import org.apache.brooklyn.core.sensor.Sensors;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.core.test.entity.TestEntity;
 import org.apache.brooklyn.test.Asserts;
@@ -51,7 +55,6 @@ import org.apache.brooklyn.util.time.Duration;
 import org.apache.brooklyn.util.time.Time;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
@@ -62,29 +65,23 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Sets;
 
-public class DynamicGroupTest {
+public class DynamicGroupTest extends BrooklynAppUnitTestSupport {
 
     private static final Logger LOG = LoggerFactory.getLogger(DynamicGroupTest.class);
     
     private static final int TIMEOUT_MS = 50*1000;
     private static final int VERY_SHORT_WAIT_MS = 100;
     
-    private TestApplication app;
     private DynamicGroup group;
     private TestEntity e1;
     private TestEntity e2;
     
     @BeforeMethod(alwaysRun=true)
-    public void setUp() {
-        app = TestApplication.Factory.newManagedInstanceForTests();
-        group = app.createAndManageChild(EntitySpec.create(DynamicGroup.class));
-        e1 = app.createAndManageChild(EntitySpec.create(TestEntity.class));
-        e2 = app.createAndManageChild(EntitySpec.create(TestEntity.class));
-    }
-    
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        if (app != null) Entities.destroyAll(app.getManagementContext());
+    public void setUp() throws Exception {
+        super.setUp();
+        group = app.addChild(EntitySpec.create(DynamicGroup.class));
+        e1 = app.addChild(EntitySpec.create(TestEntity.class));
+        e2 = app.addChild(EntitySpec.create(TestEntity.class));
     }
     
     @Test
@@ -219,13 +216,11 @@ public class DynamicGroupTest {
     //      is deleted!
     @Test
     public void testStoppedGroupIgnoresComingAndGoingsOfEntities() throws Exception {
-        Entity e3 = new AbstractEntity() {};
         group.setEntityFilter(Predicates.instanceOf(TestEntity.class));
         assertEqualsIgnoringOrder(group.getMembers(), ImmutableSet.of(e1, e2));
         group.stop();
         
-        e3.setParent(app);
-        Entities.manage(e3);
+        Entity e3 = app.addChild(EntitySpec.create(TestEntity.class));
         Asserts.succeedsContinually(MutableMap.of("timeout", VERY_SHORT_WAIT_MS), new Runnable() {
             @Override
             public void run() {
@@ -242,13 +237,13 @@ public class DynamicGroupTest {
     
     @Test
     public void testUnmanagedGroupIgnoresComingAndGoingsOfEntities() {
-        Entity e3 = new AbstractEntity() {};
         group.setEntityFilter(Predicates.instanceOf(TestEntity.class));
         assertEqualsIgnoringOrder(group.getMembers(), ImmutableSet.of(e1, e2));
         Entities.unmanage(group);
         
-        e3.setParent(app);
-        Entities.manage(e3);
+        @SuppressWarnings("unused")
+        Entity e3 = app.addChild(EntitySpec.create(TestEntity.class));
+        
         Asserts.succeedsContinually(MutableMap.of("timeout", VERY_SHORT_WAIT_MS), new Runnable() {
             @Override
             public void run() {
@@ -344,106 +339,99 @@ public class DynamicGroupTest {
     @Test(groups="Integration")
     public void testEntityAddedAndRemovedCalledSequentially() throws Exception {
         final int NUM_CYCLES = 10;
-        final Set<Entity> knownMembers = Sets.newLinkedHashSet();
-        final AtomicInteger notificationCount = new AtomicInteger(0);
-        final AtomicInteger concurrentCallsCount = new AtomicInteger(0);
-        final List<Exception> exceptions = new CopyOnWriteArrayList<Exception>();
         
-        DynamicGroupImpl group2 = new DynamicGroupImpl() {
-            @Override protected void onEntityAdded(Entity item) {
-                try {
-                    onCall("Member added: member="+item);
-                    assertTrue(knownMembers.add(item));
-                } catch (Throwable t) {
-                    exceptions.add(new Exception("Error detected adding "+item, t));
-                    throw Exceptions.propagate(t);
-                }
-            }
-            @Override protected void onEntityRemoved(Entity item) {
-                try {
-                    onCall("Member removed: member="+item);
-                    assertTrue(knownMembers.remove(item));
-                } catch (Throwable t) {
-                    exceptions.add(new Exception("Error detected adding "+item, t));
-                    throw Exceptions.propagate(t);
-                }
-            }
-            private void onCall(String msg) {
-                LOG.debug(msg+", thread="+Thread.currentThread().getName());
-                try {
-                    assertEquals(concurrentCallsCount.incrementAndGet(), 1);
-                    Time.sleep(100);
-                } finally {
-                    concurrentCallsCount.decrementAndGet();
-                }
-                notificationCount.incrementAndGet();
-            }
-        };
-        group2.config().set(DynamicGroup.ENTITY_FILTER, Predicates.instanceOf(TestEntity.class));
-        app.addChild(group2);
-        Entities.manage(group2);
+        DynamicGroup group2 = app.addChild(EntitySpec.create(DynamicGroup.class)
+                .impl(DynamicGroupCheckingEntityAddedAndRemovedSequentially.class)
+                .configure(DynamicGroup.ENTITY_FILTER, Predicates.instanceOf(TestEntity.class)));
         
         for (int i = 0; i < NUM_CYCLES; i++) {
             TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
             Entities.unmanage(entity);
         }
 
+        final DynamicGroupCheckingEntityAddedAndRemovedSequentially group2impl = 
+                (DynamicGroupCheckingEntityAddedAndRemovedSequentially) Entities.deproxy(group2);
+        
         Asserts.succeedsEventually(new Runnable() {
             @Override
             public void run() {
-                assertTrue(notificationCount.get() == (NUM_CYCLES*2) || exceptions.size() > 0);
+                assertTrue(group2impl.notificationCount.get() == (NUM_CYCLES*2) || group2impl.exceptions.size() > 0);
             }});
 
-        if (exceptions.size() > 0) {
-            throw exceptions.get(0);
+        if (group2impl.exceptions.size() > 0) {
+            throw group2impl.exceptions.get(0);
         }
         
-        assertEquals(notificationCount.get(), NUM_CYCLES*2);
+        assertEquals(group2impl.notificationCount.get(), NUM_CYCLES*2);
+    }
+    public static class DynamicGroupCheckingEntityAddedAndRemovedSequentially extends DynamicGroupImpl {
+        final Set<Entity> knownMembers = Sets.newLinkedHashSet();
+        final AtomicInteger notificationCount = new AtomicInteger(0);
+        final AtomicInteger concurrentCallsCount = new AtomicInteger(0);
+        final List<Exception> exceptions = new CopyOnWriteArrayList<Exception>();
+
+        @Override
+        protected void onEntityAdded(Entity item) {
+            try {
+                onCall("Member added: member="+item);
+                assertTrue(knownMembers.add(item));
+            } catch (Throwable t) {
+                exceptions.add(new Exception("Error detected adding "+item, t));
+                throw Exceptions.propagate(t);
+            }
+        }
+        @Override
+        protected void onEntityRemoved(Entity item) {
+            try {
+                onCall("Member removed: member="+item);
+                assertTrue(knownMembers.remove(item));
+            } catch (Throwable t) {
+                exceptions.add(new Exception("Error detected adding "+item, t));
+                throw Exceptions.propagate(t);
+            }
+        }
+        private void onCall(String msg) {
+            LOG.debug(msg+", thread="+Thread.currentThread().getName());
+            try {
+                assertEquals(concurrentCallsCount.incrementAndGet(), 1);
+                Time.sleep(100);
+            } finally {
+                concurrentCallsCount.decrementAndGet();
+            }
+            notificationCount.incrementAndGet();
+        }
     }
     
     // See Deadlock in https://github.com/brooklyncentral/brooklyn/issues/378
-    // TODO Now that entities are auto-managed, this test is no longer appropriate.
-    // Should it be re-written or deleted?
-    @Test(groups="WIP")
+    // Rewritten to avoid using entity-constructors and explicit "manage" call, so possibly not
+    // as directly applicable to the deadlock in the github issue, but that old code path is no
+    // longer possible!
+    @Test
     public void testDoesNotDeadlockOnManagedAndMemberAddedConcurrently() throws Exception {
         final CountDownLatch rescanReachedLatch = new CountDownLatch(1);
         final CountDownLatch entityAddedReachedLatch = new CountDownLatch(1);
         final CountDownLatch rescanLatch = new CountDownLatch(1);
         final CountDownLatch entityAddedLatch = new CountDownLatch(1);
         
-        final TestEntity e3 = app.addChild(EntitySpec.create(TestEntity.class));
-        
-        final DynamicGroupImpl group2 = new DynamicGroupImpl() {
-            @Override public void rescanEntities() {
-                rescanReachedLatch.countDown();
-                try {
-                    rescanLatch.await();
-                } catch (InterruptedException e) {
-                    Exceptions.propagate(e);
-                }
-                super.rescanEntities();
-            }
-            @Override protected void onEntityAdded(Entity item) {
-                entityAddedReachedLatch.countDown();
-                try {
-                    entityAddedLatch.await();
-                } catch (InterruptedException e) {
-                    Exceptions.propagate(e);
-                }
-                super.onEntityAdded(item);
-            }
-        };
-        group2.config().set(DynamicGroup.ENTITY_FILTER, Predicates.<Object>equalTo(e3));
-        app.addChild(group2);
+        final AtomicReference<DynamicGroup> group2ref = new AtomicReference<>();
+        final AtomicReference<TestEntity> e3ref = new AtomicReference<>();
         
         Thread t1 = new Thread(new Runnable() {
             @Override public void run() {
-                Entities.manage(group2);
+                DynamicGroup group2 = app.addChild(EntitySpec.create(DynamicGroupTestManagedAndMemberAddedConcurrently.class)
+                        .configure("rescanReachedLatch", rescanReachedLatch)
+                        .configure("entityAddedReachedLatch", entityAddedReachedLatch)
+                        .configure("rescanLatch", rescanLatch)
+                        .configure("entityAddedLatch", entityAddedLatch)
+                        .configure(DynamicGroup.ENTITY_FILTER, EntityPredicates.displayNameEqualTo("e3")));
+                group2ref.set(group2);
             }});
         
         Thread t2 = new Thread(new Runnable() {
             @Override public void run() {
-                Entities.manage(e3);
+                TestEntity e3 = app.addChild(EntitySpec.create(TestEntity.class)
+                        .displayName("e3"));
+                e3ref.set(e3);
             }});
 
         t1.start();
@@ -469,48 +457,66 @@ public class DynamicGroupTest {
         Asserts.succeedsEventually(new Runnable() {
             @Override
             public void run() {
-                assertEqualsIgnoringOrder(group2.getMembers(), ImmutableSet.of(e3));
+                assertEqualsIgnoringOrder(group2ref.get().getMembers(), ImmutableSet.of(e3ref.get()));
             }});
     }
+    @ImplementedBy(DynamicGroupTestManagedAndMemberAddedConcurrentlyImpl.class)
+    public interface DynamicGroupTestManagedAndMemberAddedConcurrently extends DynamicGroup {
+        ConfigKey<CountDownLatch> RESCAN_REACHED_LATCH = ConfigKeys.newConfigKey(CountDownLatch.class, "rescanReachedLatch");
+        ConfigKey<CountDownLatch> ENTITY_ADDED_REACHED_LATCH = ConfigKeys.newConfigKey(CountDownLatch.class, "entityAddedReachedLatch");
+        ConfigKey<CountDownLatch> RESCAN_LATCH = ConfigKeys.newConfigKey(CountDownLatch.class, "rescanLatch");
+        ConfigKey<CountDownLatch> ENTITY_ADDED_LATCH = ConfigKeys.newConfigKey(CountDownLatch.class, "entityAddedLatch");
+    }
+    public static class DynamicGroupTestManagedAndMemberAddedConcurrentlyImpl extends DynamicGroupImpl implements DynamicGroupTestManagedAndMemberAddedConcurrently {
+        CountDownLatch rescanReachedLatch;
+        CountDownLatch entityAddedReachedLatch;
+        CountDownLatch rescanLatch;
+        CountDownLatch entityAddedLatch;
+
+        @Override
+        public void init() {
+            super.init();
+            rescanReachedLatch = config().get(RESCAN_REACHED_LATCH);
+            entityAddedReachedLatch = config().get(ENTITY_ADDED_REACHED_LATCH);
+            rescanLatch = config().get(RESCAN_LATCH);
+            entityAddedLatch = config().get(ENTITY_ADDED_LATCH);
+        }
+        
+        @Override public void rescanEntities() {
+            rescanReachedLatch.countDown();
+            try {
+                rescanLatch.await();
+            } catch (InterruptedException e) {
+                Exceptions.propagate(e);
+            }
+            super.rescanEntities();
+        }
+        @Override protected void onEntityAdded(Entity item) {
+            entityAddedReachedLatch.countDown();
+            try {
+                entityAddedLatch.await();
+            } catch (InterruptedException e) {
+                Exceptions.propagate(e);
+            }
+            super.onEntityAdded(item);
+        }
+    }
     
     // See deadlock in https://issues.apache.org/jira/browse/BROOKLYN-66
     @Test
     public void testDoesNotDeadlockOnUnmanageWhileOtherMemberBeingAdded() throws Exception {
-        final CountDownLatch removingMemberReachedLatch = new CountDownLatch(1);
-        final CountDownLatch addingMemberReachedLatch = new CountDownLatch(1);
-        final CountDownLatch addingMemberContinueLatch = new CountDownLatch(1);
-        final AtomicBoolean addingMemberDoLatching = new AtomicBoolean(false);
         final List<Entity> membersAdded = new CopyOnWriteArrayList<Entity>();
         
-        final DynamicGroupImpl group2 = new DynamicGroupImpl() {
-            private final BasicSensorSupport interceptedSensors = new BasicSensorSupport() {
-                @Override
-                public <T> void emit(Sensor<T> sensor, T val) {
-                    // intercept inside AbstractGroup.addMember, while it still holds lock on members
-                    if (sensor == AbstractGroup.MEMBER_ADDED && addingMemberDoLatching.get()) {
-                        addingMemberReachedLatch.countDown();
-                        try {
-                            addingMemberContinueLatch.await();
-                        } catch (InterruptedException e) {
-                            throw Exceptions.propagate(e);
-                        }
-                    }
-                    super.emit(sensor, val);
-                }
-            };
-            @Override
-            public BasicSensorSupport sensors() {
-                return interceptedSensors;
-            }
-            @Override
-            public boolean removeMember(final Entity member) {
-                removingMemberReachedLatch.countDown();
-                return super.removeMember(member);
-            }
-        };
-        group2.config().set(DynamicGroup.MEMBER_DELEGATE_CHILDREN, true);
-        app.addChild(group2);
-        Entities.manage(group2);
+        final DynamicGroup group2 = app.addChild(EntitySpec.create(DynamicGroup.class)
+                .impl(DynamicGroupTestingUnmanageWhileOtherMemberBeingAdded.class)
+                .configure(DynamicGroup.MEMBER_DELEGATE_CHILDREN, true));
+
+        DynamicGroupTestingUnmanageWhileOtherMemberBeingAdded group2impl = 
+                (DynamicGroupTestingUnmanageWhileOtherMemberBeingAdded) Entities.deproxy(group2);
+        final CountDownLatch removingMemberReachedLatch = group2impl.removingMemberReachedLatch;
+        final CountDownLatch addingMemberReachedLatch = group2impl.addingMemberReachedLatch;
+        final CountDownLatch addingMemberContinueLatch = group2impl.addingMemberContinueLatch;
+        final AtomicBoolean addingMemberDoLatching = group2impl.addingMemberDoLatching;
         
         app.subscriptions().subscribe(group2, AbstractGroup.MEMBER_ADDED, new SensorEventListener<Entity>() {
             @Override public void onEvent(SensorEvent<Entity> event) {
@@ -553,6 +559,37 @@ public class DynamicGroupTest {
             t2.interrupt();
         }
     }
+    public static class DynamicGroupTestingUnmanageWhileOtherMemberBeingAdded extends DynamicGroupImpl {
+        final CountDownLatch removingMemberReachedLatch = new CountDownLatch(1);
+        final CountDownLatch addingMemberReachedLatch = new CountDownLatch(1);
+        final CountDownLatch addingMemberContinueLatch = new CountDownLatch(1);
+        final AtomicBoolean addingMemberDoLatching = new AtomicBoolean(false);
+        
+        private final BasicSensorSupport interceptedSensors = new BasicSensorSupport() {
+            @Override
+            public <T> void emit(Sensor<T> sensor, T val) {
+                // intercept inside AbstractGroup.addMember, while it still holds lock on members
+                if (sensor == AbstractGroup.MEMBER_ADDED && addingMemberDoLatching.get()) {
+                    addingMemberReachedLatch.countDown();
+                    try {
+                        addingMemberContinueLatch.await();
+                    } catch (InterruptedException e) {
+                        throw Exceptions.propagate(e);
+                    }
+                }
+                super.emit(sensor, val);
+            }
+        };
+        @Override
+        public BasicSensorSupport sensors() {
+            return interceptedSensors;
+        }
+        @Override
+        public boolean removeMember(final Entity member) {
+            removingMemberReachedLatch.countDown();
+            return super.removeMember(member);
+        }
+    };
 
     @Test
     public void testOnlyMatchesEntitiesInSameApplication() {

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
index b973c11..dff0f25 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java
@@ -30,13 +30,15 @@ import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.entity.Group;
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.core.entity.Entities;
-import org.apache.brooklyn.core.entity.factory.ApplicationBuilder;
 import org.apache.brooklyn.core.location.SimulatedLocation;
-import org.apache.brooklyn.core.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.group.DynamicGroup;
+import org.apache.brooklyn.policy.loadbalancing.BalanceableContainer;
+import org.apache.brooklyn.policy.loadbalancing.MockContainerEntity;
+import org.apache.brooklyn.policy.loadbalancing.MockItemEntity;
+import org.apache.brooklyn.policy.loadbalancing.MockItemEntityImpl;
+import org.apache.brooklyn.policy.loadbalancing.Movable;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.time.Time;
@@ -44,11 +46,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
-import org.apache.brooklyn.policy.loadbalancing.BalanceableContainer;
-import org.apache.brooklyn.policy.loadbalancing.MockContainerEntity;
-import org.apache.brooklyn.policy.loadbalancing.MockItemEntity;
-import org.apache.brooklyn.policy.loadbalancing.MockItemEntityImpl;
-import org.apache.brooklyn.policy.loadbalancing.Movable;
 
 import com.google.common.base.Function;
 import com.google.common.base.Predicates;
@@ -57,7 +54,7 @@ import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Maps;
 
-public class AbstractFollowTheSunPolicyTest {
+public abstract class AbstractFollowTheSunPolicyTest extends BrooklynAppUnitTestSupport {
     
     private static final Logger LOG = LoggerFactory.getLogger(AbstractFollowTheSunPolicyTest.class);
     
@@ -66,8 +63,6 @@ public class AbstractFollowTheSunPolicyTest {
     
     protected static final long CONTAINER_STARTUP_DELAY_MS = 100;
     
-    protected TestApplication app;
-    protected ManagementContext managementContext;
     protected SimulatedLocation loc1;
     protected SimulatedLocation loc2;
     protected FollowTheSunPool pool;
@@ -78,17 +73,16 @@ public class AbstractFollowTheSunPolicyTest {
     protected Random random = new Random();
     
     @BeforeMethod(alwaysRun=true)
+    @Override
     public void setUp() throws Exception {
+        super.setUp();
         LOG.debug("In AbstractFollowTheSunPolicyTest.setUp()");
 
         MockItemEntityImpl.totalMoveCount.set(0);
         MockItemEntityImpl.lastMoveTime.set(0);
         
-        managementContext = LocalManagementContextForTests.newInstance();
-        app = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext);
-        
-        loc1 = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).configure("name", "loc1"));
-        loc2 = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).configure("name", "loc2"));
+        loc1 = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).configure("name", "loc1"));
+        loc2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).configure("name", "loc2"));
         
         containerGroup = app.createAndManageChild(EntitySpec.create(DynamicGroup.class)
                 .displayName("containerGroup")
@@ -106,11 +100,15 @@ public class AbstractFollowTheSunPolicyTest {
     }
     
     @AfterMethod(alwaysRun=true)
-    public void tearDown() {
-        if (pool != null && policy != null) pool.policies().remove(policy);
-        if (app != null) Entities.destroyAll(app.getManagementContext());
-        MockItemEntityImpl.totalMoveCount.set(0);
-        MockItemEntityImpl.lastMoveTime.set(0);
+    @Override
+    public void tearDown() throws Exception {
+        try {
+            if (pool != null && policy != null) pool.policies().remove(policy);
+        } finally {
+            super.tearDown();
+            MockItemEntityImpl.totalMoveCount.set(0);
+            MockItemEntityImpl.lastMoveTime.set(0);
+        }
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
index 29344aa..c0956f0 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/followthesun/FollowTheSunModelTest.java
@@ -22,41 +22,48 @@ import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertTrue;
 
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
+import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.core.location.SimulatedLocation;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.policy.loadbalancing.MockContainerEntity;
-import org.apache.brooklyn.policy.loadbalancing.MockContainerEntityImpl;
 import org.apache.brooklyn.policy.loadbalancing.MockItemEntity;
-import org.apache.brooklyn.policy.loadbalancing.MockItemEntityImpl;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 
-public class FollowTheSunModelTest {
+public class FollowTheSunModelTest extends BrooklynAppUnitTestSupport {
 
-    private Location loc1 = new SimulatedLocation(DefaultFollowTheSunModel.newHashMap("name","loc1"));
-    private Location loc2 = new SimulatedLocation(DefaultFollowTheSunModel.newHashMap("name","loc2"));
-    private MockContainerEntity container1 = new MockContainerEntityImpl();
-    private MockContainerEntity container2 = new MockContainerEntityImpl();
-    private MockItemEntity item1 = new MockItemEntityImpl();
-    private MockItemEntity item2 = new MockItemEntityImpl();
-    private MockItemEntity item3 = new MockItemEntityImpl();
+    private Location loc1;
+    private Location loc2;
+    private MockContainerEntity container1;
+    private MockContainerEntity container2;
+    private MockItemEntity item1;
+    private MockItemEntity item2;
+    private MockItemEntity item3;
     
     private DefaultFollowTheSunModel<MockContainerEntity, MockItemEntity> model;
 
     @BeforeMethod(alwaysRun=true)
+    @Override
     public void setUp() throws Exception {
+        super.setUp();
         model = new DefaultFollowTheSunModel<MockContainerEntity, MockItemEntity>("myname");
+        
+        loc1 = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class)
+                .configure("name","loc1"));
+        loc2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class)
+                .configure("name","loc2"));
+        container1 = app.addChild(EntitySpec.create(MockContainerEntity.class));
+        container2 = app.addChild(EntitySpec.create(MockContainerEntity.class));
+        item1 = app.addChild(EntitySpec.create(MockItemEntity.class));
+        item2 = app.addChild(EntitySpec.create(MockItemEntity.class));
+        item3 = app.addChild(EntitySpec.create(MockItemEntity.class));
     }
     
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        // noting to tear down; no management context created
-    }
-
     @Test
     public void testSimpleAddAndRemove() throws Exception {
         model.onContainerAdded(container1, loc1);

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
index 8b2c387..faf4fae 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/AbstractLoadBalancingPolicyTest.java
@@ -32,9 +32,9 @@ import org.apache.brooklyn.api.entity.Group;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.config.BasicConfigKey;
-import org.apache.brooklyn.core.entity.Entities;
 import org.apache.brooklyn.core.location.SimulatedLocation;
 import org.apache.brooklyn.core.sensor.Sensors;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.core.test.entity.TestApplication;
 import org.apache.brooklyn.entity.group.DynamicGroup;
 import org.apache.brooklyn.test.Asserts;
@@ -53,7 +53,7 @@ import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
-public class AbstractLoadBalancingPolicyTest {
+public abstract class AbstractLoadBalancingPolicyTest extends BrooklynAppUnitTestSupport {
     
     private static final Logger LOG = LoggerFactory.getLogger(AbstractLoadBalancingPolicyTest.class);
     
@@ -68,7 +68,6 @@ public class AbstractLoadBalancingPolicyTest {
     public static final ConfigKey<Double> LOW_THRESHOLD_CONFIG_KEY = new BasicConfigKey<Double>(Double.class, TEST_METRIC.getName()+".threshold.low", "desc", 0.0);
     public static final ConfigKey<Double> HIGH_THRESHOLD_CONFIG_KEY = new BasicConfigKey<Double>(Double.class, TEST_METRIC.getName()+".threshold.high", "desc", 0.0);
     
-    protected TestApplication app;
     protected SimulatedLocation loc;
     protected BalanceableWorkerPool pool;
     protected DefaultBalanceablePoolModel<Entity, Entity> model;
@@ -78,7 +77,9 @@ public class AbstractLoadBalancingPolicyTest {
     protected Random random = new Random();
     
     @BeforeMethod(alwaysRun=true)
-    public void before() {
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
         LOG.debug("In AbstractLoadBalancingPolicyTest.before()");
         
         MockItemEntityImpl.totalMoveCount.set(0);
@@ -103,9 +104,13 @@ public class AbstractLoadBalancingPolicyTest {
     }
     
     @AfterMethod(alwaysRun=true)
-    public void after() {
-        if (policy != null) policy.destroy();
-        if (app != null) Entities.destroyAll(app.getManagementContext());
+    @Override
+    public void tearDown() throws Exception {
+        try {
+            if (policy != null) policy.destroy();
+        } finally {
+            super.tearDown();
+        }
     }
     
     // Using this utility, as it gives more info about the workrates of all containers rather than just the one that differs    

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingModelTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingModelTest.java b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingModelTest.java
index d96f509..35f6878 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingModelTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingModelTest.java
@@ -22,33 +22,37 @@ import static org.testng.Assert.assertEquals;
 
 import java.util.Collections;
 
-import org.testng.annotations.AfterMethod;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 
-public class LoadBalancingModelTest {
+public class LoadBalancingModelTest extends BrooklynAppUnitTestSupport {
 
     private static final double PRECISION = 0.00001;
     
-    private MockContainerEntity container1 = new MockContainerEntityImpl();
-    private MockContainerEntity container2 = new MockContainerEntityImpl();
-    private MockItemEntity item1 = new MockItemEntityImpl();
-    private MockItemEntity item2 = new MockItemEntityImpl();
-    private MockItemEntity item3 = new MockItemEntityImpl();
+    private MockContainerEntity container1;
+    private MockContainerEntity container2;
+    private MockItemEntity item1;
+    private MockItemEntity item2;
+    private MockItemEntity item3;
     
     private DefaultBalanceablePoolModel<MockContainerEntity, MockItemEntity> model;
 
     @BeforeMethod(alwaysRun=true)
+    @Override
     public void setUp() throws Exception {
+        super.setUp();
         model = new DefaultBalanceablePoolModel<MockContainerEntity, MockItemEntity>("myname");
-    }
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        // nothing to tear down; no management context created
+        
+        container1 = app.addChild(EntitySpec.create(MockContainerEntity.class));
+        container2 = app.addChild(EntitySpec.create(MockContainerEntity.class));
+        item1 = app.addChild(EntitySpec.create(MockItemEntity.class));
+        item2 = app.addChild(EntitySpec.create(MockItemEntity.class));
+        item3 = app.addChild(EntitySpec.create(MockItemEntity.class));
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingPolicyConcurrencyTest.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingPolicyConcurrencyTest.java b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingPolicyConcurrencyTest.java
index 6c6f392..fd032ff 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingPolicyConcurrencyTest.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/LoadBalancingPolicyConcurrencyTest.java
@@ -51,16 +51,16 @@ public class LoadBalancingPolicyConcurrencyTest extends AbstractLoadBalancingPol
 
     @BeforeMethod(alwaysRun=true)
     @Override
-    public void before() {
+    public void setUp() throws Exception {
         scheduledExecutor = Executors.newScheduledThreadPool(10);
-        super.before();
+        super.setUp();
     }
     
     @AfterMethod(alwaysRun=true)
     @Override
-    public void after() {
+    public void tearDown() throws Exception {
         if (scheduledExecutor != null) scheduledExecutor.shutdownNow();
-        super.after();
+        super.tearDown();
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/MockItemEntityImpl.java
----------------------------------------------------------------------
diff --git a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/MockItemEntityImpl.java b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/MockItemEntityImpl.java
index 699fe59..e0c960d 100644
--- a/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/MockItemEntityImpl.java
+++ b/policy/src/test/java/org/apache/brooklyn/policy/loadbalancing/MockItemEntityImpl.java
@@ -27,6 +27,7 @@ import java.util.concurrent.locks.ReentrantLock;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.sensor.AttributeSensor;
 import org.apache.brooklyn.core.entity.AbstractEntity;
+import org.apache.brooklyn.core.entity.Entities;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -81,7 +82,7 @@ public class MockItemEntityImpl extends AbstractEntity implements MockItemEntity
                 _lock.lock();
                 try {
                     if (stopped) throw new IllegalStateException("Item "+this+" is stopped; cannot move to "+destination);
-                    if (currentContainer != null) currentContainer.removeItem(MockItemEntityImpl.this);
+                    if (currentContainer != null && Entities.isManaged(currentContainer)) currentContainer.removeItem(MockItemEntityImpl.this);
                     currentContainer = destination;
                     destination.addItem(MockItemEntityImpl.this);
                     sensors().set(CONTAINER, currentContainer);
@@ -97,7 +98,7 @@ public class MockItemEntityImpl extends AbstractEntity implements MockItemEntity
         if (LOG.isDebugEnabled()) LOG.debug("Mocks: stopping item {} (was in container {})", this, currentContainer);
         _lock.lock();
         try {
-            if (currentContainer != null) currentContainer.removeItem(this);
+            if (currentContainer != null && Entities.isManaged(currentContainer)) currentContainer.removeItem(this);
             currentContainer = null;
             stopped = true;
         } finally {

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/server-cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
----------------------------------------------------------------------
diff --git a/server-cli/src/test/java/org/apache/brooklyn/cli/CliTest.java b/server-cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
index c85af6e..65b48eb 100644
--- a/server-cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
+++ b/server-cli/src/test/java/org/apache/brooklyn/cli/CliTest.java
@@ -41,8 +41,10 @@ import java.util.regex.Pattern;
 
 import org.apache.brooklyn.api.catalog.CatalogItem;
 import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.entity.ImplementedBy;
 import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
 import org.apache.brooklyn.api.mgmt.ManagementContext;
 import org.apache.brooklyn.cli.AbstractMain.BrooklynCommand;
 import org.apache.brooklyn.cli.AbstractMain.BrooklynCommandCollectingArgs;
@@ -219,19 +221,19 @@ public class CliTest {
     @Test
     public void testStopAllApplications() throws Exception {
         LaunchCommand launchCommand = new Main.LaunchCommand();
-        ExampleApp app = new ExampleApp();
-        ManagementContext mgmt = null;
+        ManagementContext mgmt = LocalManagementContextForTests.newInstance();
+        
         try {
-            Entities.startManagement(app);
-            mgmt = app.getManagementContext();
-            app.start(ImmutableList.of(new SimulatedLocation()));
-            assertTrue(app.running);
+            StartableApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(StartableApplication.class).impl(ExampleApp.class));
+            ExampleApp appImpl = (ExampleApp) Entities.deproxy(app);
+            SimulatedLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class));
+            app.start(ImmutableList.of(loc));
+            assertTrue(appImpl.running);
             
             launchCommand.stopAllApps(ImmutableList.of(app));
-            assertFalse(app.running);
+            assertFalse(appImpl.running);
         } finally {
             // Stopping the app will make app.getManagementContext return the "NonDeploymentManagementContext";
-            // hence we've retrieved it before calling stopAllApps()
             if (mgmt != null) Entities.destroyAll(mgmt);
         }
     }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
index ae3943b..635f2fd 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/SoftwareProcessEntityTest.java
@@ -92,7 +92,6 @@ import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.reflect.TypeToken;
 
-
 public class SoftwareProcessEntityTest extends BrooklynAppUnitTestSupport {
 
     // NB: These tests don't actually require ssh to localhost -- only that 'localhost' resolves.
@@ -364,12 +363,12 @@ public class SoftwareProcessEntityTest extends BrooklynAppUnitTestSupport {
                     .configure(StopSoftwareParameters.STOP_MACHINE_MODE, stopMachineMode)));
         t1.asTask().get(10, TimeUnit.SECONDS);
 
-        if (MachineLifecycleEffectorTasksTest.canStop(stopProcessMode, isEntityStopped)) {
+        if (MachineLifecycleEffectorTasksTest.canStop(app, stopProcessMode, isEntityStopped)) {
             assertEquals(d.events, ImmutableList.of("stop"));
         } else {
             assertTrue(d.events.isEmpty());
         }
-        if (MachineLifecycleEffectorTasksTest.canStop(stopMachineMode, machine == null)) {
+        if (MachineLifecycleEffectorTasksTest.canStop(app, stopMachineMode, machine == null)) {
             assertTrue(entity.getLocations().isEmpty());
             assertTrue(l.getAvailable().contains(machine));
         } else {

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9a83a598/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java
----------------------------------------------------------------------
diff --git a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java
index 4d51db0..b7bba5c 100644
--- a/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java
+++ b/software/base/src/test/java/org/apache/brooklyn/entity/software/base/lifecycle/MachineLifecycleEffectorTasksTest.java
@@ -23,6 +23,7 @@ import static org.testng.Assert.assertTrue;
 
 import java.util.List;
 
+import org.apache.brooklyn.api.entity.Application;
 import org.apache.brooklyn.api.entity.Entity;
 import org.apache.brooklyn.api.entity.EntitySpec;
 import org.apache.brooklyn.api.mgmt.Task;
@@ -34,12 +35,11 @@ import org.apache.brooklyn.core.entity.trait.Startable;
 import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
 import org.apache.brooklyn.core.sensor.DependentConfiguration;
 import org.apache.brooklyn.core.sensor.Sensors;
-import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
 import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess;
 import org.apache.brooklyn.entity.software.base.SoftwareProcess.StopSoftwareParameters.StopMode;
 import org.apache.brooklyn.entity.stock.BasicEntity;
-import org.apache.brooklyn.entity.stock.BasicEntityImpl;
 import org.apache.brooklyn.location.jclouds.BailOutJcloudsLocation;
 import org.apache.brooklyn.test.Asserts;
 import org.apache.brooklyn.util.core.task.TaskInternal;
@@ -55,10 +55,11 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 
-public class MachineLifecycleEffectorTasksTest {
-    public static boolean canStop(StopMode stopMode, boolean isEntityStopped) {
-        BasicEntityImpl entity = new BasicEntityImpl();
+public class MachineLifecycleEffectorTasksTest extends BrooklynAppUnitTestSupport {
+    
+    public static boolean canStop(Application parent, StopMode stopMode, boolean isEntityStopped) {
         Lifecycle state = isEntityStopped ? Lifecycle.STOPPED : Lifecycle.RUNNING;
+        BasicEntity entity = parent.addChild(EntitySpec.create(BasicEntity.class));
         entity.sensors().set(SoftwareProcess.SERVICE_STATE_ACTUAL, state);
         return MachineLifecycleEffectorTasks.canStop(stopMode, entity);
     }
@@ -77,7 +78,7 @@ public class MachineLifecycleEffectorTasksTest {
 
     @Test(dataProvider = "canStopStates")
     public void testBasicSonftwareProcessCanStop(StopMode mode, boolean isEntityStopped, boolean expected) {
-        boolean canStop = canStop(mode, isEntityStopped);
+        boolean canStop = canStop(app, mode, isEntityStopped);
         assertEquals(canStop, expected);
     }
 
@@ -86,7 +87,6 @@ public class MachineLifecycleEffectorTasksTest {
 
         AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");
 
-        TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
         BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));
 
         EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
@@ -115,8 +115,6 @@ public class MachineLifecycleEffectorTasksTest {
             } else {
                 Exceptions.propagate(t);
             }
-        } finally {
-            Entities.destroyAll(app.getManagementContext());
         }
     }
 


Mime
View raw message