http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/RepeaterTest.groovy ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/RepeaterTest.groovy b/core/src/test/java/brooklyn/util/internal/RepeaterTest.groovy deleted file mode 100644 index 65976e1..0000000 --- a/core/src/test/java/brooklyn/util/internal/RepeaterTest.groovy +++ /dev/null @@ -1,255 +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 java.util.concurrent.TimeUnit.* -import static org.testng.Assert.* - -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit - -import org.testng.annotations.Test - -import brooklyn.util.time.Duration; - -import com.google.common.base.Stopwatch - -public class RepeaterTest { - static { TimeExtras.init() } - - @Test - public void sanityTest() { - new Repeater("Sanity test") - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test - public void sanityTestDescription() { - new Repeater() - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test - public void sanityTestBuilder() { - Repeater.create("Sanity test") - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test - public void sanityTestBuilderDescription() { - Repeater.create() - .repeat() - .until { true } - .every(10 * MILLISECONDS); - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void repeatFailsIfClosureIsNull() { - new Repeater("repeatFailsIfClosureIsNull").repeat((Callable<?>)null); - fail "Expected exception was not thrown" - } - - @Test - public void repeatSucceedsIfClosureIsNonNull() { - new Repeater("repeatSucceedsIfClosureIsNonNull").repeat { true }; - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void untilFailsIfClosureIsNull() { - new Repeater("untilFailsIfClosureIsNull").until(null); - fail "Expected exception was not thrown" - } - - @Test - public void untilSucceedsIfClosureIsNonNull() { - new Repeater("untilSucceedsIfClosureIsNonNull").until { true }; - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void everyFailsIfPeriodIsZero() { - new Repeater("everyFailsIfPeriodIsZero").every(0 * MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void everyFailsIfPeriodIsNegative() { - new Repeater("everyFailsIfPeriodIsNegative").every(-1 * MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void everyFailsIfUnitsIsNull() { - new Repeater("everyFailsIfUnitsIsNull").every(10, null); - fail "Expected exception was not thrown" - } - - @Test - public void everySucceedsIfPeriodIsPositiveAndUnitsIsNonNull() { - new Repeater("repeatSucceedsIfClosureIsNonNull").every(10 * MILLISECONDS); - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void limitTimeToFailsIfPeriodIsZero() { - new Repeater("limitTimeToFailsIfPeriodIsZero").limitTimeTo(0, TimeUnit.MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ IllegalArgumentException.class ]) - public void limitTimeToFailsIfPeriodIsNegative() { - new Repeater("limitTimeToFailsIfPeriodIsNegative").limitTimeTo(-1, TimeUnit.MILLISECONDS); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ NullPointerException.class ]) - public void limitTimeToFailsIfUnitsIsNull() { - new Repeater("limitTimeToFailsIfUnitsIsNull").limitTimeTo(10, null); - fail "Expected exception was not thrown" - } - - @Test - public void limitTimeToSucceedsIfPeriodIsPositiveAndUnitsIsNonNull() { - new Repeater("limitTimeToSucceedsIfClosureIsNonNull").limitTimeTo(10, TimeUnit.MILLISECONDS); - } - - @Test - public void everyAcceptsDuration() { - new Repeater("everyAcceptsDuration").every(Duration.ONE_SECOND); - } - - @Test - public void everyAcceptsLong() { - new Repeater("everyAcceptsLong").every(1000L); - } - - @Test - public void everyAcceptsTimeUnit() { - new Repeater("everyAcceptsTimeUnit").every(1000000L, TimeUnit.MICROSECONDS); - } - - @Test - public void runReturnsTrueIfExitConditionIsTrue() { - assertTrue new Repeater("runReturnsTrueIfExitConditionIsTrue") - .repeat() - .every(1 * MILLISECONDS) - .until { true } - .run(); - } - - @Test - public void runRespectsMaximumIterationLimitAndReturnsFalseIfReached() { - int iterations = 0; - assertFalse new Repeater("runRespectsMaximumIterationLimitAndReturnsFalseIfReached") - .repeat { iterations++ } - .every(1 * MILLISECONDS) - .until { false } - .limitIterationsTo(5) - .run(); - assertEquals 5, iterations; - } - - /** - * Check that the {@link Repeater} will stop after a time limit. - * - * The repeater is configured to run every 100ms and never stop until the limit is reached. - * This is given as {@link Repeater#limitTimeTo(groovy.time.Duration)} and the execution time - * is then checked to ensure it is between 100% and 400% of the specified value. Due to scheduling - * delays and other factors in a non RTOS system it is expected that the repeater will take much - * longer to exit occasionally. - * - * @see #runRespectsMaximumIterationLimitAndReturnsFalseIfReached() - */ - @Test(groups="Integration") - public void runRespectsTimeLimitAndReturnsFalseIfReached() { - final long LIMIT = 2000l; - Repeater repeater = new Repeater("runRespectsTimeLimitAndReturnsFalseIfReached") - .repeat() - .every(100 * MILLISECONDS) - .until { false } - .limitTimeTo(LIMIT, TimeUnit.MILLISECONDS); - - Stopwatch stopwatch = new Stopwatch().start(); - boolean result = repeater.run(); - stopwatch.stop(); - - assertFalse result; - - long difference = stopwatch.elapsed(TimeUnit.MILLISECONDS); - assertTrue(difference >= LIMIT, "Difference was: " + difference); - assertTrue(difference < 4 * LIMIT, "Difference was: " + difference); - } - - @Test(expectedExceptions = [ IllegalStateException.class ]) - public void runFailsIfUntilWasNotSet() { - new Repeater("runFailsIfUntilWasNotSet") - .repeat() - .every(10 * MILLISECONDS) - .run(); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ IllegalStateException.class ]) - public void runFailsIfEveryWasNotSet() { - new Repeater("runFailsIfEveryWasNotSet") - .repeat() - .until { true } - .run(); - fail "Expected exception was not thrown" - } - - @Test(expectedExceptions = [ UnsupportedOperationException.class ]) - public void testRethrowsException() { - boolean result = new Repeater("throwRuntimeException") - .repeat() - .every(10 * MILLISECONDS) - .until { throw new UnsupportedOperationException("fail") } - .rethrowException() - .limitIterationsTo(2) - .run(); - fail "Expected exception was not thrown" - } - - @Test - public void testNoRethrowsException() { - try { - boolean result = new Repeater("throwRuntimeException") - .repeat() - .every(10 * MILLISECONDS) - .until { throw new UnsupportedOperationException("fail") } - .limitIterationsTo(2) - .run(); - assertFalse result - } catch (RuntimeException re) { - fail "Exception should not have been thrown: " + re.getMessage() - } - } - - public void testFlags() { - int count=0; - new Repeater(period: 5*MILLISECONDS, timeout: 100*MILLISECONDS).repeat({ count++ }).until({ count>100}).run(); - assertTrue count>10 - assertTrue count<30 - } - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/TypeCoercionsTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/TypeCoercionsTest.java b/core/src/test/java/brooklyn/util/internal/TypeCoercionsTest.java deleted file mode 100644 index ecb8c7c..0000000 --- a/core/src/test/java/brooklyn/util/internal/TypeCoercionsTest.java +++ /dev/null @@ -1,360 +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.math.BigDecimal; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.codehaus.groovy.runtime.GStringImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.Lifecycle; -import brooklyn.util.collections.MutableSet; -import brooklyn.util.flags.ClassCoercionException; -import brooklyn.util.flags.TypeCoercions; -import brooklyn.util.text.StringPredicates; - -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.reflect.TypeToken; - -public class TypeCoercionsTest { - - private static final Logger log = LoggerFactory.getLogger(TypeCoercionsTest.class); - - @Test - public void testCoerceCharSequenceToString() { - assertEquals(TypeCoercions.coerce(new StringBuilder("abc"), String.class), "abc"); - assertEquals(TypeCoercions.coerce(new GStringImpl(new Object[0], new String[0]), String.class), ""); - } - - @Test - public void testCoerceStringToPrimitive() { - assertEquals(TypeCoercions.coerce("1", Character.class), (Character)'1'); - assertEquals(TypeCoercions.coerce(" ", Character.class), (Character)' '); - assertEquals(TypeCoercions.coerce("1", Short.class), (Short)((short)1)); - assertEquals(TypeCoercions.coerce("1", Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce("1", Long.class), (Long)1l); - assertEquals(TypeCoercions.coerce("1", Float.class), (Float)1f); - assertEquals(TypeCoercions.coerce("1", Double.class), (Double)1d); - assertEquals(TypeCoercions.coerce("true", Boolean.class), (Boolean)true); - assertEquals(TypeCoercions.coerce("False", Boolean.class), (Boolean)false); - assertEquals(TypeCoercions.coerce("true ", Boolean.class), (Boolean)true); - - assertEquals(TypeCoercions.coerce("1", char.class), (Character)'1'); - assertEquals(TypeCoercions.coerce("1", short.class), (Short)((short)1)); - assertEquals(TypeCoercions.coerce("1", int.class), (Integer)1); - assertEquals(TypeCoercions.coerce("1", long.class), (Long)1l); - assertEquals(TypeCoercions.coerce("1", float.class), (Float)1f); - assertEquals(TypeCoercions.coerce("1", double.class), (Double)1d); - assertEquals(TypeCoercions.coerce("TRUE", boolean.class), (Boolean)true); - assertEquals(TypeCoercions.coerce("false", boolean.class), (Boolean)false); - } - - @Test - public void testCoercePrimitivesToSameType() { - assertEquals(TypeCoercions.coerce('1', Character.class), (Character)'1'); - assertEquals(TypeCoercions.coerce((short)1, Short.class), (Short)((short)1)); - assertEquals(TypeCoercions.coerce(1, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce(1l, Long.class), (Long)1l); - assertEquals(TypeCoercions.coerce(1f, Float.class), (Float)1f); - assertEquals(TypeCoercions.coerce(1d, Double.class), (Double)1d); - assertEquals(TypeCoercions.coerce(true, Boolean.class), (Boolean)true); - } - - @Test - public void testCastPrimitives() { - assertEquals(TypeCoercions.coerce(1L, Character.class), (Character)(char)1); - assertEquals(TypeCoercions.coerce(1L, Byte.class), (Byte)(byte)1); - assertEquals(TypeCoercions.coerce(1L, Short.class), (Short)(short)1); - assertEquals(TypeCoercions.coerce(1L, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce(1L, Long.class), (Long)(long)1); - assertEquals(TypeCoercions.coerce(1L, Float.class), (Float)(float)1); - assertEquals(TypeCoercions.coerce(1L, Double.class), (Double)(double)1); - - assertEquals(TypeCoercions.coerce(1L, char.class), (Character)(char)1); - assertEquals(TypeCoercions.coerce(1L, byte.class), (Byte)(byte)1); - assertEquals(TypeCoercions.coerce(1L, short.class), (Short)(short)1); - assertEquals(TypeCoercions.coerce(1L, int.class), (Integer)1); - assertEquals(TypeCoercions.coerce(1L, long.class), (Long)(long)1); - assertEquals(TypeCoercions.coerce(1L, float.class), (Float)(float)1); - assertEquals(TypeCoercions.coerce(1L, double.class), (Double)(double)1); - - assertEquals(TypeCoercions.coerce((char)1, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce((byte)1, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce((short)1, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce((int)1, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce((long)1, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce((float)1, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce((double)1, Integer.class), (Integer)1); - } - - @Test - public void testCoercePrimitiveFailures() { - // error messages don't have to be this exactly, but they should include sufficient information... - assertCoercionFailsWithErrorMatching("maybe", boolean.class, StringPredicates.containsAllLiterals("String", "boolean", "maybe")); - assertCoercionFailsWithErrorMatching("NaN", int.class, StringPredicates.containsAllLiterals("int", "NaN")); - assertCoercionFailsWithErrorMatching('c', boolean.class, StringPredicates.containsAllLiterals("boolean", "(c)")); // will say 'string' rather than 'char' - assertCoercionFailsWithErrorMatching(0, boolean.class, StringPredicates.containsAllLiterals("Integer", "boolean", "0")); - } - - protected void assertCoercionFailsWithErrorMatching(Object input, Class<?> type, Predicate<? super String> errorMessageRequirement) { - try { - Object result = TypeCoercions.coerce(input, type); - Assert.fail("Should have failed type coercion of "+input+" to "+type+", instead got: "+result); - } catch (Exception e) { - if (errorMessageRequirement==null || errorMessageRequirement.apply(e.toString())) - log.info("Primitive coercion failed as expected, with: "+e); - else - Assert.fail("Error from type coercion of "+input+" to "+type+" failed with wrong exception; expected match of "+errorMessageRequirement+" but got: "+e); - } - - } - - @Test - public void testCastToNumericPrimitives() { - assertEquals(TypeCoercions.coerce(BigInteger.ONE, Integer.class), (Integer)1); - assertEquals(TypeCoercions.coerce(BigInteger.ONE, int.class), (Integer)1); - assertEquals(TypeCoercions.coerce(BigInteger.valueOf(Long.MAX_VALUE), Long.class), (Long)Long.MAX_VALUE); - assertEquals(TypeCoercions.coerce(BigInteger.valueOf(Long.MAX_VALUE), long.class), (Long)Long.MAX_VALUE); - - assertEquals(TypeCoercions.coerce(BigDecimal.valueOf(0.5), Double.class), 0.5d, 0.00001d); - assertEquals(TypeCoercions.coerce(BigDecimal.valueOf(0.5), double.class), 0.5d, 0.00001d); - } - - @Test - public void testCoerceStringToBigNumber() { - assertEquals(TypeCoercions.coerce("0.5", BigDecimal.class), BigDecimal.valueOf(0.5)); - assertEquals(TypeCoercions.coerce("1", BigInteger.class), BigInteger.valueOf(1)); - } - - @Test - public void testCoerceStringToEnum() { - assertEquals(TypeCoercions.coerce("STARTING", Lifecycle.class), Lifecycle.STARTING); - assertEquals(TypeCoercions.coerce("Starting", Lifecycle.class), Lifecycle.STARTING); - assertEquals(TypeCoercions.coerce("starting", Lifecycle.class), Lifecycle.STARTING); - - assertEquals(TypeCoercions.coerce("LOWERCASE", PerverseEnum.class), PerverseEnum.lowercase); - assertEquals(TypeCoercions.coerce("CAMELCASE", PerverseEnum.class), PerverseEnum.camelCase); - assertEquals(TypeCoercions.coerce("upper", PerverseEnum.class), PerverseEnum.UPPER); - assertEquals(TypeCoercions.coerce("upper_with_underscore", PerverseEnum.class), PerverseEnum.UPPER_WITH_UNDERSCORE); - assertEquals(TypeCoercions.coerce("LOWER_WITH_UNDERSCORE", PerverseEnum.class), PerverseEnum.lower_with_underscore); - } - public static enum PerverseEnum { - lowercase, - camelCase, - UPPER, - UPPER_WITH_UNDERSCORE, - lower_with_underscore; - } - - @Test(expectedExceptions = ClassCoercionException.class) - public void testCoerceStringToEnumFailure() { - TypeCoercions.coerce("scrambled-eggs", Lifecycle.class); - } - - @Test - public void testListToSetCoercion() { - Set<?> s = TypeCoercions.coerce(ImmutableList.of(1), Set.class); - Assert.assertEquals(s, ImmutableSet.of(1)); - } - - @Test - public void testSetToListCoercion() { - List<?> s = TypeCoercions.coerce(ImmutableSet.of(1), List.class); - Assert.assertEquals(s, ImmutableList.of(1)); - } - - @Test - public void testIterableToArrayCoercion() { - String[] s = TypeCoercions.coerce(ImmutableList.of("a", "b"), String[].class); - Assert.assertTrue(Arrays.equals(s, new String[] {"a", "b"}), "result="+Arrays.toString(s)); - - Integer[] i = TypeCoercions.coerce(ImmutableList.of(1, 2), Integer[].class); - Assert.assertTrue(Arrays.equals(i, new Integer[] {1, 2}), "result="+Arrays.toString(i)); - - int[] i2 = TypeCoercions.coerce(ImmutableList.of(1, 2), int[].class); - Assert.assertTrue(Arrays.equals(i2, new int[] {1, 2}), "result="+Arrays.toString(i2)); - - int[] i3 = TypeCoercions.coerce(MutableSet.of("1", 2), int[].class); - Assert.assertTrue(Arrays.equals(i3, new int[] {1, 2}), "result="+Arrays.toString(i3)); - } - - @Test - public void testListEntryCoercion() { - List<?> s = TypeCoercions.coerce(ImmutableList.of("java.lang.Integer", "java.lang.Double"), new TypeToken<List<Class<?>>>() { }); - Assert.assertEquals(s, ImmutableList.of(Integer.class, Double.class)); - } - - @Test - public void testListEntryToSetCoercion() { - Set<?> s = TypeCoercions.coerce(ImmutableList.of("java.lang.Integer", "java.lang.Double"), new TypeToken<Set<Class<?>>>() { }); - Assert.assertEquals(s, ImmutableSet.of(Integer.class, Double.class)); - } - - @Test - public void testListEntryToCollectionCoercion() { - Collection<?> s = TypeCoercions.coerce(ImmutableList.of("java.lang.Integer", "java.lang.Double"), new TypeToken<Collection<Class<?>>>() { }); - Assert.assertEquals(s, ImmutableList.of(Integer.class, Double.class)); - } - - @Test - public void testMapValueCoercion() { - Map<?,?> s = TypeCoercions.coerce(ImmutableMap.of("int", "java.lang.Integer", "double", "java.lang.Double"), new TypeToken<Map<String, Class<?>>>() { }); - Assert.assertEquals(s, ImmutableMap.of("int", Integer.class, "double", Double.class)); - } - - @Test - public void testMapKeyCoercion() { - Map<?,?> s = TypeCoercions.coerce(ImmutableMap.of("java.lang.Integer", "int", "java.lang.Double", "double"), new TypeToken<Map<Class<?>, String>>() { }); - Assert.assertEquals(s, ImmutableMap.of(Integer.class, "int", Double.class, "double")); - } - - @Test - public void testStringToListCoercion() { - List<?> s = TypeCoercions.coerce("a,b,c", List.class); - Assert.assertEquals(s, ImmutableList.of("a", "b", "c")); - } - - @Test - @SuppressWarnings("serial") - public void testCoerceRecursivelyStringToGenericsCollection() { - assertEquals(TypeCoercions.coerce("1,2", new TypeToken<List<Integer>>() {}), ImmutableList.of(1, 2)); - } - - @Test - public void testJsonStringToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("{ \"a\" : \"1\", b : 2 }", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", "1", "b", 2)); - } - - @Test - public void testJsonStringWithoutQuotesToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("{ a : 1 }", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", 1)); - } - - @Test - public void testJsonComplexTypesToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("{ a : [1, \"2\", '\"3\"'], b: { c: d, 'e': \"f\" } }", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", ImmutableList.<Object>of(1, "2", "\"3\""), - "b", ImmutableMap.of("c", "d", "e", "f"))); - } - - @Test - public void testJsonStringWithoutBracesToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("a : 1", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", 1)); - } - - @Test - public void testJsonStringWithoutBracesWithMultipleToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("a : 1, b : 2", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", 1, "b", 2)); - } - - @Test - public void testKeyEqualsValueStringToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("a=1,b=2", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", "1", "b", "2")); - } - - @Test(expectedExceptions=IllegalArgumentException.class) - public void testJsonStringWithoutBracesOrSpaceDisallowedAsMapCoercion() { - // yaml requires spaces after the colon - Map<?,?> s = TypeCoercions.coerce("a:1,b:2", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", 1, "b", 2)); - } - - @Test - public void testEqualsInBracesMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("{ a = 1, b = '2' }", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", 1, "b", "2")); - } - - @Test - public void testKeyEqualsOrColonValueWithBracesStringToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("{ a=1, b: 2 }", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", "1", "b", 2)); - } - - @Test - public void testKeyEqualsOrColonValueWithoutBracesStringToMapCoercion() { - Map<?,?> s = TypeCoercions.coerce("a=1, b: 2", Map.class); - Assert.assertEquals(s, ImmutableMap.of("a", "1", "b", 2)); - } - - @Test - public void testAs() { - Integer x = TypeCoercions.coerce(new WithAs("3"), Integer.class); - Assert.assertEquals(x, (Integer)3); - } - - @Test - public void testFrom() { - WithFrom x = TypeCoercions.coerce("3", WithFrom.class); - Assert.assertEquals(x.value, 3); - } - - @Test - public void testCoerceStringToNumber() { - assertEquals(TypeCoercions.coerce("1", Number.class), (Number) Double.valueOf(1)); - assertEquals(TypeCoercions.coerce("1.0", Number.class), (Number) Double.valueOf(1.0)); - } - - @Test(expectedExceptions = ClassCoercionException.class) - public void testInvalidCoercionThrowsClassCoercionException() { - TypeCoercions.coerce(new Object(), TypeToken.of(Integer.class)); - } - - @Test - public void testCoercionFunction() { - assertEquals(TypeCoercions.function(Double.class).apply("1"), Double.valueOf(1)); - } - - public static class WithAs { - String value; - public WithAs(Object x) { value = ""+x; } - public Integer asInteger() { - return Integer.parseInt(value); - } - } - - public static class WithFrom { - int value; - public static WithFrom fromString(String s) { - WithFrom result = new WithFrom(); - result.value = Integer.parseInt(s); - return result; - } - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/RecordingSshTool.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/RecordingSshTool.java b/core/src/test/java/brooklyn/util/internal/ssh/RecordingSshTool.java deleted file mode 100644 index 8c556a6..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/RecordingSshTool.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.util.internal.ssh; - -import java.io.File; -import java.io.InputStream; -import java.util.List; -import java.util.Map; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; - -/** Mock tool */ -public class RecordingSshTool implements SshTool { - - public static class ExecCmd { - public final Map<String,?> props; - public final String summaryForLogging; - public final List<String> commands; - public final Map<?,?> env; - - ExecCmd(Map<String,?> props, String summaryForLogging, List<String> commands, Map env) { - this.props = props; - this.summaryForLogging = summaryForLogging; - this.commands = commands; - this.env = env; - } - - @Override - public String toString() { - return "ExecCmd["+summaryForLogging+": "+commands+"; "+props+"; "+env+"]"; - } - } - - public static List<ExecCmd> execScriptCmds = Lists.newCopyOnWriteArrayList(); - - private boolean connected; - - public RecordingSshTool(Map<?,?> props) { - } - @Override public void connect() { - connected = true; - } - @Override public void connect(int maxAttempts) { - connected = true; - } - @Override public void disconnect() { - connected = false; - } - @Override public boolean isConnected() { - return connected; - } - @Override public int execScript(Map<String, ?> props, List<String> commands, Map<String, ?> env) { - execScriptCmds.add(new ExecCmd(props, "", commands, env)); - return 0; - } - @Override public int execScript(Map<String, ?> props, List<String> commands) { - return execScript(props, commands, ImmutableMap.<String,Object>of()); - } - @Override public int execCommands(Map<String, ?> props, List<String> commands, Map<String, ?> env) { - execScriptCmds.add(new ExecCmd(props, "", commands, env)); - return 0; - } - @Override public int execCommands(Map<String, ?> props, List<String> commands) { - return execCommands(props, commands, ImmutableMap.<String,Object>of()); - } - @Override public int copyToServer(Map<String, ?> props, File localFile, String pathAndFileOnRemoteServer) { - return 0; - } - @Override public int copyToServer(Map<String, ?> props, InputStream contents, String pathAndFileOnRemoteServer) { - return 0; - } - @Override public int copyToServer(Map<String, ?> props, byte[] contents, String pathAndFileOnRemoteServer) { - return 0; - } - @Override public int copyFromServer(Map<String, ?> props, String pathAndFileOnRemoteServer, File local) { - return 0; - } -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/ShellToolAbstractTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/ShellToolAbstractTest.java b/core/src/test/java/brooklyn/util/internal/ssh/ShellToolAbstractTest.java deleted file mode 100644 index b8b394b..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/ShellToolAbstractTest.java +++ /dev/null @@ -1,439 +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.ssh; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; -import brooklyn.util.config.ConfigBag; -import brooklyn.util.text.Identifiers; -import brooklyn.util.time.Time; - -import com.google.common.base.Stopwatch; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; - -public abstract class ShellToolAbstractTest { - - protected List<ShellTool> tools = Lists.newArrayList(); - protected List<String> filesCreated; - protected String localFilePath; - - protected ShellTool tool; - - protected ShellTool newTool() { - return newTool(MutableMap.<String,Object>of()); - } - - protected ShellTool newTool(Map<String,?> flags) { - ShellTool t = newUnregisteredTool(flags); - tools.add(t); - return t; - } - - protected abstract ShellTool newUnregisteredTool(Map<String,?> flags); - - protected ShellTool tool() { return tool; } - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - localFilePath = "/tmp/ssh-test-local-"+Identifiers.makeRandomId(8); - filesCreated = new ArrayList<String>(); - filesCreated.add(localFilePath); - - tool = newTool(); - connect(tool); - } - - @AfterMethod(alwaysRun=true) - public void afterMethod() throws Exception { - for (ShellTool t : tools) { - if (t instanceof SshTool) ((SshTool)t).disconnect(); - } - for (String fileCreated : filesCreated) { - new File(fileCreated).delete(); - } - } - - protected static void connect(ShellTool tool) { - if (tool instanceof SshTool) - ((SshTool)tool).connect(); - } - - @Test(groups = {"Integration"}) - public void testExecConsecutiveCommands() throws Exception { - String out = execScript("echo run1"); - String out2 = execScript("echo run2"); - - assertTrue(out.contains("run1"), "out="+out); - assertTrue(out2.contains("run2"), "out="+out); - } - - @Test(groups = {"Integration"}) - public void testExecScriptChainOfCommands() throws Exception { - String out = execScript("export MYPROP=abc", "echo val is $MYPROP"); - - assertTrue(out.contains("val is abc"), "out="+out); - } - - @Test(groups = {"Integration"}) - public void testExecScriptReturningNonZeroExitCode() throws Exception { - int exitcode = tool.execScript(MutableMap.<String,Object>of(), ImmutableList.of("exit 123")); - assertEquals(exitcode, 123); - } - - @Test(groups = {"Integration"}) - public void testExecScriptReturningZeroExitCode() throws Exception { - int exitcode = tool.execScript(MutableMap.<String,Object>of(), ImmutableList.of("date")); - assertEquals(exitcode, 0); - } - - @Test(groups = {"Integration"}) - public void testExecScriptCommandWithEnvVariables() throws Exception { - String out = execScript(ImmutableList.of("echo val is $MYPROP2"), ImmutableMap.of("MYPROP2", "myval")); - - assertTrue(out.contains("val is myval"), "out="+out); - } - - @Test(groups = {"Integration"}) - public void testScriptDataNotLost() throws Exception { - String out = execScript("echo `echo foo``echo bar`"); - - assertTrue(out.contains("foobar"), "out="+out); - } - - @Test(groups = {"Integration"}) - public void testExecScriptWithSleepThenExit() throws Exception { - Stopwatch watch = Stopwatch.createStarted(); - execScript("sleep 1", "exit 0"); - assertTrue(watch.elapsed(TimeUnit.MILLISECONDS) > 900, "only slept "+Time.makeTimeStringRounded(watch)); - } - - // Really just tests that it returns; the command will be echo'ed automatically so this doesn't assert the command will have been executed - @Test(groups = {"Integration"}) - public void testExecScriptBigCommand() throws Exception { - String bigstring = Strings.repeat("a", 10000); - String out = execScript("echo "+bigstring); - - assertTrue(out.contains(bigstring), "out="+out); - } - - @Test(groups = {"Integration"}) - public void testExecScriptBigChainOfCommand() throws Exception { - String bigstring = Strings.repeat("abcdefghij", 100); // 1KB - List<String> cmds = Lists.newArrayList(); - for (int i = 0; i < 10; i++) { - cmds.add("export MYPROP"+i+"="+bigstring); - cmds.add("echo val"+i+" is $MYPROP"+i); - } - String out = execScript(cmds); - - for (int i = 0; i < 10; i++) { - assertTrue(out.contains("val"+i+" is "+bigstring), "out="+out); - } - } - - @Test(groups = {"Integration"}) - public void testExecScriptAbortsOnCommandFailure() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int exitcode = tool.execScript(ImmutableMap.of("out", out), ImmutableList.of("export MYPROP=myval", "acmdthatdoesnotexist", "echo val is $MYPROP")); - String outstr = new String(out.toByteArray()); - - assertFalse(outstr.contains("val is myval"), "out="+out); - assertNotEquals(exitcode, 0); - } - - @Test(groups = {"Integration"}) - public void testExecScriptWithSleepThenBigCommand() throws Exception { - String bigstring = Strings.repeat("abcdefghij", 1000); // 10KB - String out = execScript("sleep 2", "export MYPROP="+bigstring, "echo val is $MYPROP"); - assertTrue(out.contains("val is "+bigstring), "out="+out); - } - - @Test(groups = {"WIP", "Integration"}) - public void testExecScriptBigConcurrentCommand() throws Exception { - ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); - List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(); - try { - for (int i = 0; i < 10; i++) { - final ShellTool localtool = newTool(); - connect(localtool); - - futures.add(executor.submit(new Runnable() { - public void run() { - String bigstring = Strings.repeat("abcdefghij", 1000); // 10KB - String out = execScript(localtool, ImmutableList.of("export MYPROP="+bigstring, "echo val is $MYPROP")); - assertTrue(out.contains("val is "+bigstring), "outSize="+out.length()+"; out="+out); - }})); - } - Futures.allAsList(futures).get(); - } finally { - executor.shutdownNow(); - } - } - - @Test(groups = {"WIP", "Integration"}) - public void testExecScriptBigConcurrentSleepyCommand() throws Exception { - ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); - List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(); - try { - long starttime = System.currentTimeMillis(); - for (int i = 0; i < 10; i++) { - final ShellTool localtool = newTool(); - connect(localtool); - - futures.add(executor.submit(new Runnable() { - public void run() { - String bigstring = Strings.repeat("abcdefghij", 1000); // 10KB - String out = execScript(localtool, ImmutableList.of("sleep 2", "export MYPROP="+bigstring, "echo val is $MYPROP")); - assertTrue(out.contains("val is "+bigstring), "out="+out); - }})); - } - Futures.allAsList(futures).get(); - long runtime = System.currentTimeMillis() - starttime; - - long OVERHEAD = 20*1000; - assertTrue(runtime < 2000+OVERHEAD, "runtime="+runtime); - - } finally { - executor.shutdownNow(); - } - } - - @Test(groups = {"Integration"}) - public void testExecChainOfCommands() throws Exception { - String out = execCommands("MYPROP=abc", "echo val is $MYPROP"); - - assertEquals(out, "val is abc\n"); - } - - @Test(groups = {"Integration"}) - public void testExecReturningNonZeroExitCode() throws Exception { - int exitcode = tool.execCommands(MutableMap.<String,Object>of(), ImmutableList.of("exit 123")); - assertEquals(exitcode, 123); - } - - @Test(groups = {"Integration"}) - public void testExecReturningZeroExitCode() throws Exception { - int exitcode = tool.execCommands(MutableMap.<String,Object>of(), ImmutableList.of("date")); - assertEquals(exitcode, 0); - } - - @Test(groups = {"Integration"}) - public void testExecCommandWithEnvVariables() throws Exception { - String out = execCommands(ImmutableList.of("echo val is $MYPROP2"), ImmutableMap.of("MYPROP2", "myval")); - - assertEquals(out, "val is myval\n"); - } - - @Test(groups = {"Integration"}) - public void testExecBigCommand() throws Exception { - String bigstring = Strings.repeat("abcdefghij", 1000); // 10KB - String out = execCommands("echo "+bigstring); - - assertEquals(out, bigstring+"\n", "actualSize="+out.length()+"; expectedSize="+bigstring.length()); - } - - @Test(groups = {"Integration"}) - public void testExecBigConcurrentCommand() throws Exception { - runExecBigConcurrentCommand(10, 0L); - } - - // TODO Fails I believe due to synchronization model in SshjTool of calling connect/disconnect. - // Even with a retry-count of 4, it still fails because some commands are calling disconnect - // while another concurrently executing command expects to be still connected. - @Test(groups = {"Integration", "WIP"}) - public void testExecBigConcurrentCommandWithStaggeredStart() throws Exception { - // This test is to vary the concurrency of concurrent actions - runExecBigConcurrentCommand(50, 100L); - } - - protected void runExecBigConcurrentCommand(int numCommands, long staggeredDelayBeforeStart) throws Exception { - ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); - List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(); - try { - for (int i = 0; i < numCommands; i++) { - long delay = (long) (Math.random() * staggeredDelayBeforeStart); - if (i > 0) Time.sleep(delay); - - futures.add(executor.submit(new Runnable() { - public void run() { - String bigstring = Strings.repeat("abcdefghij", 1000); // 10KB - String out = execCommands("echo "+bigstring); - assertEquals(out, bigstring+"\n", "actualSize="+out.length()+"; expectedSize="+bigstring.length()); - }})); - } - Futures.allAsList(futures).get(); - } finally { - executor.shutdownNow(); - } - } - - // fails if terminal enabled - @Test(groups = {"Integration"}) - @Deprecated // tests deprecated code - public void testExecScriptCapturesStderr() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - String nonExistantCmd = "acmdthatdoesnotexist"; - tool.execScript(ImmutableMap.of("out", out, "err", err), ImmutableList.of(nonExistantCmd)); - assertTrue(new String(err.toByteArray()).contains(nonExistantCmd+": command not found"), "out="+out+"; err="+err); - } - - // fails if terminal enabled - @Test(groups = {"Integration"}) - @Deprecated // tests deprecated code - public void testExecCapturesStderr() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - String nonExistantCmd = "acmdthatdoesnotexist"; - tool.execCommands(ImmutableMap.of("out", out, "err", err), ImmutableList.of(nonExistantCmd)); - String errMsg = new String(err.toByteArray()); - assertTrue(errMsg.contains(nonExistantCmd+": command not found\n"), "errMsg="+errMsg+"; out="+out+"; err="+err); - - } - - @Test(groups = {"Integration"}) - public void testScriptHeader() { - final ShellTool localtool = newTool(); - String out = execScript(MutableMap.of("scriptHeader", "#!/bin/bash -e\necho hello world\n"), - localtool, Arrays.asList("echo goodbye world"), null); - assertTrue(out.contains("goodbye world"), "no goodbye in output: "+out); - assertTrue(out.contains("hello world"), "no hello in output: "+out); - } - - @Test(groups = {"Integration"}) - public void testStdErr() { - final ShellTool localtool = newTool(); - Map<String,Object> props = new LinkedHashMap<String, Object>(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - props.put("out", out); - props.put("err", err); - int exitcode = localtool.execScript(props, Arrays.asList("echo hello err > /dev/stderr"), null); - assertFalse(out.toString().contains("hello err"), "hello found where it shouldn't have been, in stdout: "+out); - assertTrue(err.toString().contains("hello err"), "no hello in stderr: "+err); - assertEquals(0, exitcode); - } - - @Test(groups = {"Integration"}) - public void testRunAsRoot() { - final ShellTool localtool = newTool(); - Map<String,Object> props = new LinkedHashMap<String, Object>(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - props.put("out", out); - props.put("err", err); - props.put(SshTool.PROP_RUN_AS_ROOT.getName(), true); - int exitcode = localtool.execScript(props, Arrays.asList("whoami"), null); - assertTrue(out.toString().contains("root"), "not running as root; whoami is: "+out+" (err is '"+err+"')"); - assertEquals(0, exitcode); - } - - @Test(groups = {"Integration"}) - public void testExecScriptEchosExecute() throws Exception { - String out = execScript("date"); - assertTrue(out.toString().contains("Executed"), "Executed did not display: "+out); - } - - @Test(groups = {"Integration"}) - public void testExecScriptEchosDontExecuteWhenToldNoExtraOutput() throws Exception { - final ShellTool localtool = newTool(); - Map<String,Object> props = new LinkedHashMap<String, Object>(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - props.put("out", out); - props.put("err", err); - props.put(SshTool.PROP_NO_EXTRA_OUTPUT.getName(), true); - int exitcode = localtool.execScript(props, Arrays.asList("echo hello world"), null); - assertFalse(out.toString().contains("Executed"), "Executed should not have displayed: "+out); - assertEquals(out.toString().trim(), "hello world"); - assertEquals(0, exitcode); - } - - protected String execCommands(String... cmds) { - return execCommands(Arrays.asList(cmds)); - } - - protected String execCommands(List<String> cmds) { - return execCommands(cmds, ImmutableMap.<String,Object>of()); - } - - protected String execCommands(List<String> cmds, Map<String,?> env) { - return execCommands(null, cmds, env); - } - - protected String execCommands(ConfigBag config, List<String> cmds, Map<String,?> env) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - MutableMap<String,Object> flags = MutableMap.<String,Object>of("out", out); - if (config!=null) flags.add(config.getAllConfig()); - tool.execCommands(flags, cmds, env); - return new String(out.toByteArray()); - } - - protected String execScript(String... cmds) { - return execScript(tool, Arrays.asList(cmds)); - } - - protected String execScript(ShellTool t, List<String> cmds) { - return execScript(ImmutableMap.<String,Object>of(), t, cmds, ImmutableMap.<String,Object>of()); - } - - protected String execScript(List<String> cmds) { - return execScript(cmds, ImmutableMap.<String,Object>of()); - } - - protected String execScript(List<String> cmds, Map<String,?> env) { - return execScript(MutableMap.<String,Object>of(), tool, cmds, env); - } - - protected String execScript(Map<String, ?> props, ShellTool tool, List<String> cmds, Map<String,?> env) { - Map<String, Object> props2 = new LinkedHashMap<String, Object>(props); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - props2.put("out", out); - int exitcode = tool.execScript(props2, cmds, env); - String outstr = new String(out.toByteArray()); - assertEquals(exitcode, 0, outstr); - return outstr; - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java b/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java deleted file mode 100644 index 84b1029..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java +++ /dev/null @@ -1,301 +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.ssh; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.util.Arrays; -import java.util.Calendar; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; -import brooklyn.util.exceptions.Exceptions; -import brooklyn.util.os.Os; -import brooklyn.util.text.Identifiers; -import brooklyn.util.text.Strings; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.io.Files; - -/** - * Test the operation of the {@link SshTool} utility class; to be extended to test concrete implementations. - * - * Requires keys set up, e.g. running: - * - * <pre> - * cd ~/.ssh - * ssh-keygen - * id_rsa_with_passphrase - * mypassphrase - * mypassphrase - * </pre> - * - */ -public abstract class SshToolAbstractIntegrationTest extends ShellToolAbstractTest { - - private static final Logger log = LoggerFactory.getLogger(SshToolAbstractIntegrationTest.class); - - // FIXME need tests which take properties set in entities and brooklyn.properties; - // but not in this class because it is lower level than entities, Aled would argue. - - // TODO No tests for retry logic and exception handing yet - - public static final String SSH_KEY_WITH_PASSPHRASE = System.getProperty("sshPrivateKeyWithPassphrase", "~/.ssh/id_rsa_with_passphrase"); - public static final String SSH_PASSPHRASE = System.getProperty("sshPrivateKeyPassphrase", "mypassphrase"); - - protected String remoteFilePath; - - protected SshTool tool() { return (SshTool)tool; } - - protected abstract SshTool newUnregisteredTool(Map<String,?> flags); - - @Override - protected SshTool newTool() { - return newTool(ImmutableMap.of("host", "localhost", "privateKeyFile", "~/.ssh/id_rsa")); - } - - @Override - protected SshTool newTool(Map<String,?> flags) { - return (SshTool) super.newTool(flags); - } - - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - super.setUp(); - remoteFilePath = "/tmp/ssh-test-remote-"+Identifiers.makeRandomId(8); - filesCreated.add(remoteFilePath); - } - - protected void assertRemoteFileContents(String remotePath, String expectedContents) { - String catout = execCommands("cat "+remotePath); - assertEquals(catout, expectedContents); - } - - /** - * @param remotePath - * @param expectedPermissions Of the form, for example, "-rw-r--r--" - */ - protected void assertRemoteFilePermissions(String remotePath, String expectedPermissions) { - String lsout = execCommands("ls -l "+remotePath); - assertTrue(lsout.contains(expectedPermissions), lsout); - } - - protected void assertRemoteFileLastModifiedIsNow(String remotePath) { - // Check default last-modified time is `now`. - // Be lenient in assertion, in case unlucky that clock ticked over to next hour/minute as test was running. - // TODO Code could be greatly improved, but low priority! - // Output format: - // -rw-r--r-- 1 aled wheel 18 Apr 24 15:03 /tmp/ssh-test-remote-CvFN9zQA - // [0] [1] [2] [3] [4] [5] [6] [7] [8] - - String lsout = execCommands("ls -l "+remotePath); - - String[] lsparts = lsout.split("\\s+"); - int day = Integer.parseInt(lsparts[6]); - int hour = Integer.parseInt(lsparts[7].split(":")[0]); - int minute = Integer.parseInt(lsparts[7].split(":")[1]); - - Calendar expected = Calendar.getInstance(); - int expectedDay = expected.get(Calendar.DAY_OF_MONTH); - int expectedHour = expected.get(Calendar.HOUR_OF_DAY); - int expectedMinute = expected.get(Calendar.MINUTE); - - assertEquals(day, expectedDay, "ls="+lsout+"; lsparts="+Arrays.toString(lsparts)+"; expected="+expected+"; expectedDay="+expectedDay+"; day="+day+"; zone="+expected.getTimeZone()); - assertTrue(Math.abs(hour - expectedHour) <= 1, "ls="+lsout+"; lsparts="+Arrays.toString(lsparts)+"; expected="+expected+"; expectedHour="+expectedHour+"; hour="+hour+"; zone="+expected.getTimeZone()); - assertTrue(Math.abs(minute - expectedMinute) <= 1, "ls="+lsout+"; lsparts="+Arrays.toString(lsparts)+"; expected="+expected+"; expectedMinute="+expectedMinute+"; minute="+minute+"; zone="+expected.getTimeZone()); - } - - @Test(groups = {"Integration"}) - public void testCopyToServerFromBytes() throws Exception { - String contents = "echo hello world!\n"; - byte[] contentBytes = contents.getBytes(); - tool().copyToServer(MutableMap.<String,Object>of(), contentBytes, remoteFilePath); - - assertRemoteFileContents(remoteFilePath, contents); - assertRemoteFilePermissions(remoteFilePath, "-rw-r--r--"); - - // TODO would like to also assert lastModified time, but on jenkins the jvm locale - // and the OS locale are different (i.e. different timezones) so the file time-stamp - // is several hours out. - //assertRemoteFileLastModifiedIsNow(remoteFilePath); - } - - @Test(groups = {"Integration"}) - public void testCopyToServerFromInputStream() throws Exception { - String contents = "echo hello world!\n"; - ByteArrayInputStream contentsStream = new ByteArrayInputStream(contents.getBytes()); - tool().copyToServer(MutableMap.<String,Object>of(), contentsStream, remoteFilePath); - - assertRemoteFileContents(remoteFilePath, contents); - } - - @Test(groups = {"Integration"}) - public void testCopyToServerWithPermissions() throws Exception { - tool().copyToServer(ImmutableMap.of("permissions","0754"), "echo hello world!\n".getBytes(), remoteFilePath); - - assertRemoteFilePermissions(remoteFilePath, "-rwxr-xr--"); - } - - @Test(groups = {"Integration"}) - public void testCopyToServerWithLastModifiedDate() throws Exception { - long lastModificationTime = 1234567; - tool().copyToServer(ImmutableMap.of("lastModificationDate", lastModificationTime), "echo hello world!\n".getBytes(), remoteFilePath); - - String lsout = execCommands("ls -l "+remoteFilePath);//+" | awk '{print \$6 \" \" \$7 \" \" \$8}'"]) - //execCommands([ "ls -l "+remoteFilePath+" | awk '{print \$6 \" \" \$7 \" \" \$8}'"]) - //varies depending on timezone - assertTrue(lsout.contains("Jan 15 1970") || lsout.contains("Jan 14 1970") || lsout.contains("Jan 16 1970"), lsout); - //assertLastModified(lsout, lastModifiedDate) - } - - @Test(groups = {"Integration"}) - public void testCopyFileToServerWithPermissions() throws Exception { - String contents = "echo hello world!\n"; - Files.write(contents, new File(localFilePath), Charsets.UTF_8); - tool().copyToServer(ImmutableMap.of("permissions", "0754"), new File(localFilePath), remoteFilePath); - - assertRemoteFileContents(remoteFilePath, contents); - - String lsout = execCommands("ls -l "+remoteFilePath); - assertTrue(lsout.contains("-rwxr-xr--"), lsout); - } - - @Test(groups = {"Integration"}) - public void testCopyFromServer() throws Exception { - String contentsWithoutLineBreak = "echo hello world!"; - String contents = contentsWithoutLineBreak+"\n"; - tool().copyToServer(MutableMap.<String,Object>of(), contents.getBytes(), remoteFilePath); - - tool().copyFromServer(MutableMap.<String,Object>of(), remoteFilePath, new File(localFilePath)); - - List<String> actual = Files.readLines(new File(localFilePath), Charsets.UTF_8); - assertEquals(actual, ImmutableList.of(contentsWithoutLineBreak)); - } - - // TODO No config options in sshj or scp for auto-creating the parent directories - @Test(enabled=false, groups = {"Integration"}) - public void testCopyFileToNonExistantDir() throws Exception { - String contents = "echo hello world!\n"; - String remoteFileDirPath = "/tmp/ssh-test-remote-dir-"+Identifiers.makeRandomId(8); - String remoteFileInDirPath = remoteFileDirPath + File.separator + "ssh-test-remote-"+Identifiers.makeRandomId(8); - filesCreated.add(remoteFileInDirPath); - filesCreated.add(remoteFileDirPath); - - tool().copyToServer(MutableMap.<String,Object>of(), contents.getBytes(), remoteFileInDirPath); - - assertRemoteFileContents(remoteFileInDirPath, contents); - } - - - @Test(groups = {"Integration"}) - public void testAllocatePty() { - final ShellTool localtool = newTool(MutableMap.of("host", "localhost", SshTool.PROP_ALLOCATE_PTY.getName(), true)); - Map<String,Object> props = new LinkedHashMap<String, Object>(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - props.put("out", out); - props.put("err", err); - int exitcode = localtool.execScript(props, Arrays.asList("echo hello err > /dev/stderr"), null); - assertTrue(out.toString().contains("hello err"), "no hello in output: "+out+" (err is '"+err+"')"); - assertFalse(err.toString().contains("hello err"), "hello found in stderr: "+err); - assertEquals(0, exitcode); - } - - // Requires setting up an extra ssh key, with a passphrase, and adding it to ~/.ssh/authorized_keys - @Test(groups = {"Integration"}) - public void testSshKeyWithPassphrase() throws Exception { - final SshTool localtool = newTool(ImmutableMap.<String,Object>builder() - .put(SshTool.PROP_HOST.getName(), "localhost") - .put(SshTool.PROP_PRIVATE_KEY_FILE.getName(), SSH_KEY_WITH_PASSPHRASE) - .put(SshTool.PROP_PRIVATE_KEY_PASSPHRASE.getName(), SSH_PASSPHRASE) - .build()); - localtool.connect(); - - assertEquals(tool.execScript(MutableMap.<String,Object>of(), ImmutableList.of("date")), 0); - - // Also needs the negative test to prove that we're really using an ssh-key with a passphrase - try { - final SshTool localtool2 = newTool(ImmutableMap.<String,Object>builder() - .put(SshTool.PROP_HOST.getName(), "localhost") - .put(SshTool.PROP_PRIVATE_KEY_FILE.getName(), SSH_KEY_WITH_PASSPHRASE) - .build()); - localtool2.connect(); - fail(); - } catch (Exception e) { - SshException se = Exceptions.getFirstThrowableOfType(e, SshException.class); - if (se == null) throw e; - } - } - - @Test(groups = {"Integration"}) - public void testConnectWithInvalidUserThrowsException() throws Exception { - final ShellTool localtool = newTool(ImmutableMap.of("user", "wronguser", "host", "localhost", "privateKeyFile", "~/.ssh/id_rsa")); - tools.add(localtool); - try { - connect(localtool); - fail(); - } catch (SshException e) { - if (!e.toString().contains("failed to connect")) throw e; - } - } - - @Test(groups = {"Integration"}) - public void testOutputAsExpected() throws Exception { - final String CONTENTS = "hello world\n" - + "bye bye\n"; - execCommands("cat > "+Os.mergePaths(Os.tmp(), "test1")+" << X\n" - + CONTENTS - + "X\n"); - String read = execCommands("echo START_FOO", "cat "+Os.mergePaths(Os.tmp(), "test1"), "echo END_FOO"); - log.debug("read back data written, as:\n"+read); - String contents = Strings.getFragmentBetween(read, "START_FOO", "END_FOO"); - Assert.assertEquals(CONTENTS.trim(), contents.trim()); - } - - @Test(groups = {"Integration"}) - public void testScriptDirPropertiesIsRespected() { - // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898 - final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi"; - - SshTool sshTool = newTool(ImmutableMap.<String, Object>builder() - .put(SshTool.PROP_HOST.getName(), "localhost") - .build()); - int rc = sshTool.execScript(ImmutableMap.<String, Object>builder() - .put(SshTool.PROP_SCRIPT_DIR.getName(), "/var/tmp") - .build(), ImmutableList.of(command)); - assertEquals(rc, 0); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractPerformanceTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractPerformanceTest.java b/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractPerformanceTest.java deleted file mode 100644 index be1441a..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractPerformanceTest.java +++ /dev/null @@ -1,137 +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.ssh; - -import java.io.ByteArrayOutputStream; -import java.lang.management.ManagementFactory; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import javax.management.MBeanServer; -import javax.management.ObjectName; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; -import brooklyn.util.text.Identifiers; -import brooklyn.util.time.Time; - -import com.google.common.base.Stopwatch; -import com.google.common.collect.ImmutableList; - -/** - * Test the performance of different variants of invoking the sshj tool. - * - * Intended for human-invocation and inspection, to see which parts are most expensive. - */ -public abstract class SshToolAbstractPerformanceTest { - - private static final Logger LOG = LoggerFactory.getLogger(SshToolAbstractPerformanceTest.class); - - private SshTool tool; - - protected abstract SshTool newSshTool(Map<String,?> flags); - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (tool != null) tool.disconnect(); - } - - @Test(groups = {"Integration"}) - public void testConsecutiveConnectAndDisconnect() throws Exception { - Runnable task = new Runnable() { - public void run() { - tool = newSshTool(MutableMap.of("host", "localhost")); - tool.connect(); - tool.disconnect(); - } - }; - runMany(task, "connect-disconnect", 10); - } - - @Test(groups = {"Integration"}) - public void testConsecutiveSmallCommands() throws Exception { - runExecManyCommands(ImmutableList.of("true"), false, "small-cmd", 10); - } - - @Test(groups = {"Integration"}) - public void testConsecutiveSmallCommandsWithStdouterr() throws Exception { - runExecManyCommands(ImmutableList.of("true"), true, "small-cmd-with-stdout", 10); - } - - @Test(groups = {"Integration"}) - public void testConsecutiveBigStdoutCommands() throws Exception { - runExecManyCommands(ImmutableList.of("head -c 100000 /dev/urandom"), true, "big-stdout", 10); - } - - @Test(groups = {"Integration"}) - public void testConsecutiveBigStdinCommands() throws Exception { - String bigstr = Identifiers.makeRandomId(100000); - runExecManyCommands(ImmutableList.of("echo "+bigstr+" | wc -c"), true, "big-stdin", 10); - } - - private void runExecManyCommands(final List<String> cmds, final boolean captureOutAndErr, String context, int iterations) throws Exception { - Runnable task = new Runnable() { - @Override public void run() { - execScript(cmds, captureOutAndErr); - }}; - runMany(task, context, iterations); - } - - private void runMany(Runnable task, String context, int iterations) throws Exception { - MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); - ObjectName osMBeanName = ObjectName.getInstance(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME); - long preCpuTime = (Long) mbeanServer.getAttribute(osMBeanName, "ProcessCpuTime"); - Stopwatch stopwatch = Stopwatch.createStarted(); - - for (int i = 0; i < iterations; i++) { - task.run(); - - long postCpuTime = (Long) mbeanServer.getAttribute(osMBeanName, "ProcessCpuTime"); - long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS); - double fractionCpu = (elapsedTime > 0) ? ((double)postCpuTime-preCpuTime) / TimeUnit.MILLISECONDS.toNanos(elapsedTime) : -1; - LOG.info("Executing {}; completed {}; took {}; fraction cpu {}", new Object[] {context, (i+1), Time.makeTimeStringRounded(elapsedTime), fractionCpu}); - } - } - - private int execScript(List<String> cmds, boolean captureOutandErr) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - MutableMap<String,?> flags = (captureOutandErr) ? MutableMap.of("out", out, "err", err) : MutableMap.<String,Object>of(); - - tool = newSshTool(MutableMap.of("host", "localhost")); - tool.connect(); - int result = tool.execScript(flags, cmds); - tool.disconnect(); - - int outlen = out.toByteArray().length; - int errlen = out.toByteArray().length; - if (LOG.isTraceEnabled()) LOG.trace("Executed: result={}; stdout={}; stderr={}", new Object[] {result, outlen, errlen}); - return result; - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolIntegrationTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolIntegrationTest.java b/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolIntegrationTest.java deleted file mode 100644 index c8640e7..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolIntegrationTest.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.internal.ssh.cli; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; -import brooklyn.util.internal.ssh.SshException; -import brooklyn.util.internal.ssh.SshTool; -import brooklyn.util.internal.ssh.SshToolAbstractIntegrationTest; -import brooklyn.util.internal.ssh.cli.SshCliTool; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Test the operation of the {@link SshJschTool} utility class. - */ -public class SshCliToolIntegrationTest extends SshToolAbstractIntegrationTest { - - private static final Logger log = LoggerFactory.getLogger(SshCliToolIntegrationTest.class); - - protected SshTool newUnregisteredTool(Map<String,?> flags) { - return new SshCliTool(flags); - } - - @Test(groups = {"Integration"}) - public void testFlags() throws Exception { - final SshTool localtool = newTool(ImmutableMap.of("sshFlags", "-vvv -tt", "host", "localhost")); - tools.add(localtool); - try { - localtool.connect(); - Map<String,Object> props = new LinkedHashMap<String, Object>(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - props.put("out", out); - props.put("err", err); - int exitcode = localtool.execScript(props, Arrays.asList("echo hello err > /dev/stderr"), null); - Assert.assertEquals(0, exitcode, "exitCode="+exitcode+", but expected 0"); - log.debug("OUT from ssh -vvv command is: "+out); - log.debug("ERR from ssh -vvv command is: "+err); - assertFalse(err.toString().contains("hello err"), "hello found where it shouldn't have been, in stderr (should have been tty merged to stdout): "+err); - assertTrue(out.toString().contains("hello err"), "no hello in stdout: "+err); - // look for word 'ssh' to confirm we got verbose output - assertTrue(err.toString().toLowerCase().contains("ssh"), "no mention of ssh in stderr: "+err); - } catch (SshException e) { - if (!e.toString().contains("failed to connect")) throw e; - } - } - - // Need to have at least one test method here (rather than just inherited) for eclipse to recognize it - @Test(enabled = false) - public void testDummy() throws Exception { - } - - // TODO When running mvn on the command line (for Aled), this test hangs when prompting for a password (but works in the IDE!) - // Doing .connect() isn't enough; need to cause ssh or scp to be invoked - @Test(enabled=false, groups = {"Integration"}) - public void testConnectWithInvalidUserThrowsException() throws Exception { - final SshTool localtool = newTool(ImmutableMap.of("user", "wronguser", "host", "localhost", "privateKeyFile", "~/.ssh/id_rsa")); - tools.add(localtool); - try { - localtool.connect(); - int result = localtool.execScript(ImmutableMap.<String,Object>of(), ImmutableList.of("date")); - fail("exitCode="+result+", but expected exception"); - } catch (SshException e) { - if (!e.toString().contains("failed to connect")) throw e; - } - } - - // TODO ssh-cli doesn't support pass-phrases yet - @Test(enabled=false, groups = {"Integration"}) - public void testSshKeyWithPassphrase() throws Exception { - super.testSshKeyWithPassphrase(); - } - - // Setting last modified date not yet supported for cli-based ssh - @Override - @Test(enabled=false, groups = {"Integration"}) - public void testCopyToServerWithLastModifiedDate() throws Exception { - super.testCopyToServerWithLastModifiedDate(); - } - - @Test(groups = {"Integration"}) - public void testExecReturningNonZeroExitCode() throws Exception { - int exitcode = tool.execCommands(MutableMap.<String,Object>of(), ImmutableList.of("exit 123")); - assertEquals(exitcode, 123); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolPerformanceTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolPerformanceTest.java b/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolPerformanceTest.java deleted file mode 100644 index 4d2ba20..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/cli/SshCliToolPerformanceTest.java +++ /dev/null @@ -1,44 +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.ssh.cli; - -import java.util.Map; - -import org.testng.annotations.Test; - -import brooklyn.util.internal.ssh.SshTool; -import brooklyn.util.internal.ssh.SshToolAbstractPerformanceTest; - -/** - * Test the performance of different variants of invoking the sshj tool. - * - * Intended for human-invocation and inspection, to see which parts are most expensive. - */ -public class SshCliToolPerformanceTest extends SshToolAbstractPerformanceTest { - - @Override - protected SshTool newSshTool(Map<String,?> flags) { - return new SshCliTool(flags); - } - - // Need to have at least one test method here (rather than just inherited) for eclipse to recognize it - @Test(enabled = false) - public void testDummy() throws Exception { - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolIntegrationTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolIntegrationTest.java b/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolIntegrationTest.java deleted file mode 100644 index 64054ba..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolIntegrationTest.java +++ /dev/null @@ -1,69 +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.ssh.process; - -import static org.testng.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Map; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import brooklyn.util.config.ConfigBag; -import brooklyn.util.internal.ssh.ShellToolAbstractTest; - -/** - * Test the operation of the {@link ProcessTool} utility class. - */ -public class ProcessToolIntegrationTest extends ShellToolAbstractTest { - - @Override - protected ProcessTool newUnregisteredTool(Map<String,?> flags) { - return new ProcessTool(flags); - } - - // ones here included as *non*-integration tests. must run on windows and linux. - // (also includes integration tests from parent) - - @Test(groups="UNIX") - public void testPortableCommand() throws Exception { - String out = execScript("echo hello world"); - assertTrue(out.contains("hello world"), "out="+out); - } - - @Test(groups="Integration") - public void testLoginShell() { - // this detection scheme only works for commands; can't test whether it works for scripts without - // requiring stuff in bash_profile / profile / etc, which gets hard to make portable; - // it is nearly the same code path on the impl so this is probably enough - - final String LOGIN_SHELL_CHECK = "shopt -q login_shell && echo 'yes, login shell' || echo 'no, not login shell'"; - ConfigBag config = ConfigBag.newInstance().configure(ProcessTool.PROP_NO_EXTRA_OUTPUT, true); - String out; - - out = execCommands(config, Arrays.asList(LOGIN_SHELL_CHECK), null); - Assert.assertEquals(out.trim(), "no, not login shell", "out = "+out); - - config.configure(ProcessTool.PROP_LOGIN_SHELL, true); - out = execCommands(config, Arrays.asList(LOGIN_SHELL_CHECK), null); - Assert.assertEquals(out.trim(), "yes, login shell", "out = "+out); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a4c0e5fd/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolStaticsTest.java ---------------------------------------------------------------------- diff --git a/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolStaticsTest.java b/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolStaticsTest.java deleted file mode 100644 index 787c776..0000000 --- a/core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolStaticsTest.java +++ /dev/null @@ -1,79 +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.ssh.process; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.util.collections.MutableMap; -import brooklyn.util.os.Os; - -public class ProcessToolStaticsTest { - - ByteArrayOutputStream out; - ByteArrayOutputStream err; - - @BeforeMethod(alwaysRun=true) - public void clear() { - out = new ByteArrayOutputStream(); - err = new ByteArrayOutputStream(); - } - - private List<String> getTestCommand() { - if(Os.isMicrosoftWindows()) { - return Arrays.asList("cmd", "/c", "echo", "hello", "world"); - } else { - return Arrays.asList("echo", "hello", "world"); - } - } - - @Test - public void testRunsWithStdout() throws Exception { - int code = ProcessTool.execSingleProcess(getTestCommand(), null, (File)null, out, err, this); - Assert.assertEquals(err.toString().trim(), ""); - Assert.assertEquals(out.toString().trim(), "hello world"); - Assert.assertEquals(code, 0); - } - - @Test(groups="Integration") // *nix only - public void testRunsWithBashEnvVarAndStderr() throws Exception { - int code = ProcessTool.execSingleProcess(Arrays.asList("/bin/bash", "-c", "echo hello $NAME | tee /dev/stderr"), - MutableMap.of("NAME", "BOB"), (File)null, out, err, this); - Assert.assertEquals(err.toString().trim(), "hello BOB", "err is: "+err); - Assert.assertEquals(out.toString().trim(), "hello BOB", "out is: "+out); - Assert.assertEquals(code, 0); - } - - @Test(groups="Integration") // *nix only - public void testRunsManyCommandsWithBashEnvVarAndStderr() throws Exception { - int code = ProcessTool.execProcesses(Arrays.asList("echo hello $NAME", "export NAME=JOHN", "echo goodbye $NAME | tee /dev/stderr"), - MutableMap.of("NAME", "BOB"), (File)null, out, err, " ; ", false, this); - Assert.assertEquals(err.toString().trim(), "goodbye JOHN", "err is: "+err); - Assert.assertEquals(out.toString().trim(), "hello BOB\ngoodbye JOHN", "out is: "+out); - Assert.assertEquals(code, 0); - } - - -}
