http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/test/AssertsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/test/AssertsTest.java b/utils/common/src/test/java/brooklyn/test/AssertsTest.java deleted file mode 100644 index edcdb2d..0000000 --- a/utils/common/src/test/java/brooklyn/test/AssertsTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.test; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; -import brooklyn.util.exceptions.Exceptions; -import brooklyn.util.time.Duration; - -import com.google.common.util.concurrent.Callables; - -public class AssertsTest { - - private static final Runnable NOOP_RUNNABLE = new Runnable() { - @Override public void run() { - } - }; - - // TODO this is confusing -- i'd expect it to fail since it always returns false; - // see notes at start of Asserts and in succeedsEventually method - @Test - public void testSucceedsEventually() { - Asserts.succeedsEventually(MutableMap.of("timeout", Duration.millis(50)), Callables.returning(false)); - } - - @Test - public void testAssertReturnsEventually() throws Exception { - Asserts.assertReturnsEventually(NOOP_RUNNABLE, Duration.THIRTY_SECONDS); - } - - @Test - public void testAssertReturnsEventuallyTimesOut() throws Exception { - final AtomicBoolean interrupted = new AtomicBoolean(); - - try { - Asserts.assertReturnsEventually(new Runnable() { - public void run() { - try { - Thread.sleep(60*1000); - } catch (InterruptedException e) { - interrupted.set(true); - Thread.currentThread().interrupt(); - return; - } - }}, - Duration.of(10, TimeUnit.MILLISECONDS)); - Assert.fail("Should have thrown AssertionError on timeout"); - } catch (TimeoutException e) { - // success - } - - Asserts.succeedsEventually(new Runnable() { - @Override public void run() { - Assert.assertTrue(interrupted.get()); - }}); - } - - @Test - public void testAssertReturnsEventuallyPropagatesException() throws Exception { - try { - Asserts.assertReturnsEventually(new Runnable() { - public void run() { - throw new IllegalStateException("Simulating failure"); - }}, - Duration.THIRTY_SECONDS); - Assert.fail("Should have thrown AssertionError on timeout"); - } catch (ExecutionException e) { - IllegalStateException ise = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class); - if (ise == null || !ise.toString().contains("Simulating failure")) throw e; - } - } -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/test/FixedLocaleTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/test/FixedLocaleTest.java b/utils/common/src/test/java/brooklyn/test/FixedLocaleTest.java deleted file mode 100644 index d72c5ff..0000000 --- a/utils/common/src/test/java/brooklyn/test/FixedLocaleTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.test; - -import java.util.Locale; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; - -public class FixedLocaleTest { - private Locale defaultLocale; - private Locale fixedLocale; - - public FixedLocaleTest() { - this(Locale.UK); - } - - public FixedLocaleTest(Locale fixedLocale) { - this.fixedLocale = fixedLocale; - } - - @BeforeClass - public void setUp() { - defaultLocale = Locale.getDefault(); - Locale.setDefault(fixedLocale); - } - - @AfterClass - public void tearDown() { - Locale.setDefault(defaultLocale); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/collections/CollectionFunctionalsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/collections/CollectionFunctionalsTest.java b/utils/common/src/test/java/brooklyn/util/collections/CollectionFunctionalsTest.java deleted file mode 100644 index 059fa5f..0000000 --- a/utils/common/src/test/java/brooklyn/util/collections/CollectionFunctionalsTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.collections; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -public class CollectionFunctionalsTest { - - @Test - public void testListSize() { - Assert.assertTrue(CollectionFunctionals.sizeEquals(2).apply(ImmutableList.of("x", "y"))); - Assert.assertFalse(CollectionFunctionals.sizeEquals(2).apply(null)); - Assert.assertTrue(CollectionFunctionals.sizeEquals(0).apply(ImmutableList.of())); - Assert.assertFalse(CollectionFunctionals.sizeEquals(0).apply(null)); - } - - @Test - public void testMapSize() { - Assert.assertTrue(CollectionFunctionals.<String>mapSizeEquals(2).apply(ImmutableMap.of("x", "1", "y", "2"))); - Assert.assertFalse(CollectionFunctionals.<String>mapSizeEquals(2).apply(null)); - Assert.assertTrue(CollectionFunctionals.mapSizeEquals(0).apply(ImmutableMap.of())); - Assert.assertFalse(CollectionFunctionals.mapSizeEquals(0).apply(null)); - } - - @Test - public void testMapSizeOfNull() { - Assert.assertEquals(CollectionFunctionals.mapSize().apply(null), null); - Assert.assertEquals(CollectionFunctionals.mapSize(-1).apply(null), (Integer)(-1)); - } - - @Test - public void testFirstElement() { - Assert.assertEquals(CollectionFunctionals.firstElement().apply(null), null); - Assert.assertEquals(CollectionFunctionals.firstElement().apply(ImmutableList.of("a")), "a"); - Assert.assertEquals(CollectionFunctionals.firstElement().apply(ImmutableList.of("a", "b", "c")), "a"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/collections/JsonyaTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/collections/JsonyaTest.java b/utils/common/src/test/java/brooklyn/util/collections/JsonyaTest.java deleted file mode 100644 index 1ef93a0..0000000 --- a/utils/common/src/test/java/brooklyn/util/collections/JsonyaTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.collections; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.collections.Jsonya.Navigator; - -import com.google.common.collect.ImmutableSet; - -public class JsonyaTest { - - public static Navigator<MutableMap<Object,Object>> europeMap() { - return Jsonya.newInstance().at("europe", "uk", "edinburgh") - .put("population", 500*1000) - .put("weather", "wet", "lighting", "dark") - .root().at("europe").at("france").put("population", 80*1000*1000) - .root(); - } - - @SuppressWarnings("unchecked") - @Test - public void testJsonyaMapNew() { - MutableMap<Object, Object> m = europeMap().getRootMap(); - - Assert.assertEquals(Jsonya.of(m).get("europe", "uk", "edinburgh", "population"), 500*1000); - Assert.assertEquals(Jsonya.of(m).at("europe", "uk", "edinburgh", "population").get(), 500*1000); - Assert.assertEquals(((Map<Object,Object>)Jsonya.of(m).get("europe")).keySet(), ImmutableSet.of("uk", "france")); - Assert.assertEquals(Jsonya.of(m).at("europe").getFocusMap().keySet(), ImmutableSet.of("uk", "france")); - } - - @SuppressWarnings("rawtypes") - @Test - public void testJsonyaMapExistingAndRootModification() { - Navigator<MutableMap<Object, Object>> n = Jsonya.of(europeMap().getRootMap()).at("asia") - .put(MutableMap.of("china", null)) - .put(MutableMap.of("japan", null)); - - Assert.assertTrue( n.root().at("asia").get(Map.class).containsKey("china") ); - Assert.assertTrue( ((Map)n.root().get("asia")).containsKey("japan") ); - } - - @SuppressWarnings("rawtypes") - @Test - public void testJsonyaWithList() { - Navigator<MutableMap<Object, Object>> n = europeMap(); - n.at("europe", "uk", "neighbours").list().add("ireland") - .root().at("europe", "france", "neighbours").list().add("spain", "germany").add("switzerland") - .root().at("europe", "france", "neighbours").add("lux"); - Object l = n.root().at("europe", "france", "neighbours").get(); - Assert.assertTrue(l instanceof List); - Assert.assertEquals(((List)l).size(), 4); - // this wants a map, so it creates a map in the list - n.put("east", "germany", "south", "spain"); - Assert.assertEquals(((List)l).size(), 5); - Map nd = (Map) ((List)l).get(4); - Assert.assertEquals(nd.size(), 2); - Map nd2 = (Map) n.root().get("europe", "france", "neighbours", 4); - Assert.assertEquals(nd2.size(), 2); - } - - @SuppressWarnings("rawtypes") - @Test - public void testCreateMapInList1() { - MutableMap<Object, Object> map = Jsonya.at("countries").list().map().add("europe", "uk").getRootMap(); - List l = (List)map.get("countries"); - Assert.assertEquals( ((Map)l.get(0)).get("europe"), "uk" ); - } - @SuppressWarnings("rawtypes") - @Test - public void testCreateMapInList2() { - MutableMap<Object, Object> map = Jsonya.at("countries").list().map().add("europe", "uk") - .root().at("countries").add("antarctica") - .root().at("countries").map().add("asia", (Object)null) - .at("asia").list().add("china", "japan").getRootMap(); - - List l = (List)map.get("countries"); - Assert.assertEquals( ((Map)l.get(0)).get("europe"), "uk" ); - } - - @Test - public void testJsonyaDeepSimple() { - Navigator<MutableMap<Object, Object>> n = Jsonya.of(europeMap()) - .at("europe").add("spain", "plains"); - Assert.assertEquals( n.root().get("europe", "spain"), "plains" ); - Assert.assertEquals( n.getRootMap().size(), 1 ); - Assert.assertEquals( n.root().at("europe").getFocusMap().size(), 3 ); - } - - @Test(expectedExceptions=Exception.class) - public void testJsonyaDeepSimpleFailure() { - Jsonya.of(europeMap()).at("euroope").add("spain"); - } - - @Test - public void testJsonyaDeepMoreComplicated() { - Navigator<MutableMap<Object, Object>> n = Jsonya.of(europeMap()).at("asia") - .list().add("china", "japan") - .root().add( Jsonya.newInstance().at("europe", "uk", "glasgow").put("weather", "even wetter").getRootMap() ); - - Assert.assertEquals( n.getRootMap().size(), 2 ); - Assert.assertTrue( n.root().at("asia").get(List.class).contains("china") ); - Assert.assertTrue( ((List<?>)n.root().get("asia")).contains("japan") ); - - Assert.assertEquals(n.root().at("europe", "uk").get(Map.class).size(), 2); - Assert.assertEquals(n.root().at("europe", "uk", "edinburgh", "weather").get(), "wet"); - Assert.assertEquals(n.root().at("europe", "uk", "glasgow", "weather").get(), "even wetter"); - } - - @Test - public void testJsonyaToString() { - Assert.assertEquals(europeMap().toString(), - "{ \"europe\": { \"uk\": { \"edinburgh\": { \"population\": 500000, \"weather\": \"wet\", \"lighting\": \"dark\" } }," - + " \"france\": { \"population\": 80000000 } } }"); - } - - @Test - public void testPrimitivedAndLiteralledMap() { - Object foo = new Object() { - public String toString() { return "FOO"; } - }; - - MutableMap<Object, Object> map = MutableMap.<Object,Object>of("a", 1, 2, Arrays.<Object>asList(true, 8, "8"), 'C', foo); - - Map<Object, Object> mapL = Jsonya.newInstanceLiteral().put(map).getRootMap(); - Assert.assertEquals(mapL, map); - Assert.assertEquals(mapL.get('C'), foo); - - Map<Object, Object> mapP = Jsonya.newInstancePrimitive().put(map).getRootMap(); - Assert.assertNotEquals(mapP, map); - Assert.assertEquals(mapP.get('C'), foo.toString()); - Assert.assertEquals(MutableMap.copyOf(mapP).add('C', null), MutableMap.copyOf(map).add('C', null)); - } - - @Test - public void testJsonyaBadPathNull() { - Navigator<MutableMap<Object, Object>> m = europeMap(); - // does not create (but if we 'pushed' it would) - Assert.assertNull( m.at("europe", "spain", "barcelona").get() ); - Assert.assertNull( m.root().at("europe").at("spain").at("barcelona").get() ); - } - @Test - public void testJsonyaMaybe() { - Navigator<MutableMap<Object, Object>> m = europeMap(); - Assert.assertEquals( m.at("europe", "spain", "barcelona").getMaybe().or("norealabc"), "norealabc" ); - Assert.assertEquals(m.root().at("europe").getFocusMap().keySet(), MutableSet.of("uk", "france")); - } - - @Test - public void testJsonyaPushPop() { - Navigator<MutableMap<Object, Object>> m = europeMap(); - Assert.assertTrue(m.getFocusMap().containsKey("europe")); - Assert.assertFalse(m.getFocusMap().containsKey("edinburgh")); - m.push(); - - m.at("europe", "uk"); - Assert.assertTrue(m.getFocusMap().containsKey("edinburgh")); - Assert.assertFalse(m.getFocusMap().containsKey("europe")); - - m.pop(); - Assert.assertTrue(m.getFocusMap().containsKey("europe")); - Assert.assertFalse(m.getFocusMap().containsKey("edinburgh")); - - // also check 'get' does not change focus - m.get("europe", "uk"); - Assert.assertTrue(m.getFocusMap().containsKey("europe")); - Assert.assertFalse(m.getFocusMap().containsKey("edinburgh")); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/collections/MutableListTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/collections/MutableListTest.java b/utils/common/src/test/java/brooklyn/util/collections/MutableListTest.java deleted file mode 100644 index c862e7f..0000000 --- a/utils/common/src/test/java/brooklyn/util/collections/MutableListTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.collections; - -import java.util.Arrays; -import java.util.List; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; - -@Test -public class MutableListTest { - - public void testBuilderAddArray() throws Exception { - List<Object> vals = MutableList.builder().addAll(new Object[] {1,2,3}).build(); - Assert.assertEquals(vals, ImmutableList.of(1,2,3)); - } - - public void testBuilderAddVarargs() throws Exception { - List<Object> vals = MutableList.builder().add(1,2,3).build(); - Assert.assertEquals(vals, ImmutableList.of(1,2,3)); - } - - public void testBuilderAddIterable() throws Exception { - List<Object> vals = MutableList.builder().addAll(ImmutableList.of(1,2)).addAll(ImmutableList.of(2,3)).build(); - Assert.assertEquals(vals, ImmutableList.of(1,2,2,3)); - } - - public void testBuilderAddIterator() throws Exception { - List<Object> vals = MutableList.builder().addAll(ImmutableList.of(1,2).iterator()).build(); - Assert.assertEquals(vals, ImmutableList.of(1,2)); - } - - public void testBuilderRemoval() throws Exception { - List<Object> vals = MutableList.builder() - .add(1,2,3) - .remove(2) - .add(4) - .build(); - Assert.assertEquals(vals, ImmutableList.of(1,3,4)); - } - - public void testBuilderRemoveAll() throws Exception { - List<Object> vals = MutableList.builder() - .add(1,2,3) - .removeAll(ImmutableList.of(2,3)) - .add(4) - .build(); - Assert.assertEquals(vals, ImmutableList.of(1,4)); - } - - public void testEqualsExact() { - List<Object> a = MutableList.<Object>of("a", 1, "b", false); - List<Object> b = MutableList.<Object>of("a", 1, "b", false); - Assert.assertEquals(a, b); - } - - public void testNotEqualsUnordered() { - List<Object> a = MutableList.<Object>of("a", 1, "b", false); - List<Object> b = MutableList.<Object>of("b", false, "a", 1); - Assert.assertNotEquals(a, b); - } - - public void testEqualsDifferentTypes() { - List<Object> a = MutableList.<Object>of("a", 1, "b", false); - List<Object> b = Arrays.<Object>asList("a", 1, "b", false); - Assert.assertEquals(a, b); - Assert.assertEquals(b, a); - } - - public void testEqualsDifferentTypes2() { - List<Object> a = MutableList.<Object>of("http"); - List<String> b = Arrays.<String>asList("http"); - Assert.assertEquals(a, b); - Assert.assertEquals(b, a); - } - - public void testContainingNullAndUnmodifiable() { - MutableList<Object> x = MutableList.<Object>of("x", null); - Assert.assertTrue(x.contains(null)); - - List<Object> x1 = x.asUnmodifiable(); - List<Object> x2 = x.asUnmodifiableCopy(); - List<Object> x3 = x.asImmutableCopy(); - - x.remove(null); - Assert.assertFalse(x.contains(null)); - Assert.assertFalse(x1.contains(null)); - Assert.assertTrue(x2.contains(null)); - Assert.assertTrue(x3.contains(null)); - - try { x1.remove("x"); Assert.fail(); } catch (Exception e) { /* expected */ } - try { x2.remove("x"); Assert.fail(); } catch (Exception e) { /* expected */ } - try { x3.remove("x"); Assert.fail(); } catch (Exception e) { /* expected */ } - - Assert.assertTrue(x1.contains("x")); - Assert.assertTrue(x2.contains("x")); - Assert.assertTrue(x3.contains("x")); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/collections/MutableMapTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/collections/MutableMapTest.java b/utils/common/src/test/java/brooklyn/util/collections/MutableMapTest.java deleted file mode 100644 index 8d14d36..0000000 --- a/utils/common/src/test/java/brooklyn/util/collections/MutableMapTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.collections; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -@Test -public class MutableMapTest { - - public void testEqualsExact() { - Map<Object,Object> a = MutableMap.<Object,Object>of("a", 1, "b", false); - Map<Object,Object> b = MutableMap.<Object,Object>of("a", 1, "b", false); - Assert.assertEquals(a, b); - } - - public void testEqualsUnordered() { - Map<Object,Object> a = MutableMap.<Object,Object>of("a", 1, "b", false); - Map<Object,Object> b = MutableMap.<Object,Object>of("b", false, "a", 1); - Assert.assertEquals(a, b); - } - - public void testEqualsDifferentTypes() { - Map<Object,Object> a = MutableMap.<Object,Object>of("a", 1, "b", false); - Map<Object,Object> b = ImmutableMap.<Object,Object>of("b", false, "a", 1); - Assert.assertEquals(a, b); - } - - public void testListOfMaps() { - MutableMap<Object, Object> map = MutableMap.<Object,Object>of("a", 1, 2, Arrays.<Object>asList(true, "8")); - ArrayList<Object> l = new ArrayList<Object>(); - l.add(true); l.add("8"); - MutableMap<Object, Object> map2 = MutableMap.<Object,Object>of(2, l, "a", 1); - Assert.assertEquals(map, map2); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/collections/QuorumChecksTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/collections/QuorumChecksTest.java b/utils/common/src/test/java/brooklyn/util/collections/QuorumChecksTest.java deleted file mode 100644 index bf53d68..0000000 --- a/utils/common/src/test/java/brooklyn/util/collections/QuorumChecksTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.collections; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.collections.QuorumCheck.QuorumChecks; - -public class QuorumChecksTest { - - @Test - public void testAll() { - QuorumCheck q = QuorumChecks.all(); - Assert.assertTrue(q.isQuorate(2, 2)); - Assert.assertFalse(q.isQuorate(1, 2)); - Assert.assertTrue(q.isQuorate(0, 0)); - } - - @Test - public void testAlwaysTrue() { - QuorumCheck q = QuorumChecks.alwaysTrue(); - Assert.assertTrue(q.isQuorate(0, 2)); - Assert.assertTrue(q.isQuorate(1, 2)); - Assert.assertTrue(q.isQuorate(0, 0)); - } - - @Test - public void testAtLeastOne() { - QuorumCheck q = QuorumChecks.atLeastOne(); - Assert.assertTrue(q.isQuorate(2, 2)); - Assert.assertTrue(q.isQuorate(1, 2)); - Assert.assertFalse(q.isQuorate(0, 0)); - } - - @Test - public void testAllAndAtLeastOne() { - QuorumCheck q = QuorumChecks.atLeastOne(); - Assert.assertFalse(q.isQuorate(0, 2)); - Assert.assertTrue(q.isQuorate(1, 2)); - Assert.assertFalse(q.isQuorate(0, 0)); - } - - @Test - public void testAtLeastOneUnlessEmpty() { - QuorumCheck q = QuorumChecks.atLeastOneUnlessEmpty(); - Assert.assertFalse(q.isQuorate(0, 2)); - Assert.assertTrue(q.isQuorate(1, 2)); - Assert.assertTrue(q.isQuorate(0, 0)); - } - - @Test - public void testAtLeastOneUnlessEmptyString() { - QuorumCheck q = QuorumChecks.of("atLeastOneUnlessEmpty"); - Assert.assertFalse(q.isQuorate(0, 2)); - Assert.assertTrue(q.isQuorate(1, 2)); - Assert.assertTrue(q.isQuorate(0, 0)); - } - - @Test - public void testLinearTwoPointsNeedMinTwo() { - QuorumCheck q = QuorumChecks.of("[ [0,2], [1,2] ]"); - Assert.assertTrue(q.isQuorate(2, 2)); - Assert.assertTrue(q.isQuorate(2, 10)); - Assert.assertFalse(q.isQuorate(1, 1)); - } - - @Test - public void testLinearNeedHalfToTenAndTenPercentAtHundred() { - QuorumCheck q = QuorumChecks.of("[ [0,0], [10,5], [100,10], [200, 20] ]"); - Assert.assertTrue(q.isQuorate(2, 2)); - Assert.assertTrue(q.isQuorate(1, 2)); - Assert.assertTrue(q.isQuorate(0, 0)); - Assert.assertFalse(q.isQuorate(1, 10)); - Assert.assertTrue(q.isQuorate(6, 10)); - Assert.assertFalse(q.isQuorate(7, 50)); - Assert.assertTrue(q.isQuorate(8, 50)); - Assert.assertFalse(q.isQuorate(9, 100)); - Assert.assertTrue(q.isQuorate(11, 100)); - Assert.assertFalse(q.isQuorate(19, 200)); - Assert.assertTrue(q.isQuorate(21, 200)); - Assert.assertFalse(q.isQuorate(29, 300)); - Assert.assertTrue(q.isQuorate(31, 300)); - } - - - - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/collections/TimeWindowedListTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/collections/TimeWindowedListTest.java b/utils/common/src/test/java/brooklyn/util/collections/TimeWindowedListTest.java deleted file mode 100644 index d1c2293..0000000 --- a/utils/common/src/test/java/brooklyn/util/collections/TimeWindowedListTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.collections; - -import static brooklyn.util.time.Duration.ONE_MILLISECOND; -import static org.testng.Assert.assertEquals; - -import java.util.List; - -import org.testng.annotations.Test; - -import brooklyn.util.time.Duration; - -import com.google.common.collect.Lists; - -@SuppressWarnings({"rawtypes","unchecked"}) -public class TimeWindowedListTest { - - private static final Duration TEN_MILLISECONDS = Duration.millis(10); - private static final Duration HUNDRED_MILLISECONDS = Duration.millis(100); - private static final Duration TWO_MILLISECONDS = Duration.millis(2); - - @Test - public void testKeepsMinVals() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 1L, "minVals", 2)); - assertEquals(list.getValues(2L), timestampedValues()); - - list.add("a", 0L); - assertEquals(list.getValues(2L), timestampedValues("a", 0L)); - - list.add("b", 100L); - assertEquals(list.getValues(102L), timestampedValues("a", 0L, "b", 100L)); - - list.add("c", 200L); - assertEquals(list.getValues(202L), timestampedValues("b", 100L, "c", 200L)); - } - - @Test - public void testKeepsOnlyRecentVals() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 1000L)); - - list.add("a", 0L); - list.add("b", 100L); - assertEquals(list.getValues(1000L), timestampedValues("a", 0L, "b", 100L)); - assertEquals(list.getValues(1100L), timestampedValues("b", 100L)); - assertEquals(list.getValues(1101L), Lists.newArrayList()); - } - - @Test - public void testKeepsMinExpiredVals() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 1000L, "minExpiredVals", 1)); - - list.add("a", 0L); - list.add("b", 100L); - assertEquals(list.getValues(1001L), timestampedValues("a", 0L, "b", 100L)); - assertEquals(list.getValues(1101L), timestampedValues("b", 100L)); - } - - @Test - public void testGetsSubSetOfRecentVals() { - TimeWindowedList list = new TimeWindowedList<Object>(Duration.ONE_SECOND); - - list.add("a", 0L); - list.add("b", 100L); - assertEquals(list.getValuesInWindow(100L, HUNDRED_MILLISECONDS), timestampedValues("a", 0L, "b", 100L)); - assertEquals(list.getValuesInWindow(101L, ONE_MILLISECOND), timestampedValues("b", 100L)); - } - - @Test - public void testGetsSubSetOfValsIncludingOneMinExpiredVal() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 1000L, "minExpiredVals", 1)); - - list.add("a", 0L); - list.add("b", 100L); - assertEquals(list.getValuesInWindow(100L, HUNDRED_MILLISECONDS), timestampedValues("a", 0L, "b", 100L)); - assertEquals(list.getValuesInWindow(101L, TWO_MILLISECONDS), timestampedValues("a", 0L, "b", 100L)); - assertEquals(list.getValuesInWindow(102L, ONE_MILLISECOND), timestampedValues("b", 100L)); - assertEquals(list.getValuesInWindow(1001L, ONE_MILLISECOND), timestampedValues("b", 100L)); - } - - @Test - public void testGetsWindowWithMinWhenEmpty() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 1L, "minVals", 1)); - assertEquals(list.getValuesInWindow(1000L, TEN_MILLISECONDS), timestampedValues()); - } - - @Test - public void testGetsWindowWithMinExpiredWhenEmpty() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 1L, "minExpiredVals", 1)); - assertEquals(list.getValuesInWindow(1000L, TEN_MILLISECONDS), timestampedValues()); - } - - @Test - public void testGetsWindowWithMinValsWhenExpired() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 1L, "minVals", 1)); - list.add("a", 0L); - list.add("b", 1L); - - assertEquals(list.getValuesInWindow(1000L, TEN_MILLISECONDS), timestampedValues("b", 1L)); - } - - @Test - public void testZeroSizeWindowWithOneExpiredContainsOnlyMostRecentValue() { - TimeWindowedList list = new TimeWindowedList<Object>(MutableMap.of("timePeriod", 0L, "minExpiredVals", 1)); - - list.add("a", 0L); - assertEquals(list.getValuesInWindow(0L, HUNDRED_MILLISECONDS), timestampedValues("a", 0L)); - assertEquals(list.getValuesInWindow(2L, ONE_MILLISECOND), timestampedValues("a", 0L)); - - list.add("b", 100L); - assertEquals(list.getValuesInWindow(100L, ONE_MILLISECOND), timestampedValues("b", 100L)); - assertEquals(list.getValuesInWindow(102L, ONE_MILLISECOND), timestampedValues("b", 100L)); - } - - private <T> List<TimestampedValue<T>> timestampedValues() { - return Lists.newArrayList(); - } - - private <T> List<TimestampedValue<T>> timestampedValues(T v1, long t1) { - return Lists.newArrayList(new TimestampedValue<T>(v1, t1)); - } - - private <T> List<TimestampedValue<T>> timestampedValues(T v1, long t1, T v2, long t2) { - return Lists.newArrayList(new TimestampedValue<T>(v1, t1), new TimestampedValue<T>(v2, t2)); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/exceptions/ExceptionsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/exceptions/ExceptionsTest.java b/utils/common/src/test/java/brooklyn/util/exceptions/ExceptionsTest.java deleted file mode 100644 index 5bb83aa..0000000 --- a/utils/common/src/test/java/brooklyn/util/exceptions/ExceptionsTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.exceptions; - -import java.util.ConcurrentModificationException; -import java.util.concurrent.ExecutionException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableSet; - -public class ExceptionsTest { - - private static final Logger log = LoggerFactory.getLogger(ExceptionsTest.class); - - @Test - public void test12CollapseCompound() throws Exception { - RuntimeException e = Exceptions.create("test1", MutableSet.of(new IllegalStateException("test2"), new IllegalStateException("test3"))); - assert12StandardChecks(e, false); - } - - @Test - public void test12CollapsePropagatedExecutionCompoundBoring() throws Exception { - RuntimeException e = new PropagatedRuntimeException("test1", - new ExecutionException(Exceptions.create(MutableSet.of(new IllegalStateException("test2"), new IllegalStateException("test3"))))); - assert12StandardChecks(e, true); - } - - @Test - public void test12CollapsePropagatedCompoundConcMod() throws Exception { - RuntimeException e = new PropagatedRuntimeException("test1", - new ExecutionException(Exceptions.create(MutableSet.of(new ConcurrentModificationException("test2"), new ConcurrentModificationException("test3"))))); - assert12StandardChecks(e, true); - assertContains(e, "ConcurrentModification"); - } - - @Test - public void testCollapseTextWhenExceptionMessageEmpty() throws Exception { - String text = Exceptions.collapseText(new ExecutionException(new IllegalStateException())); - Assert.assertNotNull(text); - } - - private void assert12StandardChecks(RuntimeException e, boolean isPropagated) { - String collapseText = Exceptions.collapseText(e); - log.info("Exception collapsing got: "+collapseText+" ("+e+")"); - assertContains(e, "test1"); - assertContains(e, "test2"); - - if (isPropagated) - assertContains(e, "2 errors, including"); - else - assertContains(e, "2 errors including"); - - assertNotContains(e, "IllegalState"); - assertNotContains(e, "CompoundException"); - Assert.assertFalse(collapseText.contains("Propagated"), "should NOT have had Propagated: "+collapseText); - - if (isPropagated) - Assert.assertTrue(e.toString().contains("Propagate"), "SHOULD have had Propagated: "+e); - else - Assert.assertFalse(e.toString().contains("Propagate"), "should NOT have had Propagated: "+e); - } - - private static void assertContains(Exception e, String keyword) { - Assert.assertTrue(e.toString().contains(keyword), "Missing keyword '"+keyword+"' in exception toString: "+e); - Assert.assertTrue(Exceptions.collapseText(e).contains(keyword), "Missing keyword '"+keyword+"' in collapseText: "+Exceptions.collapseText(e)); - } - private static void assertNotContains(Exception e, String keyword) { - Assert.assertFalse(e.toString().contains(keyword), "Unwanted keyword '"+keyword+"' in exception toString: "+e); - Assert.assertFalse(Exceptions.collapseText(e).contains(keyword), "Unwanted keyword '"+keyword+"' in collapseText: "+Exceptions.collapseText(e)); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/guava/FunctionalsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/guava/FunctionalsTest.java b/utils/common/src/test/java/brooklyn/util/guava/FunctionalsTest.java deleted file mode 100644 index 3da3532..0000000 --- a/utils/common/src/test/java/brooklyn/util/guava/FunctionalsTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.guava; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.math.MathFunctions; - -import com.google.common.base.Predicates; -import com.google.common.base.Suppliers; - -public class FunctionalsTest { - - @Test - public void testChain() { - Assert.assertEquals(Functionals.chain(MathFunctions.plus(1), MathFunctions.times(2)).apply(3), (Integer)8); - Assert.assertEquals(Functionals.chain(MathFunctions.times(2), MathFunctions.plus(1)).apply(3), (Integer)7); - } - - @Test - public void testIf() { - IfFunctionsTest.checkTF(Functionals.ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?").build(), "?"); - } - - @Test - public void testIfNoBuilder() { - IfFunctionsTest.checkTF(Functionals.ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?"), "?"); - } - - @Test - public void testIfPredicateAndSupplier() { - IfFunctionsTest.checkTF(Functionals.ifPredicate(Predicates.equalTo(false)).get(Suppliers.ofInstance("F")) - .ifEquals(true).value("T").defaultGet(Suppliers.ofInstance("?")).build(), "?"); - } - - @Test - public void testIfNotEqual() { - IfFunctionsTest.checkTF(Functionals.ifNotEquals(false).value("T").defaultValue("F").build(), "T"); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/guava/IfFunctionsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/guava/IfFunctionsTest.java b/utils/common/src/test/java/brooklyn/util/guava/IfFunctionsTest.java deleted file mode 100644 index 3e88d6c..0000000 --- a/utils/common/src/test/java/brooklyn/util/guava/IfFunctionsTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.guava; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.guava.IfFunctions.IfFunctionBuilder; - -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import com.google.common.base.Suppliers; - -public class IfFunctionsTest { - - @Test - public void testCommonUsage() { - checkTF(IfFunctions.ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?").build(), "?"); - } - - @Test - public void testNoBuilder() { - checkTF(IfFunctions.ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?"), "?"); - } - - @Test - public void testPredicateAndSupplier() { - // we cannot use checkTF here as an IntelliJ issues causes the project to fail to launch as IntelliJ does not - // recognize the return value of IfFunctions.ifPredicate as Function<Boolean, String> - Function function = IfFunctions.ifPredicate(Predicates.equalTo(false)).get(Suppliers.ofInstance("F")) - .ifEquals(true).value("T").defaultGet(Suppliers.ofInstance("?")).build(); - Assert.assertEquals(function.apply(true), "T"); - Assert.assertEquals(function.apply(false), "F"); - Assert.assertEquals(function.apply(null), "?"); - } - - @Test - public void testNoDefault() { - checkTF(IfFunctions.ifEquals(false).value("F").ifEquals(true).value("T").build(), null); - } - - @Test - public void testNotEqual() { - checkTF(IfFunctions.ifNotEquals(false).value("T").defaultValue("F").build(), "T"); - } - - @Test - public void testFunction() { - checkTF(IfFunctions.ifNotEquals((Boolean)null).apply(new Function<Boolean, String>() { - @Override - public String apply(Boolean input) { - return input.toString().toUpperCase().substring(0, 1); - } - }).defaultValue("?"), "?"); - } - - @Test - public void testWithCast() { - Function<Boolean, String> f = IfFunctions.ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?").build(); - checkTF(f, "?"); - } - - @Test - public void testWithoutCast() { - Function<Boolean, String> f = IfFunctions.newInstance(Boolean.class, String.class).ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?").build(); - checkTF(f, "?"); - } - - @Test - public void testSupportsReplace() { - checkTF(IfFunctions.ifEquals(false).value("false").ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?").build(), "?"); - } - - @Test - public void testIsImmutableAndSupportsReplace() { - IfFunctionBuilder<Boolean, String> f = IfFunctions.ifEquals(false).value("F").ifEquals(true).value("T").defaultValue("?"); - IfFunctionBuilder<Boolean, String> f2 = f.ifEquals(false).value("false").defaultValue("X"); - IfFunctionBuilder<Boolean, String> f3 = f2.ifEquals(false).value("F"); - checkTF(f, "?"); - checkTF(f3, "X"); - Assert.assertEquals(f2.apply(false), "false"); - } - - static void checkTF(Function<Boolean, String> f, Object defaultValue) { - Assert.assertEquals(f.apply(true), "T"); - Assert.assertEquals(f.apply(false), "F"); - Assert.assertEquals(f.apply(null), defaultValue); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/guava/KeyTransformingLoadingCacheTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/guava/KeyTransformingLoadingCacheTest.java b/utils/common/src/test/java/brooklyn/util/guava/KeyTransformingLoadingCacheTest.java deleted file mode 100644 index ed3c3ad..0000000 --- a/utils/common/src/test/java/brooklyn/util/guava/KeyTransformingLoadingCacheTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.guava; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; - -import java.util.Map; -import java.util.Set; - -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.base.Function; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; - -public class KeyTransformingLoadingCacheTest { - - LoadingCache<Integer, Integer> doublingCache; - LoadingCache<String, Integer> stringDoubler; - LoadingCache<Map<String, Integer>, Map<Integer, String>> keyValueSwapCache; - - @BeforeMethod(alwaysRun = true) - public void setUp() { - // Doubles Integer inputs - doublingCache = CacheBuilder.newBuilder() - .recordStats() - .build(new CacheLoader<Integer, Integer>() { - @Override - public Integer load(Integer key) throws Exception { - return key * 2; - } - }); - // Turns string to integer and doubles - stringDoubler = KeyTransformingLoadingCache.from(doublingCache, - new Function<String, Integer>(){ - @Override - public Integer apply(String input) { - return Integer.valueOf(input); - } - }); - // Swaps keys with values - keyValueSwapCache = CacheBuilder.newBuilder() - .recordStats() - .build(new CacheLoader<Map<String, Integer>, Map<Integer, String>>() { - @Override - public Map<Integer, String> load(Map<String, Integer> key) throws Exception { - Map<Integer, String> out = Maps.newHashMapWithExpectedSize(key.size()); - for (Map.Entry<String, Integer> entry : key.entrySet()) { - out.put(entry.getValue(), entry.getKey()); - } - return out; - } - }); - } - - @Test - public void testIdentityCache() { - assertEquals(stringDoubler.getUnchecked("10"), Integer.valueOf(20)); - } - - @Test - public void testGetIfPresent() { - assertNull(stringDoubler.getIfPresent("10"), "Cache should be empty"); - assertEquals(stringDoubler.getUnchecked("10"), Integer.valueOf(20), "Cache should load value for '10'"); - assertEquals(stringDoubler.getIfPresent("10"), Integer.valueOf(20), "Cache should load value for '10'"); - assertNull(stringDoubler.getIfPresent("20"), "Cache should have no value for '20'"); - assertNull(stringDoubler.getIfPresent(new Object()), "Cache should have no value for arbitrary Object"); - } - - @Test - public void testInvalidate() { - stringDoubler.getUnchecked("10"); - assertEquals(stringDoubler.size(), 1); - stringDoubler.invalidate(new Object()); - assertEquals(stringDoubler.size(), 1); - stringDoubler.invalidate("10"); - assertEquals(stringDoubler.size(), 0, "Expected cache to be empty after sole entry was invalidated"); - } - - @Test - public void testSubsetOfMapKeys() { - final Set<String> validKeys = ImmutableSet.of("a", "b", "c"); - LoadingCache<Map<String, Integer>, Map<Integer, String>> keySubset = - KeyTransformingLoadingCache.from(keyValueSwapCache, new Function<Map<String, Integer>, Map<String, Integer>>() { - @Override - public Map<String, Integer> apply(Map<String, Integer> input) { - Map<String, Integer> replacement = Maps.newHashMap(input); - replacement.keySet().retainAll(validKeys); - return replacement; - } - }); - - Map<Integer, String> output = keySubset.getUnchecked(ImmutableMap.of("a", 1, "b", 2, "d", 4)); - assertEquals(output, ImmutableMap.of(1, "a", 2, "b")); - assertEquals(keySubset.size(), 1, "Expected cache to contain one value"); - assertEquals(keySubset.stats().loadCount(), 1, "Expected cache to have loaded one value"); - - // Check input with different key reducing to same map gives same output - Map<Integer, String> output2 = keySubset.getUnchecked(ImmutableMap.of("a", 1, "b", 2, "z", 26)); - assertEquals(output2, output); - assertEquals(keySubset.size(), 1, "Expected cache to contain one value"); - assertEquals(keySubset.stats().loadCount(), 1, "Expected cache to have loaded one value"); - - // And - keySubset.getUnchecked(ImmutableMap.of("c", 3)); - assertEquals(keySubset.size(), 2, "Expected cache to contain two values"); - assertEquals(keySubset.stats().loadCount(), 2, "Expected cache to have loaded a second value"); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/internal/CommandLineUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/internal/CommandLineUtilTest.java b/utils/common/src/test/java/brooklyn/util/internal/CommandLineUtilTest.java deleted file mode 100644 index 642ef7b..0000000 --- a/utils/common/src/test/java/brooklyn/util/internal/CommandLineUtilTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.internal; - -import static org.testng.Assert.assertEquals; - -import java.util.Arrays; -import java.util.List; - -import org.testng.annotations.Test; - -import brooklyn.util.CommandLineUtil; - -import com.google.common.collect.Lists; - -public class CommandLineUtilTest { - - @Test - public void testGetCommandReturnsDefaultIfNotPresent() throws Exception { - List<String> args = Lists.newArrayList("k1", "v1"); - String result = CommandLineUtil.getCommandLineOption(args, "notthere", "mydefault"); - assertEquals(result, "mydefault"); - assertEquals(args, Arrays.asList("k1", "v1")); - } - - @Test - public void testGetCommandReturnsParamAndRemovesIt() throws Exception { - List<String> args = Lists.newArrayList("k1", "v1"); - String result = CommandLineUtil.getCommandLineOption(args, "k1"); - assertEquals(result, "v1"); - assertEquals(args, Arrays.asList()); - } - - @Test - public void testGetCommandReturnsParamAndRemovesItButLeavesOtherVals() throws Exception { - List<String> args = Lists.newArrayList("k1", "v1", "k2", "v2"); - String result = CommandLineUtil.getCommandLineOption(args, "k1"); - assertEquals(result, "v1"); - assertEquals(args, Arrays.asList("k2", "v2")); - } - - @Test - public void testGetCommandReturnsParamAndRemovesItButLeavesOtherValsWhenDuplicateVals() throws Exception { - List<String> args = Lists.newArrayList("k1", "vdup", "k2", "v2", "k3", "vdup"); - String result = CommandLineUtil.getCommandLineOption(args, "k3"); - assertEquals(result, "vdup"); - assertEquals(args, Arrays.asList("k1", "vdup", "k2", "v2")); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/internal/JavaClassNamesCallerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/internal/JavaClassNamesCallerTest.java b/utils/common/src/test/java/brooklyn/util/internal/JavaClassNamesCallerTest.java deleted file mode 100644 index 1c4359b..0000000 --- a/utils/common/src/test/java/brooklyn/util/internal/JavaClassNamesCallerTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.internal; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.javalang.JavaClassNames; - -/** test must not be in {@link JavaClassNames} directory due to exclusion! */ -public class JavaClassNamesCallerTest { - - @Test - public void testCallerIsMe() { - String result = JavaClassNames.niceClassAndMethod(); - Assert.assertEquals(result, "JavaClassNamesCallerTest.testCallerIsMe"); - } - - @Test - public void testCallerIsYou() { - other(); - } - - public void other() { - String result = JavaClassNames.callerNiceClassAndMethod(1); - Assert.assertEquals(result, "JavaClassNamesCallerTest.testCallerIsYou"); - } - - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/io/FileUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/io/FileUtilTest.java b/utils/common/src/test/java/brooklyn/util/io/FileUtilTest.java deleted file mode 100644 index eb2c4b1..0000000 --- a/utils/common/src/test/java/brooklyn/util/io/FileUtilTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.io; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; - -import java.io.File; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.util.os.Os; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableList; -import com.google.common.io.Files; - -public class FileUtilTest { - - private File file; - private File dir; - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - file = File.createTempFile("fileUtilsTest", ".tmp"); - dir = Files.createTempDir(); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (file != null) file.delete(); - if (dir != null) Os.deleteRecursively(dir); - } - - @Test(groups="Integration") - public void testSetFilePermission600() throws Exception { - FileUtil.setFilePermissionsTo600(file); - String permissions = FileUtil.getFilePermissions(file).get(); - assertEquals(permissions, "-rw-------"); - } - - @Test(groups="Integration") - public void testSetFilePermission700() throws Exception { - FileUtil.setFilePermissionsTo700(file); - String permissions = FileUtil.getFilePermissions(file).get(); - assertEquals(permissions, "-rwx------"); - } - - @Test(groups="Integration") - public void testSetDirPermission700() throws Exception { - FileUtil.setFilePermissionsTo700(dir); - String permissions = FileUtil.getFilePermissions(dir).get(); - assertEquals(permissions, "drwx------"); - } - - @Test(groups="Integration") - public void testMoveDir() throws Exception { - File destParent = Files.createTempDir(); - try { - Files.write("abc", new File(dir, "afile"), Charsets.UTF_8); - File destDir = new File(destParent, "dest"); - - FileUtil.moveDir(dir, destDir); - - assertEquals(Files.readLines(new File(destDir, "afile"), Charsets.UTF_8), ImmutableList.of("abc")); - assertFalse(dir.exists()); - } finally { - if (destParent != null) Os.deleteRecursively(destParent); - } - } - - @Test(groups="Integration") - public void testCopyDir() throws Exception { - File destParent = Files.createTempDir(); - try { - Files.write("abc", new File(dir, "afile"), Charsets.UTF_8); - File destDir = new File(destParent, "dest"); - - FileUtil.copyDir(dir, destDir); - - assertEquals(Files.readLines(new File(destDir, "afile"), Charsets.UTF_8), ImmutableList.of("abc")); - assertEquals(Files.readLines(new File(dir, "afile"), Charsets.UTF_8), ImmutableList.of("abc")); - } finally { - if (destParent != null) Os.deleteRecursively(destParent); - } - } - - // Never run this as root! You really don't want to mess with permissions of these files! - // Visual inspection test that we get the log message just once saying: - // WARN Failed to set permissions to 600 for file /etc/hosts: setRead=false, setWrite=false, setExecutable=false; subsequent failures (on any file) will be logged at trace - // Disabled because really don't want to mess up anyone's system, and also no automated assertions about log messages. - @Test(groups="Integration", enabled=false) - public void testLogsWarningOnceIfCannotSetPermission() throws Exception { - File file = new File("/etc/hosts"); - FileUtil.setFilePermissionsTo600(file); - FileUtil.setFilePermissionsTo600(file); - FileUtil.setFilePermissionsTo700(file); - FileUtil.setFilePermissionsTo700(file); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/javalang/BoxingTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/javalang/BoxingTest.java b/utils/common/src/test/java/brooklyn/util/javalang/BoxingTest.java deleted file mode 100644 index de1ffcb..0000000 --- a/utils/common/src/test/java/brooklyn/util/javalang/BoxingTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.javalang; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class BoxingTest { - - @Test - public static void testIntPrimitiveAndBoxed() { - Assert.assertEquals(Integer.TYPE.getName(), "int"); - - Class<?> t = Boxing.getPrimitiveType("int").get(); - Assert.assertEquals(t, Integer.TYPE); - - Class<?> bt = Boxing.boxedType(t); - Assert.assertEquals(bt, Integer.class); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/javalang/EnumsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/javalang/EnumsTest.java b/utils/common/src/test/java/brooklyn/util/javalang/EnumsTest.java deleted file mode 100644 index 1d9b776..0000000 --- a/utils/common/src/test/java/brooklyn/util/javalang/EnumsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.javalang; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class EnumsTest { - - private static enum SomeENum { E_300, E_624, WORD_UP, aliceTheCamel } - - @Test - public static void testValueOf() { - Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "e_300").get(), SomeENum.E_300); - Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "e_624").get(), SomeENum.E_624); - Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "ALICE_THE_CAMEL").get(), SomeENum.aliceTheCamel); - Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "alice_the_camel").get(), SomeENum.aliceTheCamel); - Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "wordUp").get(), SomeENum.WORD_UP); - Assert.assertEquals(Enums.valueOfIgnoreCase(SomeENum.class, "wordup").get(), SomeENum.WORD_UP); - Assert.assertFalse(Enums.valueOfIgnoreCase(SomeENum.class, "MSG").isPresent()); - Assert.assertFalse(Enums.valueOfIgnoreCase(SomeENum.class, "alice_thecamel").isPresent()); - Assert.assertFalse(Enums.valueOfIgnoreCase(SomeENum.class, "_word_up").isPresent()); - } - - @Test - public static void testAllValuesEnumerated() { - Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "E_624", "WORD_UP", "aliceTheCamel"); - } - - @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover values.*vitamin.*") - public static void testAllValuesEnumeratedExtra() { - Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "E_624", "Vitamin C", "wordUp", "alice_the_camel"); - } - - @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover enums.*E_624.*leftover values.*") - public static void testAllValuesEnumeratedMissing() { - Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "word_UP", "aliceTheCamel"); - } - - @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover enums.*E_624.*leftover values.*msg.*") - public static void testAllValuesEnumeratedMissingAndExtra() { - Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "MSG", "WORD_UP", "aliceTheCamel"); - } - - @Test(expectedExceptions=IllegalStateException.class, expectedExceptionsMessageRegExp = ".*leftover enums.*\\[aliceTheCamel\\].*leftover values.*alice_thecamel.*") - public static void testAllValuesEnumeratedNoMatchBadCamel() { - Enums.checkAllEnumeratedIgnoreCase(SomeENum.class, "e_300", "E_624", "WORD_UP", "alice_TheCamel"); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/javalang/JavaClassNamesTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/javalang/JavaClassNamesTest.java b/utils/common/src/test/java/brooklyn/util/javalang/JavaClassNamesTest.java deleted file mode 100644 index a41c91e..0000000 --- a/utils/common/src/test/java/brooklyn/util/javalang/JavaClassNamesTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.javalang; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.reflect.TypeToken; - -public class JavaClassNamesTest { - - @Test - public void testType() { - Assert.assertEquals(JavaClassNames.type(this), JavaClassNamesTest.class); - Assert.assertEquals(JavaClassNames.type(JavaClassNamesTest.class), JavaClassNamesTest.class); - } - - @Test - public void testPackage() { - Assert.assertEquals(JavaClassNames.packageName(JavaClassNamesTest.class), "brooklyn.util.javalang"); - Assert.assertEquals(JavaClassNames.packagePath(JavaClassNamesTest.class), "/brooklyn/util/javalang/"); - } - - @Test - public void testResolveName() { - Assert.assertEquals(JavaClassNames.resolveName(this, "foo.txt"), "/brooklyn/util/javalang/foo.txt"); - Assert.assertEquals(JavaClassNames.resolveName(JavaClassNamesTest.class, "foo.txt"), "/brooklyn/util/javalang/foo.txt"); - Assert.assertEquals(JavaClassNames.resolveName(this, "/foo.txt"), "/foo.txt"); - Assert.assertEquals(JavaClassNames.resolveName(this, "/bar/foo.txt"), "/bar/foo.txt"); - Assert.assertEquals(JavaClassNames.resolveName(this, "bar/foo.txt"), "/brooklyn/util/javalang/bar/foo.txt"); - } - - @Test - public void testResolveClasspathUrls() { - Assert.assertEquals(JavaClassNames.resolveClasspathUrl(this, "foo.txt"), "classpath://brooklyn/util/javalang/foo.txt"); - Assert.assertEquals(JavaClassNames.resolveClasspathUrl(JavaClassNamesTest.class, "/foo.txt"), "classpath://foo.txt"); - Assert.assertEquals(JavaClassNames.resolveClasspathUrl(JavaClassNamesTest.class, "http://localhost/foo.txt"), "http://localhost/foo.txt"); - } - - @Test - public void testSimpleClassNames() { - Assert.assertEquals(JavaClassNames.simpleClassName(this), "JavaClassNamesTest"); - Assert.assertEquals(JavaClassNames.simpleClassName(JavaClassNames.class), JavaClassNames.class.getSimpleName()); - Assert.assertEquals(JavaClassNames.simpleClassName(TypeToken.of(JavaClassNames.class)), JavaClassNames.class.getSimpleName()); - - Assert.assertEquals(JavaClassNames.simpleClassName(JavaClassNames.class.getSimpleName()), "String"); - Assert.assertEquals(JavaClassNames.simplifyClassName(JavaClassNames.class.getSimpleName()), JavaClassNames.class.getSimpleName()); - - Assert.assertEquals(JavaClassNames.simpleClassName(1), "Integer"); - Assert.assertEquals(JavaClassNames.simpleClassName(new String[][] { }), "String[][]"); - - // primitives? - Assert.assertEquals(JavaClassNames.simpleClassName(new int[] { 1, 2, 3 }), "int[]"); - - // anonymous - String anon1 = JavaClassNames.simpleClassName(new Object() {}); - Assert.assertTrue(anon1.startsWith(JavaClassNamesTest.class.getName()+"$"), "anon class is: "+anon1); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/javalang/MemoryUsageTrackerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/javalang/MemoryUsageTrackerTest.java b/utils/common/src/test/java/brooklyn/util/javalang/MemoryUsageTrackerTest.java deleted file mode 100644 index 747abc5..0000000 --- a/utils/common/src/test/java/brooklyn/util/javalang/MemoryUsageTrackerTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.javalang; - -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.test.Asserts; -import brooklyn.util.collections.MutableList; -import brooklyn.util.guava.Maybe; -import brooklyn.util.text.Strings; - -public class MemoryUsageTrackerTest { - - private static final Logger LOG = LoggerFactory.getLogger(MemoryUsageTrackerTest.class); - - @Test(groups="Integration") - public void testBigUsage() { - final int ALLOCATION_CHUNK_SIZE = 10*1000*1000; // 10MB - - // Don't just use runtime.maxMemory()*2; javadoc says: - // If there is no inherent limit then the value java.lang.Long.MAX_VALUE will be returned. - // Therefore cap at 10GB. - final long MAX_MEMORY_CAP = 10*1024*1024*1024L; // 10GB - final long maxMemory = Math.min(Runtime.getRuntime().maxMemory(), MAX_MEMORY_CAP); - - List<Maybe<byte[]>> references = MutableList.of(); - long created = 0; - while (created < 2*maxMemory) { - byte d[] = new byte[ALLOCATION_CHUNK_SIZE]; - references.add(Maybe.soft(d)); - MemoryUsageTracker.SOFT_REFERENCES.track(d, d.length); - created += d.length; - - long totalMemory = Runtime.getRuntime().totalMemory(); - long freeMemory = Runtime.getRuntime().freeMemory(); - - LOG.info("created "+Strings.makeSizeString(created) + - " ... in use: "+Strings.makeSizeString(totalMemory - freeMemory)+" / " + - Strings.makeSizeString(totalMemory) + - " ... reclaimable: "+Strings.makeSizeString(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed()) + - " ... live refs: "+Strings.makeSizeString(sizeOfActiveReferences(references)) + - " ... maxMem="+maxMemory+"; totalMem="+totalMemory+"; usedMem="+(totalMemory-freeMemory)); - } - - Asserts.succeedsEventually(new Runnable() { - public void run() { - long totalMemory = Runtime.getRuntime().totalMemory(); - long freeMemory = Runtime.getRuntime().freeMemory(); - assertLessThan(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed(), maxMemory); - assertLessThan(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed(), totalMemory); - assertLessThan(MemoryUsageTracker.SOFT_REFERENCES.getBytesUsed(), totalMemory - freeMemory); - }}); - } - - private long sizeOfActiveReferences(List<Maybe<byte[]>> references) { - long size = 0; - for (Maybe<byte[]> ref: references) { - byte[] deref = ref.orNull(); - if (deref!=null) size += deref.length; - } - return size; - } - - private static void assertLessThan(long lhs, long rhs) { - Assert.assertTrue(lhs<rhs, "Expected "+lhs+" < "+rhs); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/javalang/ReflectionsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/javalang/ReflectionsTest.java b/utils/common/src/test/java/brooklyn/util/javalang/ReflectionsTest.java deleted file mode 100644 index 3652b9b..0000000 --- a/utils/common/src/test/java/brooklyn/util/javalang/ReflectionsTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.util.javalang; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -public class ReflectionsTest { - - @Test - public void testFindPublicMethodsOrderedBySuper() throws Exception { - List<Method> methods = Reflections.findPublicMethodsOrderedBySuper(MySubClass.class); - assertContainsInOrder(methods, ImmutableList.of( - MyInterface.class.getMethod("mymethod"), - MySuperClass.class.getMethod("mymethod"), - MySubClass.class.getMethod("mymethod"))); - assertNoDuplicates(methods); - } - - @Test - public void testFindPublicFieldsOrdereBySuper() throws Exception { - List<Field> fields = Reflections.findPublicFieldsOrderedBySuper(MySubClass.class); - assertContainsInOrder(fields, ImmutableList.of( - MyInterface.class.getField("MY_FIELD"), - MySuperClass.class.getField("MY_FIELD"), - MySubClass.class.getField("MY_FIELD"))); - assertNoDuplicates(fields); - } - - public static interface MyInterface { - public static final int MY_FIELD = 0; - public void mymethod(); - } - public static class MySuperClass implements MyInterface { - public static final int MY_FIELD = 0; - - @Override public void mymethod() {} - } - public static class MySubClass extends MySuperClass implements MyInterface { - public static final int MY_FIELD = 0; - @Override public void mymethod() {} - } - - private void assertContainsInOrder(List<?> actual, List<?> subsetExpected) { - int lastIndex = -1; - for (Object e : subsetExpected) { - int index = actual.indexOf(e); - assertTrue(index >= 0 && index > lastIndex, "actual="+actual); - lastIndex = index; - } - } - - private void assertNoDuplicates(List<?> actual) { - assertEquals(actual.size(), Sets.newLinkedHashSet(actual).size(), "actual="+actual); - } - - public static class CI1 { - public final List<Object> constructorArgs; - - public CI1() { - constructorArgs = ImmutableList.of(); - } - public CI1(String x, int y) { - constructorArgs = ImmutableList.<Object>of(x, y); - } - public CI1(String x, int y0, int y1, int ...yy) { - constructorArgs = Lists.newArrayList(); - constructorArgs.addAll(ImmutableList.of(x, y0, y1)); - for (int yi: yy) constructorArgs.add((Integer)yi); - } - public static String m1(String x, int y) { - return x+y; - } - public static String m1(String x, int y0, int y1, int ...yy) { - int Y = y0 + y1;; - for (int yi: yy) Y += yi; - return x+Y; - } - } - - @Test - public void testTypesMatch() throws Exception { - Assert.assertTrue(Reflections.typesMatch(new Object[] { 3 }, new Class[] { Integer.class } )); - Assert.assertTrue(Reflections.typesMatch(new Object[] { 3 }, new Class[] { int.class } ), "auto-boxing failure"); - } - - @Test - public void testInvocation() throws Exception { - Method m = CI1.class.getMethod("m1", String.class, int.class, int.class, int[].class); - Assert.assertEquals(m.invoke(null, "hello", 1, 2, new int[] { 3, 4}), "hello10"); - - Assert.assertEquals(Reflections.invokeMethodWithArgs(CI1.class, "m1", Arrays.<Object>asList("hello", 3)).get(), "hello3"); - Assert.assertEquals(Reflections.invokeMethodWithArgs(CI1.class, "m1", Arrays.<Object>asList("hello", 3, 4, 5)).get(), "hello12"); - } - - @Test - public void testConstruction() throws Exception { - Assert.assertEquals(Reflections.invokeConstructorWithArgs(CI1.class, new Object[] {"hello", 3}).get().constructorArgs, ImmutableList.of("hello", 3)); - Assert.assertEquals(Reflections.invokeConstructorWithArgs(CI1.class, new Object[] {"hello", 3, 4, 5}).get().constructorArgs, ImmutableList.of("hello", 3, 4, 5)); - Assert.assertFalse(Reflections.invokeConstructorWithArgs(CI1.class, new Object[] {"wrong", "args"}).isPresent()); - } - - interface I { }; - interface J extends I { }; - interface K extends I, J { }; - interface L { }; - interface M { }; - class A implements I { }; - class B extends A implements L { }; - class C extends B implements M, K { }; - - @Test - public void testGetAllInterfaces() throws Exception { - Assert.assertEquals(Reflections.getAllInterfaces(A.class), ImmutableList.of(I.class)); - Assert.assertEquals(Reflections.getAllInterfaces(B.class), ImmutableList.of(L.class, I.class)); - Assert.assertEquals(Reflections.getAllInterfaces(C.class), ImmutableList.of(M.class, K.class, I.class, J.class, L.class)); - } - -}
