http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/stream/ThreadLocalStdoutStderrTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/stream/ThreadLocalStdoutStderrTest.java b/utils/common/src/test/java/brooklyn/util/stream/ThreadLocalStdoutStderrTest.java deleted file mode 100644 index 2d49925..0000000 --- a/utils/common/src/test/java/brooklyn/util/stream/ThreadLocalStdoutStderrTest.java +++ /dev/null @@ -1,90 +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.stream; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.os.Os; -import brooklyn.util.stream.ThreadLocalPrintStream.OutputCapturingContext; - -public class ThreadLocalStdoutStderrTest { - - /** simple example showing how a capture to stdout can be set up */ - @Test - public void testStdoutCapture() { - OutputCapturingContext capture = ThreadLocalPrintStream.stdout().captureTee(); - System.out.println("hello"); - String out = capture.end(); - Assert.assertEquals("hello", out.trim()); - - System.out.println("goodbye - not captured, restored normal output"); - Assert.assertEquals("hello", out.trim()); - } - - @Test - public void testStdoutCaptureDetail() { - ThreadLocalPrintStream.stdout(); - System.out.println("1 - not captured, but next goes to capture only"); - OutputCapturingContext capture = ThreadLocalPrintStream.stdout().capture(); - final String TWO = "2 - captured"; - System.out.println(TWO); - Assert.assertEquals(TWO, capture.getOutputSoFar().trim()); - String out = capture.end(); - Assert.assertEquals(TWO, out.trim()); - System.out.println("3 - not captured, restored normal output"); - Assert.assertEquals(TWO, capture.getOutputSoFar().trim()); - } - - @Test - public void testStderrCaptureDetail() { - ThreadLocalPrintStream.stderr(); - System.err.println("1 - not captured, but next goes to capture only"); - OutputCapturingContext capture = ThreadLocalPrintStream.stderr().capture(); - final String TWO = "2 - captured"; - System.err.println(TWO); - Assert.assertEquals(TWO, capture.getOutputSoFar().trim()); - String out = capture.end(); - Assert.assertEquals(TWO, out.trim()); - System.err.println("3 - not captured, restored normal output"); - Assert.assertEquals(TWO, capture.getOutputSoFar().trim()); - } - - @Test - public void testStdoutCaptureTeeDetail() { - ThreadLocalPrintStream.stdout(); - System.out.println("1 - not captured, but next go to capture and stdout"); - OutputCapturingContext capture1 = ThreadLocalPrintStream.stdout().captureTee(); - OutputCapturingContext capture2 = ThreadLocalPrintStream.stdout().captureTee(); - final String TWO = "2 - captured"; - System.out.println(TWO); - Assert.assertEquals(TWO, capture1.getOutputSoFar().trim()); - Assert.assertEquals(TWO, capture2.getOutputSoFar().trim()); - String out2 = capture2.end(); - - final String THREE = "3 - captured by 1"; - System.out.println(THREE); - String out1 = capture1.end(); - - System.out.println("4 - not captured, restored normal output"); - Assert.assertEquals(TWO, out2.trim()); - Assert.assertEquals(TWO+Os.LINE_SEPARATOR+THREE, out1.trim()); - } - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/ByteSizeStringsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/ByteSizeStringsTest.java b/utils/common/src/test/java/brooklyn/util/text/ByteSizeStringsTest.java deleted file mode 100644 index 982acc1..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/ByteSizeStringsTest.java +++ /dev/null @@ -1,163 +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.text; - -import static org.testng.Assert.assertEquals; - -import java.util.Arrays; - -import org.testng.annotations.Test; - -import brooklyn.test.FixedLocaleTest; - -import com.google.common.collect.Iterables; - -/** - * Test the different {@link ByteSizeStrings} formatting options using a list of byte sizes. - */ -@Test -public class ByteSizeStringsTest extends FixedLocaleTest { - - public void testSizeString() { - assertEquals(Strings.makeSizeString(-1), "-1 B"); - assertEquals(Strings.makeSizeString(0), "0 B"); - assertEquals(Strings.makeSizeString(999), "999 B"); - assertEquals(Strings.makeSizeString(1024), "1024 B"); - assertEquals(Strings.makeSizeString(1234), "1234 B"); - assertEquals(Strings.makeSizeString(2345), "2.34 kB"); - assertEquals(Strings.makeSizeString(4096), "4.10 kB"); - assertEquals(Strings.makeSizeString(4567), "4.57 kB"); - assertEquals(Strings.makeSizeString(65535), "65.5 kB"); - assertEquals(Strings.makeSizeString(23456789L), "23.5 MB"); - assertEquals(Strings.makeSizeString(23456789012L), "23.5 GB"); - assertEquals(Strings.makeSizeString(23456789012345L), "23.5 TB"); - assertEquals(Strings.makeSizeString(Long.MAX_VALUE), "9223372 TB"); - } - - public void testJavaSizeString() { - assertEquals(ByteSizeStrings.java().makeSizeString(-1), "-1"); - assertEquals(ByteSizeStrings.java().makeSizeString(0), "0"); - assertEquals(ByteSizeStrings.java().makeSizeString(999), "999"); - assertEquals(ByteSizeStrings.java().makeSizeString(1024), "1024"); - assertEquals(ByteSizeStrings.java().makeSizeString(1234), "1234"); - assertEquals(ByteSizeStrings.java().makeSizeString(2345), "2345"); - assertEquals(ByteSizeStrings.java().makeSizeString(4096), "4096"); - assertEquals(ByteSizeStrings.java().makeSizeString(4567), "4567"); - assertEquals(ByteSizeStrings.java().makeSizeString(6789), "6789"); - assertEquals(ByteSizeStrings.java().makeSizeString(65535), "64k"); - assertEquals(ByteSizeStrings.java().makeSizeString(23456789L), "22m"); - assertEquals(ByteSizeStrings.java().makeSizeString(23456789012L), "22g"); - assertEquals(ByteSizeStrings.java().makeSizeString(23456789012345L), "21000g"); - assertEquals(ByteSizeStrings.java().makeSizeString(Long.MAX_VALUE), "8388608000g"); - } - - public void testISOSizeString() { - assertEquals(ByteSizeStrings.iso().makeSizeString(-1), "-1 B"); - assertEquals(ByteSizeStrings.iso().makeSizeString(0), "0 B"); - assertEquals(ByteSizeStrings.iso().makeSizeString(999), "999 B"); - assertEquals(ByteSizeStrings.iso().makeSizeString(1024), "1024 B"); - assertEquals(ByteSizeStrings.iso().makeSizeString(1234), "1234 B"); - assertEquals(ByteSizeStrings.iso().makeSizeString(2345), "2.29 KiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(4096), "4 KiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(4567), "4.46 KiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(6789), "6.63 KiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(65535), "64.0 KiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(23456789L), "22.4 MiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(23456789012L), "21.8 GiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(23456789012345L), "21.3 TiB"); - assertEquals(ByteSizeStrings.iso().makeSizeString(Long.MAX_VALUE), "8388608 TiB"); - } - - public void testBuilder() { - ByteSizeStrings strings = ByteSizeStrings.builder() - .bytesPerMetricUnit(1024) - .precision(4) - .lowerLimit(5) - .maxLen(4) - .suffixBytes("b") - .suffixKilo("kb") - .suffixMega("Mb") - .suffixGiga("Gb") - .suffixTera("Tb") - .addSpace() - .build(); - - assertEquals(strings.makeSizeString(-1), "-1 b"); - assertEquals(strings.makeSizeString(0), "0 b"); - assertEquals(strings.makeSizeString(999), "999 b"); - assertEquals(strings.makeSizeString(1024), "1024 b"); - assertEquals(strings.makeSizeString(1234), "1234 b"); - assertEquals(strings.makeSizeString(2345), "2345 b"); - assertEquals(strings.makeSizeString(4096), "4096 b"); - assertEquals(strings.makeSizeString(4567), "4567 b"); - assertEquals(strings.makeSizeString(6789), "6.630 kb"); - assertEquals(strings.makeSizeString(65535), "64.00 kb"); - assertEquals(strings.makeSizeString(23456789L), "22.37 Mb"); - assertEquals(strings.makeSizeString(23456789012L), "21.85 Gb"); - assertEquals(strings.makeSizeString(23456789012345L), "21.33 Tb"); - assertEquals(strings.makeSizeString(Long.MAX_VALUE), "8388608 Tb"); - } - - public void testFormatter() { - ByteSizeStrings iso = ByteSizeStrings.iso(); - assertEquals(String.format("%s", iso.formatted(23456789L)), "22.4 MiB"); - assertEquals(String.format("%.6s", iso.formatted(23456789L)), "22.3701 MiB"); - assertEquals(String.format("%#s", iso.formatted(23456789L)), "23.5 MB"); - } - - public void testFunction() { - ByteSizeStrings iso = ByteSizeStrings.iso(); - Iterable<String> bytes = Iterables.transform(Arrays.asList(23456789L, 23456789012L, 23456789012345L), iso); - assertEquals(Iterables.get(bytes, 0), "22.4 MiB"); - assertEquals(Iterables.get(bytes, 1), "21.8 GiB"); - assertEquals(Iterables.get(bytes, 2), "21.3 TiB"); - } - - public void testParse() { - assertEquals(ByteSizeStrings.parse("1", "k"), 1024); - - // basics - assertEquals(ByteSizeStrings.parse("1b"), 1); - assertEquals(ByteSizeStrings.parse("1k"), 1024); - assertEquals(ByteSizeStrings.parse("1m"), 1024*1024); - assertEquals(ByteSizeStrings.parse("1g"), 1024*1024*1024); - assertEquals(ByteSizeStrings.parse("1t"), 1024L*1024*1024*1024); - - // iso - assertEquals(ByteSizeStrings.parse("64.0 KiB"), 65536); - // metric - assertEquals(ByteSizeStrings.parse("64.0 KB"), 64000); - // java - assertEquals(ByteSizeStrings.parse("64.0k"), 65536); - - // spaces and things - assertEquals(ByteSizeStrings.parse("64k"), 65536); - assertEquals(ByteSizeStrings.parse("64 k"), 65536); - - // smaller than zero - assertEquals(ByteSizeStrings.parse("0.5t"), 512L*1024*1024*1024); - - // applying default unit - assertEquals(ByteSizeStrings.parse("1", "k"), 1024); - // not applying default unit - assertEquals(ByteSizeStrings.parse("1k", "m"), 1024); - // forcing use of metric - assertEquals(ByteSizeStrings.parse("1k", "m", ByteSizeStrings.metric()), 1000); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/ComparableVersionTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/ComparableVersionTest.java b/utils/common/src/test/java/brooklyn/util/text/ComparableVersionTest.java deleted file mode 100644 index fa710b1..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/ComparableVersionTest.java +++ /dev/null @@ -1,55 +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.text; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.text.NaturalOrderComparator; - -public class ComparableVersionTest { - - public static final NaturalOrderComparator noc = new NaturalOrderComparator(); - - @Test - public void testBasicOnes() { - Assert.assertEquals(0, noc.compare("a", "a")); - Assert.assertTrue(noc.compare("a", "b") < 0); - Assert.assertTrue(noc.compare("b", "a") > 0); - - Assert.assertTrue(noc.compare("9", "10") < 0); - Assert.assertTrue(noc.compare("10", "9") > 0); - - Assert.assertTrue(noc.compare("b10", "a9") > 0); - Assert.assertTrue(noc.compare("b9", "a10") > 0); - - Assert.assertTrue(noc.compare(" 9", "10") < 0); - Assert.assertTrue(noc.compare("10", " 9") > 0); - } - - @Test - public void testVersionNumbers() { - Assert.assertEquals(0, noc.compare("10.5.8", "10.5.8")); - Assert.assertTrue(noc.compare("10.5", "9.9") > 0); - Assert.assertTrue(noc.compare("10.5.1", "10.5") > 0); - Assert.assertTrue(noc.compare("10.5.1", "10.6") < 0); - Assert.assertTrue(noc.compare("10.5.1-1", "10.5.1-0") > 0); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/IdentifiersTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/IdentifiersTest.java b/utils/common/src/test/java/brooklyn/util/text/IdentifiersTest.java deleted file mode 100644 index 9a4148c..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/IdentifiersTest.java +++ /dev/null @@ -1,87 +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.text; - -import java.util.HashSet; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class IdentifiersTest { - - private static final Logger log = LoggerFactory.getLogger(IdentifiersTest.class); - - @Test - public void testRandomId() { - String id1 = Identifiers.makeRandomId(4); - Assert.assertEquals(id1.length(), 4); - String id2 = Identifiers.makeRandomId(4); - Assert.assertNotEquals(id1, id2); - } - - //The test is disabled since it takes a while to finish - //and there is still the possibility that it could fail. - @Test(enabled = false) - public void testRandomIdRandomness() { - int collisionTestCnt = 100000; - int sampleSize = 2000; - - int duplicateTests = 0; - for(int testIdx = 0; testIdx < collisionTestCnt; testIdx++) { - Set<String> randomIds = new HashSet<String>(); - for (int sampleCnt = 0; sampleCnt < sampleSize; sampleCnt++) { - if(!randomIds.add(Identifiers.makeRandomId(4))) { - duplicateTests++; - break; - } - } - } - double probability = ((double)duplicateTests)*100/collisionTestCnt; - log.info("testRandomIdRandomness probability = " + probability); - Assert.assertEquals(probability, 15, 0.5d, "Expected probability of collision with id of length 4 and 2000 samples is 15%."); - } - - @Test - public void testFromHash() { - String id1 = Identifiers.makeIdFromHash("Hello".hashCode()); - Assert.assertTrue(!Strings.isBlank(id1)); - - String id2 = Identifiers.makeIdFromHash("hello".hashCode()); - String id3 = Identifiers.makeIdFromHash("hello".hashCode()); - Assert.assertEquals(id2, id3); - Assert.assertNotEquals(id1, id2); - - Assert.assertEquals(Identifiers.makeIdFromHash(0), "A"); - - String idLong = Identifiers.makeIdFromHash(Long.MAX_VALUE); - log.info("ID's made from hash, of 'hello' is "+id1+" and of Long.MAX_VALUE is "+idLong); - Assert.assertTrue(idLong.length() > id1.length()); - } - - @Test - public void testFromNegativeHash() { - String id1 = Identifiers.makeIdFromHash(-1); - Assert.assertTrue(!Strings.isBlank(id1)); - log.info("ID's made from hash, of -1 is "+id1+" and of Long.MIN_VALUE is "+Identifiers.makeIdFromHash(Long.MIN_VALUE)); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/KeyValueParserTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/KeyValueParserTest.java b/utils/common/src/test/java/brooklyn/util/text/KeyValueParserTest.java deleted file mode 100644 index 9806d77..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/KeyValueParserTest.java +++ /dev/null @@ -1,148 +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.text; - -import static org.testng.Assert.assertEquals; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; - -/** - * The ConfigParserTest - * - * @author aled - **/ -public class KeyValueParserTest { - - // Gives an example of how to do this with guava. But note that does not - // give the same behaviour for quoted values. - @Test - public void testGuavaEquivalent() { - assertOrderedMapsEqual(Splitter.on(",").withKeyValueSeparator("=").split("a=x,b=y"), ImmutableMap.of("a", "x", "b", "y")); - } - - @Test - public void testTrimsWhiteSpaceOutsideOfQuotes() throws Exception { - assertOrderedMapsEqual(KeyValueParser.parseMap("a=x"), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a=x "), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap(" a=x"), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a =x"), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a= x"), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a = x"), ImmutableMap.of("a", "x")); - - assertOrderedMapsEqual(KeyValueParser.parseMap("a=\"x\""), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a=\"x\" "), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap(" a=\"x\""), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a =\"x\""), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a= \"x\""), ImmutableMap.of("a", "x")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a = \"x\""), ImmutableMap.of("a", "x")); - - assertOrderedMapsEqual(KeyValueParser.parseMap("a=x,b=y"), ImmutableMap.of("a", "x", "b", "y")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a=x, b=y"), ImmutableMap.of("a", "x", "b", "y")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a=x,\tb=y"), ImmutableMap.of("a", "x", "b", "y")); - assertOrderedMapsEqual(KeyValueParser.parseMap("a=x ,b=y"), ImmutableMap.of("a", "x", "b", "y")); - } - - @Test - public void testPreservesWhiteSpaceInsideQuotes() throws Exception { - assertOrderedMapsEqual(KeyValueParser.parseMap("a=\" x \""), ImmutableMap.of("a", " x ")); - } - - @Test - public void testConfigParseMap() throws Exception { - Map<String, String> result = KeyValueParser.parseMap("a=x, b=\"x x\", c, \"d d\""); - Map<String, String> expected = Maps.newLinkedHashMap(); - expected.put("a", "x"); - expected.put("b", "x x"); - expected.put("c", null); - expected.put("d d", null); - - assertOrderedMapsEqual(result, expected); - assertOrderedMapsEqual(KeyValueParser.parseMap(KeyValueParser.toLine(expected)), expected); - } - - @Test - public void testConfigParseMapWithBigWhiteSpace() throws Exception { - Map<String, String> result = KeyValueParser.parseMap(" a=x, b=y "); - Map<String, String> expected = Maps.newLinkedHashMap(); - expected.put("a", "x"); - expected.put("b", "y"); - - assertOrderedMapsEqual(result, expected); - assertOrderedMapsEqual(KeyValueParser.parseMap(KeyValueParser.toLine(expected)), expected); - } - - @Test - public void testConfigParseMapWithEmptyValue() throws Exception { - Map<String, String> result = KeyValueParser.parseMap("a=\"\""); - Map<String, String> expected = Maps.newLinkedHashMap(); - expected.put("a", ""); - - assertOrderedMapsEqual(result, expected); - assertOrderedMapsEqual(KeyValueParser.parseMap(KeyValueParser.toLine(expected)), expected); - } - - @Test - public void testConfigParseMapWithNoValue() throws Exception { - Map<String, String> result = KeyValueParser.parseMap("a=, b"); - Map<String, String> expected = Maps.newLinkedHashMap(); - expected.put("a", ""); - expected.put("b", null); - - assertOrderedMapsEqual(result, expected); - assertOrderedMapsEqual(KeyValueParser.parseMap(KeyValueParser.toLine(expected)), expected); - } - - @Test - public void testConfigParseList() throws Exception { - assertParsedList(Arrays.asList("a", "b b")); - assertParsedList(Arrays.asList("\"a\" \"a\"")); - assertParsedList(Arrays.<String>asList()); - - StringBuilder ascii = new StringBuilder(); - for (int i = 0; i <= 127; i++) { - ascii.append((char)i); - } - assertParsedList(Arrays.asList(ascii.toString())); - } - - @Test - public void testConfigParseListWithEmptyValue() throws Exception { - assertParsedList(Arrays.asList("")); - assertEquals(KeyValueParser.parseList("\"\""), Arrays.asList("")); - } - - private void assertParsedList(List<String> expected) { - assertEquals(KeyValueParser.parseList(KeyValueParser.toLine(expected)), expected); - } - - private void assertOrderedMapsEqual(Map<?,?> map1, Map<?,?> map2) { - Assert.assertEquals(map1, map2); - Assert.assertEquals(ImmutableList.copyOf(map1.keySet()), ImmutableList.copyOf(map2.keySet())); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/NaturalOrderComparatorTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/NaturalOrderComparatorTest.java b/utils/common/src/test/java/brooklyn/util/text/NaturalOrderComparatorTest.java deleted file mode 100644 index 6c109cf..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/NaturalOrderComparatorTest.java +++ /dev/null @@ -1,81 +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.text; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.text.NaturalOrderComparator; - -public class NaturalOrderComparatorTest { - - public static final NaturalOrderComparator noc = new NaturalOrderComparator(); - - ComparableVersion v = new ComparableVersion("10.5.8"); - ComparableVersion v_rc2 = new ComparableVersion("10.5.8-rc2"); - - @Test - public void testBasicOnes() { - Assert.assertTrue(v.isGreaterThanAndNotEqualTo("10.5")); - Assert.assertTrue(v.isGreaterThanOrEqualTo("10.5.8")); - Assert.assertFalse(v.isGreaterThanAndNotEqualTo("10.5.8")); - - Assert.assertTrue(v.isLessThanAndNotEqualTo("10.6")); - Assert.assertTrue(v.isLessThanOrEqualTo("10.5.8")); - Assert.assertFalse(v.isLessThanAndNotEqualTo("10.5.8")); - - Assert.assertTrue(v.isLessThanAndNotEqualTo("10.5.8.1")); - - Assert.assertTrue(v_rc2.isLessThanAndNotEqualTo("10.5.8-rc3")) ; - Assert.assertTrue(v_rc2.isGreaterThanAndNotEqualTo("10.5.8-rc1")); - - Assert.assertTrue(v_rc2.isGreaterThanAndNotEqualTo("10.5.8-beta1")==v_rc2.isGreaterThanAndNotEqualTo("10.5.8-beta3")); - - Assert.assertTrue(v.isInRange("[10.5,10.6)")); - Assert.assertFalse(v.isInRange("[10.5,10.5.8)")); - Assert.assertTrue(v.isInRange("[10.5,)")); - Assert.assertTrue(v.isInRange("[9,)")); - Assert.assertFalse(v.isInRange("(10.5.8,)")); - Assert.assertFalse(v.isInRange("[10.6,)")); - Assert.assertTrue(v.isInRange("[,11)")); - Assert.assertTrue(v.isInRange("[,]")); - } - - @Test(expectedExceptions={IllegalArgumentException.class}) - public void testError1() { v.isInRange("10.5"); } - @Test(expectedExceptions={IllegalArgumentException.class}) - public void testError2() { v.isInRange("[10.5"); } - @Test(expectedExceptions={IllegalArgumentException.class}) - public void testError3() { v.isInRange("[10.5]"); } - - @Test(groups="WIP", enabled=false) - public void testUnderscoreDoesNotChangeMeaningOfNumberInNoc() { - // why?? - Assert.assertTrue(noc.compare("0.0.0_SNAPSHOT", "0.0.1-SNAPSHOT-20141111114709760") < 0); - - Assert.assertTrue(v.isGreaterThanAndNotEqualTo(v_rc2.version)); - Assert.assertTrue(v_rc2.isLessThanAndNotEqualTo(v.version)); - } - - @Test(groups="WIP", enabled=false) - public void testUnderscoreDoesNotChangeMeaningOfNumberInOurWorld() { - Assert.assertTrue(new ComparableVersion("0.0.0_SNAPSHOT").isLessThanAndNotEqualTo("0.0.1-SNAPSHOT-20141111114709760")); - } - -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/QuotedStringTokenizerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/QuotedStringTokenizerTest.java b/utils/common/src/test/java/brooklyn/util/text/QuotedStringTokenizerTest.java deleted file mode 100644 index a70e546..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/QuotedStringTokenizerTest.java +++ /dev/null @@ -1,110 +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.text; - -import static org.testng.Assert.assertEquals; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class QuotedStringTokenizerTest { - - // have to initialise to use the methods (instance as it can take custom tokens) - private QuotedStringTokenizer defaultTokenizer= new QuotedStringTokenizer("", true); - - @Test - public void testQuoting() throws Exception { - assertQuoteUnquoteFor("a=b"); - assertQuoteUnquoteFor("a=\"things\",b=c"); - assertQuoteUnquoteFor("thing=\"\""); - assertQuoteUnquoteFor("\"thing\"=\"\""); - assertQuoteUnquoteFor(""); - assertQuoteUnquoteFor("\""); - assertQuoteUnquoteFor("\"\""); - - assertUnquoteFor("", "''"); - assertUnquoteFor("thing=", "\"thing\"=\"\""); - assertUnquoteFor("a=", "a=\"\""); - } - - @Test - public void testTokenizing() throws Exception { - testResultingTokens("foo,bar,baz", "\"", false, ",", false, "foo", "bar", "baz"); - testResultingTokens("\"foo,bar\",baz", "\"", false, ",", false, "foo,bar", "baz"); - testResultingTokens("\"foo,,bar\",baz", "\"", false, ",", false, "foo,,bar", "baz"); - - // Have seen "the operator ""foo"" is not recognised" entries in BAML CSV files. - testResultingTokens("foo \"\"bar\"\" baz", "\"", false, ",", false, "foo bar baz"); - testResultingTokens("\"foo \"\"bar\"\" baz\"", "\"", false, ",", false, "foo bar baz"); - - // FIXME: would like to return empty tokens when we encounter adjacent delimiters, but need - // to work around brain-dead java.util.StringTokenizer to do this. - // testResultingTokens("foo,,baz", "\"", false, ",", false, "foo", "", "baz"); - } - - @Test - public void testTokenizingBuilder() throws Exception { - Assert.assertEquals(Arrays.asList("foo", "bar"), QuotedStringTokenizer.builder().buildList("foo bar")); - Assert.assertEquals(Arrays.asList("foo,bar"), QuotedStringTokenizer.builder().buildList("foo,bar")); - Assert.assertEquals(Arrays.asList("foo", "bar"), QuotedStringTokenizer.builder().delimiterChars(",").buildList("foo,bar")); - Assert.assertEquals(Arrays.asList("foo", " bar"), QuotedStringTokenizer.builder().delimiterChars(",").buildList("foo, bar")); - Assert.assertEquals(Arrays.asList("foo", "bar"), QuotedStringTokenizer.builder().addDelimiterChars(",").buildList("foo, bar")); - } - - @Test - public void testCommaInQuotes() throws Exception { - List<String> l = QuotedStringTokenizer.builder().addDelimiterChars(",").buildList("location1,byon:(hosts=\"loc2,loc3\"),location4"); - Assert.assertEquals(Arrays.asList("location1", "byon:(hosts=\"loc2,loc3\")", "location4"), l); - } - - /** not implemented yet */ - @Test(enabled=false) - public void testCommaInParentheses() throws Exception { - List<String> l = QuotedStringTokenizer.builder().addDelimiterChars(",").buildList("location1, byon:(hosts=\"loc2,loc3\",user=foo),location4"); - Assert.assertEquals(Arrays.asList("location1", "byon:(hosts=\"loc2,loc3\",user=foo)", "location4"), l); - } - - private void testResultingTokens(String input, String quoteChars, boolean includeQuotes, String delimiterChars, boolean includeDelimiters, String... expectedTokens) { - QuotedStringTokenizer tok = new QuotedStringTokenizer(input, quoteChars, includeQuotes, delimiterChars, includeDelimiters); - testResultingTokens(input, tok, expectedTokens); - } - - private void testResultingTokens(String input, QuotedStringTokenizer tok, String... expectedTokens) { - List<String> actual = new LinkedList<String>(); - while (tok.hasMoreTokens()) actual.add(tok.nextToken()); - assertEquals(actual, Arrays.asList(expectedTokens), "Wrong tokens returned."); - } - - private void assertQuoteUnquoteFor(String unquoted) { - String quoted = defaultTokenizer.quoteToken(unquoted); - String reunquoted = defaultTokenizer.unquoteToken(quoted); - //System.out.println("orig="+unquoted+" quoted="+quoted+" reunquoted="+reunquoted); - assertEquals(reunquoted, unquoted); - } - - private void assertUnquoteFor(String expected, String quoted) { - String unquoted = defaultTokenizer.unquoteToken(quoted); - //System.out.println("expected="+expected+" quoted="+quoted+" unquoted="+unquoted); - assertEquals(unquoted, expected); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/StringEscapesTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/StringEscapesTest.java b/utils/common/src/test/java/brooklyn/util/text/StringEscapesTest.java deleted file mode 100644 index 3b326b6..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/StringEscapesTest.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.text; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableList; -import brooklyn.util.text.StringEscapes.BashStringEscapes; -import brooklyn.util.text.StringEscapes.JavaStringEscapes; - -public class StringEscapesTest { - - @Test - public void testEscapeSql() { - Assert.assertEquals(StringEscapes.escapeSql("I've never been to Brooklyn"), "I''ve never been to Brooklyn"); - } - - - @Test - public void testBashEscaping() { - Assert.assertEquals( - BashStringEscapes.doubleQuoteLiteralsForBash("-Dname=Bob Johnson", "-Dnet.worth=$100"), - "\"-Dname=Bob Johnson\" \"-Dnet.worth=\\$100\""); - } - - @Test - public void testBashEscapable() { - Assert.assertTrue(BashStringEscapes.isValidForDoubleQuotingInBash("Bob Johnson")); - Assert.assertFalse(BashStringEscapes.isValidForDoubleQuotingInBash("\"")); - Assert.assertTrue(BashStringEscapes.isValidForDoubleQuotingInBash("\\\"")); - } - - /** Bash handles ampersand in double quoted strings without escaping. */ - @Test - public void testBashEscapableAmpersand() { - Assert.assertTrue(BashStringEscapes.isValidForDoubleQuotingInBash("&")); - Assert.assertTrue(BashStringEscapes.isValidForDoubleQuotingInBash("Marks & Spencer")); - } - - @Test - public void testJavaUnwrap() { - Assert.assertEquals(JavaStringEscapes.unwrapJavaString("\"Hello World\""), "Hello World"); - Assert.assertEquals(JavaStringEscapes.unwrapJavaString("\"Hello \\\"Bob\\\"\""), "Hello \"Bob\""); - try { - JavaStringEscapes.unwrapJavaString("Hello World"); - Assert.fail("Should have thrown"); - } catch (Exception e) { /* expected */ } - try { - // missing final quote - JavaStringEscapes.unwrapJavaString("\"Hello \\\"Bob\\\""); - Assert.fail("Should have thrown"); - } catch (Exception e) { /* expected */ } - - Assert.assertEquals(JavaStringEscapes.unwrapJavaStringIfWrapped("\"Hello World\""), "Hello World"); - Assert.assertEquals(JavaStringEscapes.unwrapJavaStringIfWrapped("\"Hello \\\"Bob\\\"\""), "Hello \"Bob\""); - Assert.assertEquals(JavaStringEscapes.unwrapJavaStringIfWrapped("Hello World"), "Hello World"); - try { - // missing final quote - JavaStringEscapes.unwrapJavaStringIfWrapped("\"Hello \\\"Bob\\\""); - Assert.fail("Should have thrown"); - } catch (Exception e) { /* expected */ } - } - - @Test - public void testJavaEscape() { - Assert.assertEquals(JavaStringEscapes.wrapJavaString("Hello \"World\""), "\"Hello \\\"World\\\"\""); - } - - @Test - public void testJavaLists() { - Assert.assertEquals(MutableList.of("hello", "world"), - JavaStringEscapes.unwrapQuotedJavaStringList("\"hello\", \"world\"", ",")); - try { - JavaStringEscapes.unwrapQuotedJavaStringList("\"hello\", world", ","); - Assert.fail("Should have thrown"); - } catch (Exception e) { /* expected */ } - - Assert.assertEquals(MutableList.of("hello", "world"), - JavaStringEscapes.unwrapJsonishListIfPossible("\"hello\", \"world\"")); - Assert.assertEquals(MutableList.of("hello"), - JavaStringEscapes.unwrapJsonishListIfPossible("hello")); - Assert.assertEquals(MutableList.of("hello", "world"), - JavaStringEscapes.unwrapJsonishListIfPossible("hello, world")); - Assert.assertEquals(MutableList.of("hello", "world"), - JavaStringEscapes.unwrapJsonishListIfPossible("\"hello\", world")); - Assert.assertEquals(MutableList.of("hello", "world"), - JavaStringEscapes.unwrapJsonishListIfPossible("[ \"hello\", world ]")); - // if can't parse e.g. because contains double quote, then returns original string as single element list - Assert.assertEquals(MutableList.of("hello\", \"world\""), - JavaStringEscapes.unwrapJsonishListIfPossible("hello\", \"world\"")); - Assert.assertEquals(MutableList.of(), - JavaStringEscapes.unwrapJsonishListIfPossible(" ")); - Assert.assertEquals(MutableList.of(""), - JavaStringEscapes.unwrapJsonishListIfPossible("\"\"")); - Assert.assertEquals(MutableList.of("x"), - JavaStringEscapes.unwrapJsonishListIfPossible(",,x,")); - Assert.assertEquals(MutableList.of("","x",""), - JavaStringEscapes.unwrapJsonishListIfPossible("\"\",,x,\"\"")); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/StringFunctionsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/StringFunctionsTest.java b/utils/common/src/test/java/brooklyn/util/text/StringFunctionsTest.java deleted file mode 100644 index 87b4191..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/StringFunctionsTest.java +++ /dev/null @@ -1,56 +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.text; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class StringFunctionsTest { - - @Test - public static void testPrepend() { - Assert.assertEquals(StringFunctions.prepend("Hello ").apply("World"), "Hello World"); - } - - @Test - public static void testFormatter() { - Assert.assertEquals(StringFunctions.formatter("Hello %s").apply("World"), "Hello World"); - } - - @Test - public static void testFormatterForArray() { - Assert.assertEquals(StringFunctions.formatterForArray("Hello %s").apply(new Object[] { "World" }), "Hello World"); - } - - @Test - public static void testSurround() { - Assert.assertEquals(StringFunctions.surround("goodbye ", " world").apply("cruel"), "goodbye cruel world"); - } - - @Test - public static void testLowerCase() { - Assert.assertEquals(StringFunctions.toLowerCase().apply("Hello World"), "hello world"); - } - - @Test - public static void testUpperCase() { - Assert.assertEquals(StringFunctions.toUpperCase().apply("Hello World"), "HELLO WORLD"); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/StringPredicatesTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/StringPredicatesTest.java b/utils/common/src/test/java/brooklyn/util/text/StringPredicatesTest.java deleted file mode 100644 index a27900c..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/StringPredicatesTest.java +++ /dev/null @@ -1,74 +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.text; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; - -public class StringPredicatesTest { - - @Test - public static void testIsBlank() { - Assert.assertTrue(StringPredicates.isBlank().apply("")); - Assert.assertTrue(StringPredicates.isBlank().apply(" \n\t")); - Assert.assertTrue(StringPredicates.isBlank().apply(null)); - Assert.assertFalse(StringPredicates.isBlank().apply(" hi ")); - } - - @Test - public static void testContainsLiteral() { - Assert.assertTrue(StringPredicates.containsLiteral("xx").apply("texxxt tessst")); - Assert.assertFalse(StringPredicates.containsLiteral("xx").apply("text test")); - Assert.assertFalse(StringPredicates.containsLiteral("xx").apply("texXxt tessst")); - - Assert.assertTrue(StringPredicates.containsLiteralIgnoreCase("xx").apply("texxxt tessst")); - Assert.assertFalse(StringPredicates.containsLiteralIgnoreCase("xx").apply("text test")); - Assert.assertTrue(StringPredicates.containsLiteralIgnoreCase("xx").apply("texXxt tessst")); - - Assert.assertTrue(StringPredicates.containsAllLiterals("xx", "ss").apply("texxxt tessst")); - Assert.assertFalse(StringPredicates.containsAllLiterals("xx", "tt").apply("texxxt tessst")); - } - - @Test - public static void testEqualToAny() { - Assert.assertTrue(StringPredicates.equalToAny(ImmutableSet.of("1", "2")).apply("2")); - Assert.assertFalse(StringPredicates.equalToAny(ImmutableSet.of("1", "2")).apply("3")); - } - - @Test - public static void testStartsWith() { - Assert.assertTrue(StringPredicates.startsWith("t").apply("test")); - Assert.assertFalse(StringPredicates.startsWith("v").apply("test")); - - Assert.assertTrue(StringPredicates.isStringStartingWith("t").apply("test")); - Assert.assertFalse(StringPredicates.isStringStartingWith("t").apply(true)); - } - - @Test - public static void testMatches() { - Assert.assertTrue(StringPredicates.matchesRegex("t.*").apply("test")); - Assert.assertFalse(StringPredicates.matchesRegex("v.*").apply("test")); - - Assert.assertTrue(StringPredicates.matchesGlob("t*").apply("test")); - Assert.assertFalse(StringPredicates.matchesGlob("v*").apply("test")); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/StringShortenerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/StringShortenerTest.java b/utils/common/src/test/java/brooklyn/util/text/StringShortenerTest.java deleted file mode 100644 index 92a7847..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/StringShortenerTest.java +++ /dev/null @@ -1,64 +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.text; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class StringShortenerTest { - - @Test - public void testSimpleShortener() { - StringShortener ss = new StringShortener() - .separator("-") - .append("1", "hello") - .append("2", "new") - .append("3", "world") - .canRemove("2") - .canTruncate("1", 2) - .canTruncate("3", 2); - - Assert.assertEquals(ss.getStringOfMaxLength(12), "hello-world"); - Assert.assertEquals(ss.getStringOfMaxLength(10), "hell-world"); - Assert.assertEquals(ss.getStringOfMaxLength(6), "he-wor"); - Assert.assertEquals(ss.getStringOfMaxLength(5), "he-wo"); - Assert.assertEquals(ss.getStringOfMaxLength(4), "he-w"); - Assert.assertEquals(ss.getStringOfMaxLength(0), ""); - } - - @Test - public void testEdgeCases() { - StringShortener ss = new StringShortener(); - ss.separator(null); - Assert.assertEquals(ss.getStringOfMaxLength(4), ""); - ss.append("1", "hello"); - Assert.assertEquals(ss.getStringOfMaxLength(8), "hello"); - Assert.assertEquals(ss.getStringOfMaxLength(4), "hell"); - ss.append("2", "world"); - ss.append("3", null); - Assert.assertEquals(ss.getStringOfMaxLength(15), "helloworld"); - Assert.assertEquals(ss.getStringOfMaxLength(8), "hellowor"); - ss.canTruncate("1", 2); - Assert.assertEquals(ss.getStringOfMaxLength(8), "helworld"); - Assert.assertEquals(ss.getStringOfMaxLength(5), "hewor"); - Assert.assertEquals(ss.getStringOfMaxLength(2), "he"); - Assert.assertEquals(ss.getStringOfMaxLength(0), ""); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/StringsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/StringsTest.java b/utils/common/src/test/java/brooklyn/util/text/StringsTest.java deleted file mode 100644 index 5759c6f..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/StringsTest.java +++ /dev/null @@ -1,364 +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.text; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.util.Arrays; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.test.FixedLocaleTest; -import brooklyn.util.collections.MutableMap; - -@Test -public class StringsTest extends FixedLocaleTest { - - public void isBlankOrEmpty() { - assertTrue(Strings.isEmpty(null)); - assertTrue(Strings.isEmpty("")); - assertFalse(Strings.isEmpty(" \t ")); - assertFalse(Strings.isEmpty("abc")); - assertFalse(Strings.isEmpty(" abc ")); - - assertFalse(Strings.isNonEmpty(null)); - assertFalse(Strings.isNonEmpty("")); - assertTrue(Strings.isNonEmpty(" \t ")); - assertTrue(Strings.isNonEmpty("abc")); - assertTrue(Strings.isNonEmpty(" abc ")); - - assertTrue(Strings.isBlank(null)); - assertTrue(Strings.isBlank("")); - assertTrue(Strings.isBlank(" \t ")); - assertFalse(Strings.isBlank("abc")); - assertFalse(Strings.isBlank(" abc ")); - - assertFalse(Strings.isNonBlank(null)); - assertFalse(Strings.isNonBlank("")); - assertFalse(Strings.isNonBlank(" \t ")); - assertTrue(Strings.isNonBlank("abc")); - assertTrue(Strings.isNonBlank(" abc ")); - } - - public void testMakeValidFilename() { - assertEquals("abcdef", Strings.makeValidFilename("abcdef")); - assertEquals("abc_def", Strings.makeValidFilename("abc$$$def")); - assertEquals("abc_def", Strings.makeValidFilename("$$$abc$$$def$$$")); - assertEquals("a_b_c", Strings.makeValidFilename("a b c")); - assertEquals("a.b.c", Strings.makeValidFilename("a.b.c")); - } - @Test(expectedExceptions = { NullPointerException.class }) - public void testMakeValidFilenameNull() { - Strings.makeValidFilename(null); - } - @Test(expectedExceptions = { IllegalArgumentException.class }) - public void testMakeValidFilenameEmpty() { - Strings.makeValidFilename(""); - } - @Test(expectedExceptions = { IllegalArgumentException.class }) - public void testMakeValidFilenameBlank() { - Strings.makeValidFilename(" \t "); - } - - public void makeValidJavaName() { - assertEquals(Strings.makeValidJavaName(null), "__null"); - assertEquals(Strings.makeValidJavaName(""), "__empty"); - assertEquals(Strings.makeValidJavaName("abcdef"), "abcdef"); - assertEquals(Strings.makeValidJavaName("a'b'c'd'e'f"), "abcdef"); - assertEquals(Strings.makeValidJavaName("12345"), "_12345"); - } - - public void makeValidUniqueJavaName() { - assertEquals(Strings.makeValidUniqueJavaName(null), "__null"); - assertEquals(Strings.makeValidUniqueJavaName(""), "__empty"); - assertEquals(Strings.makeValidUniqueJavaName("abcdef"), "abcdef"); - assertEquals(Strings.makeValidUniqueJavaName("12345"), "_12345"); - } - - public void testRemoveFromEnd() { - assertEquals(Strings.removeFromEnd("", "bar"), ""); - assertEquals(Strings.removeFromEnd(null, "bar"), null); - - assertEquals(Strings.removeFromEnd("foobar", "bar"), "foo"); - assertEquals(Strings.removeFromEnd("foo", "bar"), "foo"); - assertEquals(Strings.removeFromEnd("foobar", "foo", "bar"), "foo"); - // test they are applied in order - assertEquals(Strings.removeFromEnd("foobar", "ar", "bar", "b"), "foob"); - } - - public void testRemoveAllFromEnd() { - assertEquals(Strings.removeAllFromEnd("", "bar"), ""); - assertEquals(Strings.removeAllFromEnd(null, "bar"), null); - assertEquals(Strings.removeAllFromEnd("foo", ""), "foo"); - - assertEquals(Strings.removeAllFromEnd("foobar", "foo", "bar"), ""); - assertEquals(Strings.removeAllFromEnd("foobar", "ar", "car", "b", "o"), "f"); - // test they are applied in order - assertEquals(Strings.removeAllFromEnd("foobar", "ar", "car", "b", "ob"), "foo"); - assertEquals(Strings.removeAllFromEnd("foobar", "zz", "x"), "foobar"); - assertEquals(Strings.removeAllFromEnd("foobarbaz", "bar", "baz"), "foo"); - assertEquals(Strings.removeAllFromEnd("foobarbaz", "baz", "", "foo", "bar", "baz"), ""); - } - - public void testRemoveFromStart() { - assertEquals(Strings.removeFromStart("", "foo"), ""); - assertEquals(Strings.removeFromStart(null, "foo"), null); - - assertEquals(Strings.removeFromStart("foobar", "foo"), "bar"); - assertEquals(Strings.removeFromStart("foo", "bar"), "foo"); - assertEquals(Strings.removeFromStart("foobar", "foo", "bar"), "bar"); - assertEquals(Strings.removeFromStart("foobar", "ob", "fo", "foo", "o"), "obar"); - } - - public void testRemoveAllFromStart() { - assertEquals(Strings.removeAllFromStart("", "foo"), ""); - assertEquals(Strings.removeAllFromStart(null, "foo"), null); - assertEquals(Strings.removeAllFromStart("foo", ""), "foo"); - - assertEquals(Strings.removeAllFromStart("foobar", "foo"), "bar"); - assertEquals(Strings.removeAllFromStart("foo", "bar"), "foo"); - assertEquals(Strings.removeAllFromStart("foobar", "foo", "bar"), ""); - - assertEquals(Strings.removeAllFromStart("foobar", "fo", "ob", "o"), "ar"); - assertEquals(Strings.removeAllFromStart("foobar", "ob", "fo", "o"), "ar"); - // test they are applied in order, "ob" doesn't match because "o" eats the o - assertEquals(Strings.removeAllFromStart("foobar", "o", "fo", "ob"), "bar"); - assertEquals(Strings.removeAllFromStart("foobarbaz", "bar", "foo"), "baz"); - assertEquals(Strings.removeAllFromStart("foobarbaz", "baz", "bar", "foo"), ""); - } - - public void testRemoveFromStart2() { - assertEquals(Strings.removeFromStart("xyz", "x"), "yz"); - assertEquals(Strings.removeFromStart("xyz", "."), "xyz"); - assertEquals(Strings.removeFromStart("http://foo.com", "http://"), "foo.com"); - } - - public void testRemoveFromEnd2() { - assertEquals(Strings.removeFromEnd("xyz", "z"), "xy"); - assertEquals(Strings.removeFromEnd("xyz", "."), "xyz"); - assertEquals(Strings.removeFromEnd("http://foo.com/", "/"), "http://foo.com"); - } - - public void testReplaceAll() { - assertEquals(Strings.replaceAll("xyz", "x", ""), "yz"); - assertEquals(Strings.replaceAll("xyz", ".", ""), "xyz"); - assertEquals(Strings.replaceAll("http://foo.com/", "/", ""), "http:foo.com"); - assertEquals(Strings.replaceAll("http://foo.com/", "http:", "https:"), "https://foo.com/"); - } - - public void testReplaceAllNonRegex() { - assertEquals(Strings.replaceAllNonRegex("xyz", "x", ""), "yz"); - assertEquals(Strings.replaceAllNonRegex("xyz", ".", ""), "xyz"); - assertEquals(Strings.replaceAllNonRegex("http://foo.com/", "/", ""), "http:foo.com"); - assertEquals(Strings.replaceAllNonRegex("http://foo.com/", "http:", "https:"), "https://foo.com/"); - } - - public void testReplaceAllRegex() { - assertEquals(Strings.replaceAllRegex("xyz", "x", ""), "yz"); - assertEquals(Strings.replaceAllRegex("xyz", ".", ""), ""); - assertEquals(Strings.replaceAllRegex("http://foo.com/", "/", ""), "http:foo.com"); - assertEquals(Strings.replaceAllRegex("http://foo.com/", "http:", "https:"), "https://foo.com/"); - } - - public void testReplaceMap() { - assertEquals(Strings.replaceAll("xyz", MutableMap.builder().put("x","a").put("y","").build()), "az"); - } - - public void testContainsLiteral() { - assertTrue(Strings.containsLiteral("hello", "ell")); - assertTrue(Strings.containsLiteral("hello", "h")); - assertFalse(Strings.containsLiteral("hello", "H")); - assertFalse(Strings.containsLiteral("hello", "O")); - assertFalse(Strings.containsLiteral("hello", "x")); - assertFalse(Strings.containsLiteral("hello", "ELL")); - assertTrue(Strings.containsLiteral("hello", "hello")); - assertTrue(Strings.containsLiteral("hELlo", "ELl")); - assertFalse(Strings.containsLiteral("hello", "!")); - } - - public void testContainsLiteralIgnoreCase() { - assertTrue(Strings.containsLiteralIgnoreCase("hello", "ell")); - assertTrue(Strings.containsLiteralIgnoreCase("hello", "H")); - assertTrue(Strings.containsLiteralIgnoreCase("hello", "O")); - assertFalse(Strings.containsLiteralIgnoreCase("hello", "X")); - assertTrue(Strings.containsLiteralIgnoreCase("hello", "ELL")); - assertTrue(Strings.containsLiteralIgnoreCase("hello", "hello")); - assertTrue(Strings.containsLiteralIgnoreCase("hELlo", "Hello")); - assertFalse(Strings.containsLiteralIgnoreCase("hello", "!")); - } - - @Test - public void testDeferredFormat() { - ToStringCounter c = new ToStringCounter(); - FormattedString x = Strings.format("hello %s", c); - Assert.assertEquals(c.count, 0); - Assert.assertEquals(x.toString(), "hello world"); - Assert.assertEquals(c.count, 1); - } - - @Test - public void testToStringSupplier() { - ToStringCounter c = new ToStringCounter(true); - Assert.assertEquals(Strings.toStringSupplier(c).get(), "world1"); - FormattedString x = Strings.format("hello %s", c); - Assert.assertEquals(x.toString(), "hello world2"); - Assert.assertEquals(x.toString(), "hello world3"); - } - - private static class ToStringCounter { - private int count = 0; - private boolean appendCount = false; - private ToStringCounter() {} - private ToStringCounter(boolean append) { this.appendCount = append; } - @Override - public String toString() { - count++; - return "world"+(appendCount?""+count:""); - } - } - - @Test - public void testFormatter() { - Assert.assertEquals(StringFunctions.formatter("hello %s").apply("world"), "hello world"); - Assert.assertEquals(StringFunctions.formatterForArray("%s %s").apply(new String[] { "hello", "world" }), "hello world"); - } - - @Test - public void testJoiner() { - Assert.assertEquals(StringFunctions.joiner(" ").apply(Arrays.asList("hello", "world")), "hello world"); - Assert.assertEquals(StringFunctions.joinerForArray(" ").apply(new String[] { "hello", "world" }), "hello world"); - } - - @Test - public void testSurround() { - Assert.assertEquals(StringFunctions.surround("hello ", " world").apply("new"), "hello new world"); - } - - @Test - public void testFirstWord() { - Assert.assertEquals(Strings.getFirstWord("hello world"), "hello"); - Assert.assertEquals(Strings.getFirstWord(" hello world"), "hello"); - Assert.assertEquals(Strings.getFirstWord(" hello "), "hello"); - Assert.assertEquals(Strings.getFirstWord("hello"), "hello"); - Assert.assertEquals(Strings.getFirstWord(" "), null); - Assert.assertEquals(Strings.getFirstWord(""), null); - Assert.assertEquals(Strings.getFirstWord(null), null); - } - - @Test - public void testLastWord() { - Assert.assertEquals(Strings.getLastWord("hello world"), "world"); - Assert.assertEquals(Strings.getLastWord(" hello world "), "world"); - Assert.assertEquals(Strings.getLastWord(" hello "), "hello"); - Assert.assertEquals(Strings.getLastWord("hello"), "hello"); - Assert.assertEquals(Strings.getLastWord(" "), null); - Assert.assertEquals(Strings.getLastWord(""), null); - Assert.assertEquals(Strings.getLastWord(null), null); - } - - @Test - public void testFirstWordAfter() { - Assert.assertEquals(Strings.getFirstWordAfter("hello world", "hello"), "world"); - Assert.assertEquals(Strings.getFirstWordAfter(" hello world", "hello"), "world"); - Assert.assertEquals(Strings.getFirstWordAfter(" hello world: is not enough", "world:"), "is"); - Assert.assertEquals(Strings.getFirstWordAfter(" hello world: is not enough", "world"), ":"); - Assert.assertEquals(Strings.getFirstWordAfter(" hello ", "hello"), null); - Assert.assertEquals(Strings.getFirstWordAfter("hello", "hello"), null); - Assert.assertEquals(Strings.getFirstWordAfter(" ", "x"), null); - Assert.assertEquals(Strings.getFirstWordAfter("", "x"), null); - Assert.assertEquals(Strings.getFirstWordAfter(null, "x"), null); - } - - @Test - public void testFragmentBetween() { - Assert.assertEquals("ooba", Strings.getFragmentBetween("foobar", "f", "r")); - Assert.assertEquals("oobar", Strings.getFragmentBetween("foobar", "f", "z")); - Assert.assertEquals("oobar", Strings.getFragmentBetween("foobar", "f", null)); - Assert.assertEquals("oba", Strings.getFragmentBetween("foobar", "o", "r")); - Assert.assertEquals("\nba", Strings.getFragmentBetween("foo\nbar", "foo", "r")); - Assert.assertEquals("fooba", Strings.getFragmentBetween("foobar", null, "r")); - Assert.assertEquals(null, Strings.getFragmentBetween("foobar", "z", "r")); - } - - @Test - public void testWordCount() { - Assert.assertEquals(Strings.getWordCount("hello", true), 1); - Assert.assertEquals(Strings.getWordCount("hello world", true), 2); - Assert.assertEquals(Strings.getWordCount("hello\nworld", true), 2); - Assert.assertEquals(Strings.getWordCount("hello world \nit is me!\n", true), 5); - Assert.assertEquals(Strings.getWordCount("", true), 0); - Assert.assertEquals(Strings.getWordCount(null, true), 0); - Assert.assertEquals(Strings.getWordCount("\"hello world\" ", true), 1); - Assert.assertEquals(Strings.getWordCount("\"hello world\" ", false), 2); - Assert.assertEquals(Strings.getWordCount("hello world \nit's me!\n", true), 3); - Assert.assertEquals(Strings.getWordCount("hello world \nit's me!\n", false), 4); - } - - @Test - public void testMakeRealString() { - // less precision = less length - Assert.assertEquals(Strings.makeRealString(1.23456d, 4, 2, 0), "1.2"); - // precision trumps length, and rounds - Assert.assertEquals(Strings.makeRealString(1.23456d, 4, 5, 0), "1.2346"); - // uses E notation when needed - Assert.assertEquals(Strings.makeRealString(123456, 2, 2, 0), "1.2E5"); - // and works with negatives - Assert.assertEquals(Strings.makeRealString(-123456, 2, 2, 0), "-1.2E5"); - // and very small negatives - Assert.assertEquals(Strings.makeRealString(-0.000000000123456, 2, 2, 0), "-1.2E-10"); - // and 0 - Assert.assertEquals(Strings.makeRealString(0.0d, 4, 2, 0), "0"); - // skips E notation and gives extra precision when it's free - Assert.assertEquals(Strings.makeRealString(123456, 8, 2, 0), "123456"); - } - - @Test - public void testCollapseWhitespace() { - Assert.assertEquals(Strings.collapseWhitespace(" x\n y\n", ""), "xy"); - Assert.assertEquals(Strings.collapseWhitespace(" x\n y\n", " "), " x y "); - Assert.assertEquals(Strings.collapseWhitespace(" x\n y\n", "\n").trim(), "x\ny"); - } - - @Test - public void testMaxlen() { - Assert.assertEquals(Strings.maxlen("hello world", 5), "hello"); - Assert.assertEquals(Strings.maxlenWithEllipsis("hello world", 9), "hello ..."); - Assert.assertEquals(Strings.maxlenWithEllipsis("hello world", 7, "--"), "hello--"); - } - - @Test - public void testGetRemainderOfLineAfter() { - // Basic test (also tests start is trimmed) - Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is hello", "is"), " hello"); - Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is is hello", "is"), " is hello"); - // Trim spaces from end - Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is is hello ", "is"), " is hello "); - // Trim non-matching lines from start - Assert.assertEquals(Strings.getRemainderOfLineAfter("one\ntwo\nthree\nthe message is is hello ", "is"), " is hello "); - // Trim lines from end - Assert.assertEquals(Strings.getRemainderOfLineAfter("one\ntwo\nthree\nthe message is is hello \nfour\nfive\nsix\nis not seven", "is"), " is hello "); - // Play nicely with null / non-match - Assert.assertEquals(Strings.getRemainderOfLineAfter(null, "is"), null); - Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is hello", null), null); - Assert.assertEquals(Strings.getRemainderOfLineAfter("the message is hello", "foo"), null); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/text/WildcardGlobsTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/text/WildcardGlobsTest.java b/utils/common/src/test/java/brooklyn/util/text/WildcardGlobsTest.java deleted file mode 100644 index 1417cfe..0000000 --- a/utils/common/src/test/java/brooklyn/util/text/WildcardGlobsTest.java +++ /dev/null @@ -1,236 +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.text; - -import java.util.Arrays; -import java.util.List; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.text.WildcardGlobs.InvalidPatternException; -import brooklyn.util.text.WildcardGlobs.PhraseTreatment; -import brooklyn.util.text.WildcardGlobs.SpecialistGlobExpander; - -@Test -public class WildcardGlobsTest extends Assert { - - @Test - public void testBasic() throws InvalidPatternException { - assertTrue(WildcardGlobs.isGlobMatched("a?{ex,in}", "akin")); - assertTrue(WildcardGlobs.isGlobMatched("a?{ex,in}", "alex")); - assertFalse(WildcardGlobs.isGlobMatched("a?{ex,in}", "appin")); - } - - @Test - public void testEmpty() throws InvalidPatternException { - assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "a")); - assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "ab")); - assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "ac")); - assertTrue(WildcardGlobs.isGlobMatched("a{,?}{,b}", "acb")); - assertFalse(WildcardGlobs.isGlobMatched("a{,?}{,b}", "abc")); - assertFalse(WildcardGlobs.isGlobMatched("a{,?}{,b}", "accb")); - } - - @Test - public void testNum() throws InvalidPatternException { - assertTrue(newGlobExpander().isGlobMatchedNumeric("{1-3}", "1")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3}", "a1")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a1")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a3")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a5")); - assertFalse(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a4")); - assertFalse(newGlobExpander().isGlobMatchedNumeric("a{1-3,5}", "a01")); - } - - @Test - public void testNumLeadZero() throws InvalidPatternException { - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a01")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a01")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a02")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a03")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{ 01 - 03 , 05 }", "a 05 ")); - assertTrue(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a05")); - assertFalse(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a04")); - assertFalse(newGlobExpander().isGlobMatchedNumeric("a{01-03,05}", "a3")); - } - - @Test - public void testOrder() throws InvalidPatternException { - List<String> result; - result = newGlobExpander().expand("{a,b}"); - assertEquals(result, Arrays.asList("a","b"), "Expansion was "+result); - result = newGlobExpander().expand("{{a},b}"); - assertEquals(result, Arrays.asList("a","b"), "Expansion was "+result); - result = newGlobExpander().expand("{a,b}{1,2}"); - assertEquals(result, Arrays.asList("a1","a2","b1","b2"), "Expansion was "+result); - result = newGlobExpander().expand("{80{8{1,2},90},8000+}"); - assertEquals(result, Arrays.asList("8081","8082","8090","8000+"), "Expansion was "+result); - } - - @Test - public void testQuotes() throws InvalidPatternException { - List<String> result; - SpecialistGlobExpander notSpecial = new SpecialistGlobExpander(true, PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR); - result = notSpecial.expand("hello \"{1-3}\""); - assertEquals(3, result.size()); - assertEquals("hello \"1\"", result.get(0)); - - SpecialistGlobExpander expanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_EXPANDABLE, PhraseTreatment.NOT_A_SPECIAL_CHAR); - result = expanding.expand("hello \"{1-3}\""); - assertEquals(3, result.size()); - assertEquals("hello \"1\"", result.get(0)); - result = expanding.expand("hello \"{1,2-3}\""); - assertEquals(3, result.size()); - assertEquals("hello \"2\"", result.get(1)); - - SpecialistGlobExpander notExpanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_NOT_EXPANDABLE, PhraseTreatment.NOT_A_SPECIAL_CHAR); - result = notExpanding.expand("hello \"{1,2-3}\""); - assertEquals(1, result.size()); - assertEquals("hello \"{1,2-3}\"", result.get(0)); - - - result = notSpecial.expand("hello {\"1,2,3\"}"); - assertEquals(3, result.size()); - assertEquals("hello \"1", result.get(0)); - - result = expanding.expand("hello {\"1,2,3\"}"); - assertEquals(1, result.size()); - assertEquals("hello \"1,2,3\"", result.get(0)); - - result = notExpanding.expand("hello {\"1,2,3\"}"); - assertEquals(1, result.size()); - assertEquals("hello \"1,2,3\"", result.get(0)); - - - result = notSpecial.expand("hello {\"1,{02-03,04}\"}"); - assertEquals(4, result.size()); - assertEquals("hello \"1", result.get(0)); - assertEquals("hello 03\"", result.get(2)); - - result = expanding.expand("hello {\"1,{02-03,04}\"}"); - assertEquals(3, result.size()); - assertEquals("hello \"1,02\"", result.get(0)); - - result = notExpanding.expand("hello {\"1,{02-03,04}\"}"); - assertEquals(1, result.size()); - assertEquals("hello \"1,{02-03,04}\"", result.get(0)); - - //no exception - notSpecial.expand("{\"}"); - notSpecial.expand("\"{\"}"); - //exceptions - try { - expanding.expand("\""); - fail("exception expected"); - } catch (InvalidPatternException e) { /* expected */ } - try { - expanding.expand("{\"}"); - fail("exception expected"); - } catch (InvalidPatternException e) { /* expected */ } - try { - expanding.expand("\"{\""); - fail("exception expected"); - } catch (InvalidPatternException e) { /* expected */ } - try { - notExpanding.expand("\""); - fail("exception expected"); - } catch (InvalidPatternException e) { /* expected */ } - try { - notExpanding.expand("{\"}"); - fail("exception expected"); - } catch (InvalidPatternException e) { /* expected */ } - //no exception - notExpanding.expand("\"{\""); - } - - @Test - public void testParen() throws InvalidPatternException { - List<String> result; - SpecialistGlobExpander notSpecial = new SpecialistGlobExpander(true, PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR); - result = notSpecial.expand("hello ({1-3})"); - assertEquals(3, result.size()); - assertEquals("hello (1)", result.get(0)); - - SpecialistGlobExpander expanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_NOT_EXPANDABLE, PhraseTreatment.INTERIOR_EXPANDABLE); - result = expanding.expand("hello ({1-3})"); - assertEquals(3, result.size()); - assertEquals("hello (1)", result.get(0)); - result = expanding.expand("hello ({1,2-3})"); - assertEquals(3, result.size()); - assertEquals("hello (2)", result.get(1)); - - SpecialistGlobExpander notExpanding = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_EXPANDABLE, PhraseTreatment.INTERIOR_NOT_EXPANDABLE); - result = notExpanding.expand("hello ({1,2-3})"); - assertEquals(1, result.size()); - assertEquals("hello ({1,2-3})", result.get(0)); - - result = notSpecial.expand("hello {(1,2,3)}"); - assertEquals(3, result.size()); - assertEquals("hello (1", result.get(0)); - - result = expanding.expand("hello {(1,2,3)}"); - assertEquals(1, result.size()); - assertEquals("hello (1,2,3)", result.get(0)); - - result = notExpanding.expand("hello {(1,2,3)}"); - assertEquals(1, result.size()); - assertEquals("hello (1,2,3)", result.get(0)); - - - result = notSpecial.expand("hello {(1,{02-03,04})}"); - assertEquals(4, result.size()); - assertEquals("hello (1", result.get(0)); - assertEquals("hello 03)", result.get(2)); - - result = expanding.expand("hello {(1,{02-03,04})}"); - assertEquals(3, result.size()); - assertEquals("hello (1,02)", result.get(0)); - - result = notExpanding.expand("hello {(1,{02-03,04})}"); - assertEquals(1, result.size()); - assertEquals("hello (1,{02-03,04})", result.get(0)); - - try { - notExpanding.expand("{(}"); - fail("exception expected"); - } catch (InvalidPatternException e) { /* expected */ } - try { - notExpanding.expand("(()"); - fail("exception expected"); - } catch (InvalidPatternException e) { /* expected */ } - notExpanding.expand("({())"); - } - - @Test - public void testQuotesAndParen() throws InvalidPatternException { - List<String> result; - SpecialistGlobExpander special = new SpecialistGlobExpander(true, PhraseTreatment.INTERIOR_EXPANDABLE, PhraseTreatment.INTERIOR_NOT_EXPANDABLE); - result = special.expand("\"{hello,goodbye}{1-2,({3-4}),(\")}\""); - assertEquals(8, result.size()); - assertTrue(result.contains("\"goodbye2\"")); - assertTrue(result.contains("\"hello({3-4})\"")); - assertTrue(result.contains("\"goodbye(\")\"")); - } - - private SpecialistGlobExpander newGlobExpander() { - return new SpecialistGlobExpander(true, PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/cf2f7a93/utils/common/src/test/java/brooklyn/util/time/CountdownTimerTest.java ---------------------------------------------------------------------- diff --git a/utils/common/src/test/java/brooklyn/util/time/CountdownTimerTest.java b/utils/common/src/test/java/brooklyn/util/time/CountdownTimerTest.java deleted file mode 100644 index 73488e2..0000000 --- a/utils/common/src/test/java/brooklyn/util/time/CountdownTimerTest.java +++ /dev/null @@ -1,93 +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.time; - -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.util.Arrays; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import org.testng.annotations.Test; - -import com.google.common.base.Stopwatch; - -import brooklyn.util.exceptions.Exceptions; - -@Test -public class CountdownTimerTest { - - // Test failed on jenkins when using 1 second, sleeping for 500ms; - // hence relaxing time constraints so is less time-sensitive at the expense of being a slower test. - @Test(groups="Integration") - public void testSimpleExpiry() { - final int TOTAL_TIME_MS = 5*1000; - final int OVERHEAD_MS = 2000; - final int EARLY_RETURN_GRACE_MS = 30; - final int FIRST_SLEEP_TIME_MS = 2500; - final int SECOND_SLEEP_TIME_MS = TOTAL_TIME_MS - FIRST_SLEEP_TIME_MS + EARLY_RETURN_GRACE_MS*2; - - final Duration SIMPLE_DURATION = Duration.millis(TOTAL_TIME_MS); - - CountdownTimer timer = SIMPLE_DURATION.countdownTimer(); - assertFalse(timer.isExpired()); - assertTrue(timer.getDurationElapsed().toMilliseconds() <= OVERHEAD_MS, "elapsed="+timer.getDurationElapsed().toMilliseconds()); - assertTrue(timer.getDurationRemaining().toMilliseconds() >= TOTAL_TIME_MS - OVERHEAD_MS, "remaining="+timer.getDurationElapsed().toMilliseconds()); - - Time.sleep(Duration.millis(FIRST_SLEEP_TIME_MS)); - assertFalse(timer.isExpired()); - assertOrdered(FIRST_SLEEP_TIME_MS - EARLY_RETURN_GRACE_MS, timer.getDurationElapsed().toMilliseconds(), FIRST_SLEEP_TIME_MS + OVERHEAD_MS); - assertOrdered(TOTAL_TIME_MS - FIRST_SLEEP_TIME_MS - OVERHEAD_MS, timer.getDurationRemaining().toMilliseconds(), TOTAL_TIME_MS - FIRST_SLEEP_TIME_MS + EARLY_RETURN_GRACE_MS); - - Time.sleep(Duration.millis(SECOND_SLEEP_TIME_MS)); - assertTrue(timer.isExpired()); - } - - public void testNotify() throws InterruptedException { - CountdownTimer timer = Duration.FIVE_SECONDS.countdownTimer(); - final Object mutex = new Object(); - final Semaphore gun = new Semaphore(0); - Stopwatch watch = Stopwatch.createStarted(); - new Thread(new Runnable() { - @Override - public void run() { - try { gun.acquire(); } catch (Exception e) { throw Exceptions.propagate(e); } - synchronized (mutex) { - mutex.notifyAll(); - } - } - }).start(); - synchronized (mutex) { - gun.release(); - assertTrue(timer.waitOnForExpiry(mutex)); - } - assertTrue(watch.elapsed(TimeUnit.MILLISECONDS) < 3000, "took too long: "+watch); - } - - private void assertOrdered(long... vals) { - String errmsg = "vals="+Arrays.toString(vals); - long prevVal = Long.MIN_VALUE; - for (long val : vals) { - assertTrue(val >= prevVal, errmsg); - prevVal = val; - } - } - -}
