http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/base/CommandsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/base/CommandsTest.java b/commons/src/test/java/com/twitter/common/base/CommandsTest.java new file mode 100644 index 0000000..da64b6d --- /dev/null +++ b/commons/src/test/java/com/twitter/common/base/CommandsTest.java @@ -0,0 +1,87 @@ +// ================================================================================================= +// Copyright 2013 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.base; + +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; + +import com.twitter.common.testing.easymock.EasyMockTest; + +import static org.easymock.EasyMock.expectLastCall; +import static org.junit.Assert.assertNull; + +public class CommandsTest extends EasyMockTest { + private Command c1; + private Command c2; + private Command c3; + + @Before + public void mySetup() { + c1 = createMock(new Clazz<Command>() { }); + c2 = createMock(new Clazz<Command>() { }); + c3 = createMock(new Clazz<Command>() { }); + } + + @Test + public void testAsSupplier() { + c1.execute(); + + control.replay(); + + assertNull(Commands.asSupplier(c1).get()); + } + + @Test(expected = NullPointerException.class) + public void testAsSupplierPreconditions() { + control.replay(); + + Commands.asSupplier(null); + } + + @Test + public void testCompoundCommand() { + c1.execute(); + c2.execute(); + c3.execute(); + + control.replay(); + + Commands.compound(Arrays.asList(c1, c2, c3)).execute(); + } + + @Test(expected = NullPointerException.class) + public void testCompoundCommandPreconditions() { + control.replay(); + + Commands.compound(Arrays.asList(c1, null, c2)); + } + + @Test(expected = RuntimeException.class) + public void testRuntimeException() { + Command badCommand = createMock(new Clazz<Command>() { }); + + c1.execute(); + badCommand.execute(); + expectLastCall().andThrow(new RuntimeException("Cannot Run")); + + control.replay(); + + Commands.compound(Arrays.asList(c1, badCommand, c2)).execute(); + } +}
http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/base/EitherTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/base/EitherTest.java b/commons/src/test/java/com/twitter/common/base/EitherTest.java new file mode 100644 index 0000000..432b7b8 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/base/EitherTest.java @@ -0,0 +1,253 @@ +package com.twitter.common.base; + +import java.io.IOException; +import java.net.MalformedURLException; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; + +import org.junit.Test; + +import com.twitter.common.base.Either.Transformer; +import com.twitter.common.base.Either.UnguardedException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EitherTest { + + @Test + public void testLeft() { + Exception left = new Exception(); + assertLeft(left, Either.<Exception, String>left(left)); + } + + @Test + public void testRight() { + assertRight("jake", Either.<Exception, String>right("jake")); + } + + @Test + public void testSwap() { + assertLeft("jake", Either.right("jake").swap()); + assertRight("jake", Either.left("jake").swap()); + + Either<String, Object> left = Either.left("jake"); + assertEquals(left, left.swap().swap()); + + Either<Object, String> right = Either.right("jake"); + assertEquals(right, right.swap().swap()); + } + + public static final Function<CharSequence, Integer> LENGTH = + new Function<CharSequence, Integer>() { + @Override public Integer apply(CharSequence item) { + return item.length(); + } + }; + + public static final Function<Object, Integer> HASHCODE = new Function<Object, Integer>() { + @Override public Integer apply(Object item) { + return item.hashCode(); + } + }; + + @Test + public void testMapLeft() { + RuntimeException left = new RuntimeException() { + @Override public int hashCode() { + return 42; + } + }; + assertLeft(42, Either.left(left).mapLeft(HASHCODE)); + + assertRight("jake", Either.right("jake").mapLeft(HASHCODE)); + } + + @Test + public void testMapRight() { + assertRight(4, Either.right("jake").mapRight(LENGTH)); + + RuntimeException left = new RuntimeException(); + assertLeft(left, Either.left(left).mapRight(HASHCODE)); + } + + @Test + public void testMap() { + Transformer<Object, CharSequence, Integer> transformer = Either.transformer(HASHCODE, LENGTH); + + Object left = new Object() { + @Override public int hashCode() { + return 1137; + } + }; + Either<Object, CharSequence> either = Either.left(left); + assertEquals(1137, either.map(transformer).intValue()); + + assertEquals(19, Either.right("The Meaning of Life").map(transformer).intValue()); + } + + private static final ImmutableList<Either<String, String>> LEFT_RESULTS = + ImmutableList.of( + Either.<String, String>left("jack"), + Either.<String, String>left("jill")); + + private static final ImmutableList<Either<String, String>> RIGHT_RESULTS = + ImmutableList.of( + Either.<String, String>right("jack"), + Either.<String, String>right("jill")); + + private static final ImmutableList<Either<String, String>> MIXED_RESULTS = + ImmutableList.of( + Either.<String, String>left("jack"), + Either.<String, String>right("jane"), + Either.<String, String>left("jill")); + + @Test + public void testLefts() { + assertEquals(ImmutableList.of("jack", "jill"), + ImmutableList.copyOf(Either.lefts(LEFT_RESULTS))); + assertEquals(ImmutableList.of(), ImmutableList.copyOf(Either.lefts(RIGHT_RESULTS))); + assertEquals(ImmutableList.of("jack", "jill"), + ImmutableList.copyOf(Either.lefts(MIXED_RESULTS))); + } + + @Test + public void testRights() { + assertEquals(ImmutableList.of(), ImmutableList.copyOf(Either.rights(LEFT_RESULTS))); + assertEquals(ImmutableList.of("jack", "jill"), + ImmutableList.copyOf(Either.rights(RIGHT_RESULTS))); + assertEquals(ImmutableList.of("jane"), ImmutableList.copyOf(Either.rights(MIXED_RESULTS))); + } + + @Test + public void testTransformer() { + assertEquals(ImmutableList.of("jackjack", "4", "jilljill"), + ImmutableList.copyOf(Iterables.transform(MIXED_RESULTS, + new Transformer<String, String, String>() { + @Override public String mapLeft(String left) { + return left + left; + } + @Override public String mapRight(String right) { + return String.valueOf(right.length()); + } + }))); + } + + static <T, X extends Exception> ExceptionalSupplier<T, X> constantSupplier(final T value) { + return new ExceptionalSupplier<T, X>() { + @Override public T get() { + return value; + } + }; + } + + static <T, X extends Exception> ExceptionalSupplier<T, X> failedSupplier(final X failure) { + return new ExceptionalSupplier<T, X>() { + @Override public T get() throws X { + throw failure; + } + }; + } + + @Test + public void testGuard() { + assertRight("jake", + Either.guard(IOException.class, EitherTest.<String, IOException>constantSupplier("jake"))); + + IOException left = new IOException(); + assertLeft(left, Either.guard(IOException.class, failedSupplier(left))); + + try { + Either.guard(IOException.class, new ExceptionalSupplier<Object, IOException>() { + @Override public String get() { + throw new ArithmeticException(); + } + }); + fail("Expected an unguarded exception type to fail fast."); + } catch (UnguardedException e) { + assertTrue(e.getCause() instanceof ArithmeticException); + } + + Either<Exception, String> result = + Either.guard(ImmutableList.of(IOException.class, InterruptedException.class), + new SupplierE<String>() { + @Override public String get() throws InterruptedException { + throw new InterruptedException(); + } + }); + assertTrue(result.getLeft() instanceof InterruptedException); + + result = Either.guard(ImmutableList.of(IOException.class, InterruptedException.class), + new SupplierE<String>() { + @Override public String get() throws IOException { + throw new MalformedURLException(); + } + }); + assertTrue(result.getLeft() instanceof IOException); + + class MyException extends Exception { } + try { + Either.guard(ImmutableList.of(IOException.class, InterruptedException.class), + new SupplierE<String>() { + @Override public String get() throws Exception { + throw new MyException(); + } + }); + fail("Expected an unguarded exception type to fail fast."); + } catch (UnguardedException e) { + assertTrue(e.getCause() instanceof MyException); + } + } + + private static <L, R> void assertLeft(L left, Either<L, R> either) { + assertEquals(Either.left(left), either); + + assertTrue(either.isLeft()); + assertTrue(either.left().isPresent()); + assertSame(left, either.getLeft()); + assertSame(left, either.left().get()); + + assertFalse(either.isRight()); + assertFalse(either.right().isPresent()); + try { + either.getRight(); + fail("Expected a a left to throw when accessing its right."); + } catch (IllegalStateException e) { + // expected + } + try { + either.right().get(); + fail("Expected a a left to throw when accessing its right."); + } catch (IllegalStateException e) { + // expected + } + } + + private static <L, R> void assertRight(R right, Either<L, R> either) { + assertEquals(Either.right(right), either); + + assertTrue(either.isRight()); + assertTrue(either.right().isPresent()); + assertSame(right, either.getRight()); + assertSame(right, either.right().get()); + + assertFalse(either.isLeft()); + assertFalse(either.left().isPresent()); + try { + either.getLeft(); + fail("Expected a a right to throw when accessing its left."); + } catch (IllegalStateException e) { + // expected + } + try { + either.left().get(); + fail("Expected a a right to throw when accessing its left."); + } catch (IllegalStateException e) { + // expected + } + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/base/ExceptionTransporterTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/base/ExceptionTransporterTest.java b/commons/src/test/java/com/twitter/common/base/ExceptionTransporterTest.java new file mode 100644 index 0000000..bc86c4f --- /dev/null +++ b/commons/src/test/java/com/twitter/common/base/ExceptionTransporterTest.java @@ -0,0 +1,60 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.base; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.SocketException; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author John Sirois + */ +public class ExceptionTransporterTest { + + @Test(expected = FileNotFoundException.class) + public void testCheckedTransport() throws FileNotFoundException { + ExceptionTransporter.guard(new Function<ExceptionTransporter<FileNotFoundException>, File>() { + @Override public File apply(ExceptionTransporter<FileNotFoundException> transporter) { + throw transporter.transport(new FileNotFoundException()); + } + }); + } + + @Test(expected = IllegalStateException.class) + public void testUncheckedTransport() throws SocketException { + ExceptionTransporter.guard(new Function<ExceptionTransporter<SocketException>, File>() { + @Override public File apply(ExceptionTransporter<SocketException> transporter) { + throw new IllegalStateException(); + } + }); + } + + @Test + public void testNoTransport() throws IOException { + assertEquals("jake", ExceptionTransporter.guard( + new Function<ExceptionTransporter<IOException>, String>() { + @Override public String apply(ExceptionTransporter<IOException> exceptionTransporter) { + return "jake"; + } + })); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/base/ExceptionalFunctionsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/base/ExceptionalFunctionsTest.java b/commons/src/test/java/com/twitter/common/base/ExceptionalFunctionsTest.java new file mode 100644 index 0000000..bf8c685 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/base/ExceptionalFunctionsTest.java @@ -0,0 +1,169 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.base; + +import java.io.IOException; + +import org.easymock.EasyMock; +import org.easymock.IMocksControl; +import org.junit.Before; +import org.junit.Test; + +import static org.easymock.EasyMock.expect; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +/** + * @author John Sirois + */ +public class ExceptionalFunctionsTest { + + private static final String STRING = "jake"; + private ExceptionalFunction<String, Integer, NumberFormatException> stringToInt = + new ExceptionalFunction<String, Integer, NumberFormatException>() { + @Override + public Integer apply(String item) throws NumberFormatException { + return Integer.parseInt(item); + } + }; + private ExceptionalFunction<Integer, Double, Exception> intToDouble = + new ExceptionalFunction<Integer, Double, Exception>() { + @Override + public Double apply(Integer item) throws NumberFormatException { + return item.doubleValue(); + } + }; + private IMocksControl control; + private ExceptionalFunction<String, Integer, IOException> function; + + @Before + public void setUp() throws Exception { + control = EasyMock.createControl(); + + @SuppressWarnings("unchecked") + ExceptionalFunction<String, Integer, IOException> f = + control.createMock(ExceptionalFunction.class); + this.function = f; + } + + @Test + public void testCurryLazy() throws IOException { + control.replay(); + + ExceptionalFunctions.curry(function, STRING); + + control.verify(); + } + + @Test + public void testCurryExecution() throws IOException { + expect(function.apply(STRING)).andReturn(1); + expect(function.apply(STRING)).andReturn(2); + + control.replay(); + + CallableExceptionalSupplier<Integer, IOException> supplier = + ExceptionalFunctions.curry(function, STRING); + + assertEquals("curried function should be called", Integer.valueOf(1), supplier.get()); + assertEquals("curried function should not be memoized", Integer.valueOf(2), supplier.get()); + + control.verify(); + } + + @Test + public void testCurryException() throws IOException { + IOException ioException = new IOException(); + expect(function.apply(STRING)).andThrow(ioException); + + RuntimeException runtimeException = new IllegalStateException(); + expect(function.apply(STRING)).andThrow(runtimeException); + + control.replay(); + + CallableExceptionalSupplier<Integer, IOException> supplier = + ExceptionalFunctions.curry(function, STRING); + + try { + supplier.get(); + } catch (IOException e) { + assertSame("Expected exception propagation to be transparent", ioException, e); + } + + try { + supplier.get(); + } catch (IllegalStateException e) { + assertSame("Expected exception propagation to be transparent", runtimeException, e); + } + + control.verify(); + } + + @Test + public void testCompose() throws Exception { + ExceptionalFunction<String, Double, Exception> stringToDouble = + ExceptionalFunctions.compose(intToDouble, stringToInt); + assertEquals(new Double(2d), stringToDouble.apply("2")); + assertEquals(new Double(-1d), stringToDouble.apply("-1")); + } + + @Test(expected = NumberFormatException.class) + public void testComposeWithException() throws Exception { + ExceptionalFunction<String, Double, Exception> stringToDouble = + ExceptionalFunctions.compose(intToDouble, stringToInt); + stringToDouble.apply("1.1"); + } + + @Test + public void testForFunction() { + com.google.common.base.Function<String, Integer> stringToIntegerGuavaFunction = + new com.google.common.base.Function<String, Integer>() { + @Override + public Integer apply(String item) { + return Integer.parseInt(item); + } + }; + ExceptionalFunction<String, Integer, NumberFormatException> stringToIntegerExceptionalFunction = + ExceptionalFunctions.forFunction(stringToIntegerGuavaFunction); + assertEquals( + stringToIntegerGuavaFunction.apply("1234"), + stringToIntegerExceptionalFunction.apply("1234")); + } + + @Test + public void testConstantReturn() { + final String value = "taxes?"; + ExceptionalFunction<String, String, IllegalArgumentException> constant = + ExceptionalFunctions.constant(value); + assertEquals(value, constant.apply("yes")); + } + + @Test(expected = IllegalArgumentException.class) + public void testConstantException() { + ExceptionalFunction<String, String, IllegalArgumentException> badness = + ExceptionalFunctions.forException(new IllegalArgumentException()); + badness.apply("pleaseno"); + } + + @Test + public void testConstantExceptionReturn() { + final Exception value = new Exception("corner case?"); + ExceptionalFunction<String, Exception, IllegalArgumentException> constant = + ExceptionalFunctions.constant(value); + assertEquals(value, constant.apply("yes")); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/base/MorePreconditionsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/base/MorePreconditionsTest.java b/commons/src/test/java/com/twitter/common/base/MorePreconditionsTest.java new file mode 100644 index 0000000..a3da99a --- /dev/null +++ b/commons/src/test/java/com/twitter/common/base/MorePreconditionsTest.java @@ -0,0 +1,103 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.base; + +import com.google.common.collect.ImmutableList; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +/** + * @author John Sirois + */ +public class MorePreconditionsTest { + + @Test(expected = NullPointerException.class) + public void testCheckNotBlankStringNull() { + MorePreconditions.checkNotBlank((String) null); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotBlankStringEmpty() { + MorePreconditions.checkNotBlank(""); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotBlankSpaces() { + MorePreconditions.checkNotBlank(" "); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotBlankWhitespace() { + MorePreconditions.checkNotBlank("\t\r\n "); + } + + @Test + public void testCheckNotBlankStringValid() { + String argument = new String("foo"); + assertSame(argument, MorePreconditions.checkNotBlank(argument)); + } + + @Test + public void testCheckNotBlankStringExceptionFormatting() { + try { + MorePreconditions.checkNotBlank((String) null, "the meaning of life is %s", 42); + } catch (NullPointerException e) { + assertEquals("the meaning of life is 42", e.getMessage()); + } + + try { + MorePreconditions.checkNotBlank("", "wing beats per second is %s", 43); + } catch (IllegalArgumentException e) { + assertEquals("wing beats per second is 43", e.getMessage()); + } + } + + @Test(expected = NullPointerException.class) + public void testCheckNotBlankIterableNull() { + MorePreconditions.checkNotBlank((Iterable<?>) null); + } + + @Test(expected = IllegalArgumentException.class) + public void testCheckNotBlankIterableEmpty() { + MorePreconditions.checkNotBlank(ImmutableList.<Object>of()); + } + + @Test + public void testCheckNotBlankIterableValid() { + ImmutableList<String> argument = ImmutableList.of(""); + ImmutableList<String> result = MorePreconditions.checkNotBlank(argument); + assertSame(argument, result); + } + + @Test + public void testCheckNotBlankIterableExceptionFormatting() { + try { + MorePreconditions.checkNotBlank((Iterable<?>) null, "the meaning of life is %s", 42); + } catch (NullPointerException e) { + assertEquals("the meaning of life is 42", e.getMessage()); + } + + try { + MorePreconditions.checkNotBlank(ImmutableList.of(), "wing beats per second is %s", 43); + } catch (IllegalArgumentException e) { + assertEquals("wing beats per second is 43", e.getMessage()); + } + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/base/MoreSuppliersTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/base/MoreSuppliersTest.java b/commons/src/test/java/com/twitter/common/base/MoreSuppliersTest.java new file mode 100644 index 0000000..2379624 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/base/MoreSuppliersTest.java @@ -0,0 +1,110 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.base; + +import com.google.common.base.Preconditions; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +/** + * @author John Sirois + */ +public class MoreSuppliersTest { + private static final class PrivateClassPublicConstructor { + public PrivateClassPublicConstructor() { } + } + + private static final class PrivateClassPrivateConstructor { + private PrivateClassPrivateConstructor() { } + } + + public static final class PublicClassPublicConstructor { + public PublicClassPublicConstructor() { } + } + + public static final class PublicClassPrivateConstructor { + private PublicClassPrivateConstructor() { } + } + + @Test + public void testOfVisibilitiesHandled() throws Exception { + testOfForType(PrivateClassPublicConstructor.class); + testOfForType(PrivateClassPrivateConstructor.class); + testOfForType(PublicClassPublicConstructor.class); + testOfForType(PublicClassPrivateConstructor.class); + } + + private void testOfForType(Class<?> type) { + Supplier<Object> supplier = MoreSuppliers.of(type); + Object object = supplier.get(); + assertNotNull(object); + assertNotSame(object, supplier.get()); + } + + static class NoNoArgConstructor { + NoNoArgConstructor(String unused) { } + } + + @Test(expected = NullPointerException.class) + public void testNullArgumentRejected() { + MoreSuppliers.of(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testNoNoArgFailsFast() { + MoreSuppliers.of(NoNoArgConstructor.class); + } + + @Test + public void testOfInstance() { + class ValueEquals { + private final String value; + + ValueEquals(String value) { + this.value = Preconditions.checkNotNull(value); + } + + @Override + public boolean equals(Object o) { + return value.equals(((ValueEquals) o).value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + } + + Supplier<ValueEquals> nullSupplier = MoreSuppliers.ofInstance(new ValueEquals("jake")); + ValueEquals actual = nullSupplier.get(); + assertEquals(new ValueEquals("jake"), actual); + assertSame(actual, nullSupplier.get()); + } + + @Test + public void testOfInstanceNullable() { + Supplier<String> nullSupplier = MoreSuppliers.ofInstance(null); + assertNull(nullSupplier.get()); + assertNull(nullSupplier.get()); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/collections/BitsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/collections/BitsTest.java b/commons/src/test/java/com/twitter/common/collections/BitsTest.java new file mode 100644 index 0000000..1a41acd --- /dev/null +++ b/commons/src/test/java/com/twitter/common/collections/BitsTest.java @@ -0,0 +1,302 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.collections; + + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +/** + * @author William Farner + */ +public class BitsTest { + + private static final List<Long> BASIC_LONGS = Arrays.asList( + 0x0000000000000000L, + 0x00000000FFFFFFFFL, + 0xFFFFFFFF00000000L, + 0xFFFFFFFFFFFFFFFFL + ); + + private static final List<Long> SINGLE_BIT_LONGS = Arrays.asList( + 0x0000000000000001L, + 0x0000000000000002L, + 0x0000000000000004L, + 0x0000000000000008L, + 0x0000000000000010L, + 0x0000000000000020L, + 0x0000000000000040L, + 0x0000000000000080L, + 0x0000000000000100L, + 0x0000000000000200L, + 0x0000000000000400L, + 0x0000000000000800L, + 0x0000000000001000L, + 0x0000000000002000L, + 0x0000000000004000L, + 0x0000000000008000L, + 0x0000000000010000L, + 0x0000000000020000L, + 0x0000000000040000L, + 0x0000000000080000L, + 0x0000000000100000L, + 0x0000000000200000L, + 0x0000000000400000L, + 0x0000000000800000L, + 0x0000000001000000L, + 0x0000000002000000L, + 0x0000000004000000L, + 0x0000000008000000L, + 0x0000000010000000L, + 0x0000000020000000L, + 0x0000000040000000L, + 0x0000000080000000L, + 0x0000000100000000L, + 0x0000000200000000L, + 0x0000000400000000L, + 0x0000000800000000L, + 0x0000001000000000L, + 0x0000002000000000L, + 0x0000004000000000L, + 0x0000008000000000L, + 0x0000010000000000L, + 0x0000020000000000L, + 0x0000040000000000L, + 0x0000080000000000L, + 0x0000100000000000L, + 0x0000200000000000L, + 0x0000400000000000L, + 0x0000800000000000L, + 0x0001000000000000L, + 0x0002000000000000L, + 0x0004000000000000L, + 0x0008000000000000L, + 0x0010000000000000L, + 0x0020000000000000L, + 0x0040000000000000L, + 0x0080000000000000L, + 0x0100000000000000L, + 0x0200000000000000L, + 0x0400000000000000L, + 0x0800000000000000L, + 0x1000000000000000L, + 0x2000000000000000L, + 0x4000000000000000L, + 0x8000000000000000L + ); + + private static final List<Long> RANDOM_LONGS = Arrays.asList( + 0x88BA910280684BFAL, + 0xAD4376223ACCDA29L, + 0xE5992FBC3D222B2BL, + 0x93385280AC0EE09CL, + 0x7BFCB384F2B88BD1L, + 0xABD0E19C726DC54EL, + 0xA0C0A9D1C38073E1L, + 0x957A232B46A01071L, + 0x04CCBDFE1F714EB4L, + 0xACDC6DACDF25C070L, + 0xCE9AC78F31BA17FAL, + 0xEAE5F04361A46FFFL, + 0x1B18F8BE5089C1EDL, + 0xD8E0EED9F397496DL, + 0xD6A1F134843B4AC9L, + 0x186F1C907FBA5B3CL, + 0x8A1CB91A7929357AL, + 0xB6F5B84FFBFE21F3L, + 0xD8F2E84C73735997L, + 0xFE9C4FBDAB495B31L, + 0x92AB7DEB113D3E8FL, + 0x5CBA4C59FC1C7605L, + 0xBADD2C1E2D9A7621L, + 0x54ADAEDF528B347DL, + 0x1C131C0F1FC1AA11L, + 0x00D79CEBA636527CL, + 0x7A6B6E39E6765118L, + 0xF021A4E5DD3845D0L, + 0x6966FAE6CA243F1BL, + 0xF738DC1B00956B83L, + 0x09D616F4502784A0L, + 0xEFDA3B2B2EF13671L + ); + + private static final List<Integer> BASIC_INTS = Arrays.asList( + 0x00000000, + 0xFFFFFFFF + ); + + private static final List<Integer> SINGLE_BIT_INTS = Arrays.asList( + 0x00000001, + 0x00000002, + 0x00000004, + 0x00000008, + 0x00000010, + 0x00000020, + 0x00000040, + 0x00000080, + 0x00000100, + 0x00000200, + 0x00000400, + 0x00000800, + 0x00001000, + 0x00002000, + 0x00004000, + 0x00008000, + 0x00010000, + 0x00020000, + 0x00040000, + 0x00080000, + 0x00100000, + 0x00200000, + 0x00400000, + 0x00800000, + 0x01000000, + 0x02000000, + 0x04000000, + 0x08000000, + 0x10000000, + 0x20000000, + 0x40000000, + 0x80000000 + ); + + private static final List<Integer> RANDOM_INTS = Arrays.asList( + 0x124FE3D6, + 0xA688379A, + 0xB49EC20C, + 0x0C2C8D99, + 0x32D1E1BB, + 0xCF7169FF, + 0x94D7D596, + 0xE3A962CD, + 0xA47FA154, + 0x20DB4BA5, + 0x27FA77BC, + 0x2DCEDF0D, + 0xC05ACE5A, + 0x4C871D86, + 0x29B4D423, + 0xFCB5EC65, + 0x1CAD4057, + 0x2EC8E1C8, + 0x251D315A, + 0x6D6C6021, + 0x3F58FF67, + 0xFB917B2E, + 0x51338D3E, + 0xE1D6695B, + 0x149D5142, + 0x51B6CFD1, + 0xABB61BA0, + 0x4E1FD4D4, + 0x0AB11279, + 0xEA8EE310, + 0x9C6C8B24, + 0x99DD3A07 + ); + + @SuppressWarnings("unchecked") //Needed because type information lost in vargs. + private static final List<List<Long>> LONGS_TEST_LISTS = Arrays.asList( + BASIC_LONGS, + SINGLE_BIT_LONGS, + RANDOM_LONGS + ); + + @SuppressWarnings("unchecked") //Needed because type information lost in vargs. + private static final List<List<Integer>> INTS_TEST_LISTS = Arrays.asList( + BASIC_INTS, + SINGLE_BIT_INTS, + RANDOM_INTS + ); + + @Test + public void testSetAndGetSingleLongBits() { + for (List<Long> testList : LONGS_TEST_LISTS) { + for (long testValue : testList) { + for (int i = 0; i < 64; ++i) { + long setOneBit = Bits.setBit(testValue, i); + assertTrue(Bits.isBitSet(setOneBit, i)); + assertEquals(Bits.clearBit(testValue, i), Bits.clearBit(setOneBit, i)); + assertTrue(!Bits.isBitSet(Bits.clearBit(setOneBit, i), i)); + } + } + } + } + + @Test + public void testAllLongBits() { + for (List<Long> testList : LONGS_TEST_LISTS) { + for (long testValue : testList) { + long inverseValue1 = 0; + long inverseValue2 = 0xFFFFFFFFFFFFFFFFL; + for (int i = 0; i < 64; ++i) { + if (!Bits.isBitSet(testValue, i)) { + inverseValue1 = Bits.setBit(inverseValue1, i); + } else { + inverseValue2 = Bits.clearBit(inverseValue2, i); + } + } + assertThat(0xFFFFFFFFFFFFFFFFL, is(inverseValue1 | testValue)); + assertThat(0xFFFFFFFFFFFFFFFFL, is(inverseValue2 | testValue)); + assertThat(0xFFFFFFFFFFFFFFFFL, is(inverseValue1 ^ testValue)); + assertThat(0xFFFFFFFFFFFFFFFFL, is(inverseValue2 ^ testValue)); + } + } + } + + @Test + public void testSetAndGetSingleIntBits() { + for (List<Integer> testList : INTS_TEST_LISTS) { + for (int testValue : testList) { + for (int i = 0; i < 32; ++i) { + int setOneBit = Bits.setBit(testValue, i); + assertTrue(Bits.isBitSet(setOneBit, i)); + assertEquals(Bits.clearBit(testValue, i), Bits.clearBit(setOneBit, i)); + assertTrue(!Bits.isBitSet(Bits.clearBit(setOneBit, i), i)); + } + } + } + } + + @Test + public void testAllIntBits() { + for (List<Integer> testList : INTS_TEST_LISTS) { + for (int testValue : testList) { + int inverseValue1 = 0; + int inverseValue2 = 0xFFFFFFFF; + for (int i = 0; i < 32; ++i) { + if (!Bits.isBitSet(testValue, i)) { + inverseValue1 = Bits.setBit(inverseValue1, i); + } else { + inverseValue2 = Bits.clearBit(inverseValue2, i); + } + } + assertThat(0xFFFFFFFF, is(inverseValue1 | testValue)); + assertThat(0xFFFFFFFF, is(inverseValue2 | testValue)); + assertThat(0xFFFFFFFF, is(inverseValue1 ^ testValue)); + assertThat(0xFFFFFFFF, is(inverseValue2 ^ testValue)); + } + } + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/collections/BoundedQueueTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/collections/BoundedQueueTest.java b/commons/src/test/java/com/twitter/common/collections/BoundedQueueTest.java new file mode 100644 index 0000000..59bee4a --- /dev/null +++ b/commons/src/test/java/com/twitter/common/collections/BoundedQueueTest.java @@ -0,0 +1,60 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.collections; + +import java.util.Iterator; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +/** + * @author William Farner + */ +public class BoundedQueueTest { + + private static final int SIZE = 4; + + private BoundedQueue<Integer> queue; + + @Before + public void setUp() { + queue = new BoundedQueue<Integer>(SIZE); + } + + @Test + public void testEmpty() { + assertThat(queue.iterator().hasNext(), is(false)); + } + + @Test + public void testFIFO() { + queue.add(0); + queue.add(1); + queue.add(2); + queue.add(3); + queue.add(4); + + Iterator<Integer> it = queue.iterator(); + assertThat(it.next(), is(1)); + assertThat(it.next(), is(2)); + assertThat(it.next(), is(3)); + assertThat(it.next(), is(4)); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/collections/Iterables2Test.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/collections/Iterables2Test.java b/commons/src/test/java/com/twitter/common/collections/Iterables2Test.java new file mode 100644 index 0000000..7b05ede --- /dev/null +++ b/commons/src/test/java/com/twitter/common/collections/Iterables2Test.java @@ -0,0 +1,110 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.collections; + +import java.util.Arrays; +import java.util.List; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +/** + * @author William Farner + */ +public class Iterables2Test { + + @Test + @SuppressWarnings("unchecked") // Needed because type information lost in vargs. + public void testZipSingleIterable() { + assertValues(Iterables2.zip(0, list(1, 2, 3, 4)), + list(1), + list(2), + list(3), + list(4) + ); + } + + @Test + @SuppressWarnings("unchecked") // Needed because type information lost in vargs. + public void testZipDefaultValue() { + assertValues(Iterables2.zip(10, list(1, 2, 3, 4), list(1)), + list(1, 1), + list(2, 10), + list(3, 10), + list(4, 10) + ); + } + + @Test + @SuppressWarnings("unchecked") // Needed because type information lost in vargs. + public void testZipNbyN() { + assertValues(Iterables2.zip(10, list(1, 2, 3, 4), list(5, 6, 7, 8)), + list(1, 5), + list(2, 6), + list(3, 7), + list(4, 8) + ); + } + + @Test + @SuppressWarnings("unchecked") // Needed because type information lost in vargs. + public void testZipEmptyIterable() { + assertValues(Iterables2.zip(10, list(1, 2, 3, 4), Arrays.<Integer>asList()), + list(1, 10), + list(2, 10), + list(3, 10), + list(4, 10) + ); + } + + @Test + @SuppressWarnings("unchecked") // Needed because type information lost in vargs. + public void testZipRemove() { + final int DEFAULT = 10; + Iterable<List<Integer>> meta = Iterables2.zip(DEFAULT, + list(1, 2, 3, 4), + list(5, 6, 7, 8), + list(9)); + + // Attempt to trim all rows that have the default value. + Iterables.removeIf(meta, new Predicate<List<Integer>>() { + @Override public boolean apply(List<Integer> input) { + return Iterables.contains(input, DEFAULT); + } + }); + + assertValues(meta, list(1, 5, 9)); + } + + private static List<Integer> list(Integer... ints) { + return Lists.newArrayList(ints); + } + + private static void assertValues(Iterable<List<Integer>> meta, List<Integer>... rows) { + assertThat(Iterables.size(meta), is(rows.length)); + int i = 0; + for (List<Integer> row : meta) { + assertThat(row, is(rows[i++])); + } + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/collections/PairTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/collections/PairTest.java b/commons/src/test/java/com/twitter/common/collections/PairTest.java new file mode 100644 index 0000000..e0b85fd --- /dev/null +++ b/commons/src/test/java/com/twitter/common/collections/PairTest.java @@ -0,0 +1,53 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.collections; + +import com.google.common.base.Function; +import com.google.common.base.Functions; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +/** + * @author John Sirois + */ +public class PairTest { + @Test + public void testSlots() { + assertEquals("jake", Pair.of("jake", null).getFirst()); + assertNull(Pair.of("jake", null).getSecond()); + assertNull(Pair.of(null, "jim").getFirst()); + assertEquals("jim", Pair.of(null, "jim").getSecond()); + } + + @Test + public void testValueEquals() { + assertEquals(new Pair<Integer, String>(1, "a"), Pair.of(1, "a")); + assertEquals(new Pair<Integer, String>(null, "a"), Pair.<Integer, String>of(null, "a")); + assertEquals(new Pair<Integer, String>(1, null), Pair.<Integer, String>of(1, null)); + } + + @Test + public void testExtractors() { + Function<Pair<Pair<String, Integer>, Character>, Pair<String, Integer>> first = Pair.first(); + Function<Pair<String, Integer>, Integer> second = Pair.second(); + assertEquals(Integer.valueOf(42), + Functions.compose(second, first).apply(Pair.of(Pair.of("arthur", 42), 'z'))); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/inject/BindingsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/inject/BindingsTest.java b/commons/src/test/java/com/twitter/common/inject/BindingsTest.java new file mode 100644 index 0000000..291ba00 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/inject/BindingsTest.java @@ -0,0 +1,128 @@ +package com.twitter.common.inject; + +import java.lang.annotation.Annotation; +import java.lang.annotation.Retention; +import java.util.List; + +import javax.inject.Qualifier; + +import com.google.inject.AbstractModule; +import com.google.inject.BindingAnnotation; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; +import com.google.inject.name.Named; +import com.google.inject.name.Names; + +import org.junit.Test; + +import com.twitter.common.inject.Bindings.KeyFactory; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class BindingsTest { + + private static final Named NAME_KEY = Names.named("fred"); + private static final TypeLiteral<List<String>> STRING_LIST = new TypeLiteral<List<String>>() { }; + + @Retention(RUNTIME) + @BindingAnnotation + @interface BindKey { } + + @Retention(RUNTIME) + @Qualifier + @interface QualifierKey { } + + @Test + public void testCheckBindingAnnotation() { + Bindings.checkBindingAnnotation(NAME_KEY); + Bindings.checkBindingAnnotation(BindKey.class); + + try { + Bindings.checkBindingAnnotation((Class<? extends Annotation>) null); + fail(); + } catch (NullPointerException e) { + // expected + } + + try { + Bindings.checkBindingAnnotation((Annotation) null); + fail(); + } catch (NullPointerException e) { + // expected + } + + try { + Bindings.checkBindingAnnotation(BindingAnnotation.class); + fail(); + } catch (IllegalArgumentException e) { + // expected + } + } + + public BindingsTest() { + super(); //To change body of overridden methods use File | Settings | File Templates. + } + + @Test + public void testPlainKeyFactory() { + assertEquals(Key.get(String.class), KeyFactory.PLAIN.create(String.class)); + assertEquals(Key.get(STRING_LIST), KeyFactory.PLAIN.create(STRING_LIST)); + } + + @Test + public void testAnnotationKeyFactory() { + KeyFactory factory = Bindings.annotatedKeyFactory(NAME_KEY); + assertEquals(Key.get(String.class, NAME_KEY), factory.create(String.class)); + assertEquals(Key.get(STRING_LIST, NAME_KEY), factory.create(STRING_LIST)); + } + + @Test + public void testAnnotationKeyFactoryJsr330() { + KeyFactory factory = Bindings.annotatedKeyFactory(NAME_KEY); + assertEquals(Key.get(String.class, NAME_KEY), factory.create(String.class)); + assertEquals(Key.get(STRING_LIST, NAME_KEY), factory.create(STRING_LIST)); + } + + @Test + public void testAnnotationTypeKeyFactory() { + KeyFactory factory = Bindings.annotatedKeyFactory(QualifierKey.class); + assertEquals(Key.get(String.class, QualifierKey.class), factory.create(String.class)); + assertEquals(Key.get(STRING_LIST, QualifierKey.class), factory.create(STRING_LIST)); + } + + @Test + public void testRebinder() { + Injector injector = Guice.createInjector(new AbstractModule() { + @Override protected void configure() { + Key<Integer> fromKey = Key.get(Integer.class, NAME_KEY); + bind(fromKey).toInstance(42); + Bindings.rebinder(binder(), BindKey.class).rebind(fromKey); + } + }); + assertEquals(42, injector.getInstance(Key.get(Integer.class, BindKey.class)).intValue()); + } + + @Test + public void testExposing() { + Injector injector = + Guice.createInjector(Bindings.exposing(Key.get(String.class), + new AbstractModule() { + @Override protected void configure() { + bind(String.class).toInstance("jake"); + bind(Integer.class).toInstance(42); + } + })); + + assertTrue(injector.getBindings().containsKey(Key.get(String.class))); + assertEquals("jake", injector.getInstance(String.class)); + + assertFalse(injector.getBindings().containsKey(Key.get(Integer.class))); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/inject/DefaultProviderTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/inject/DefaultProviderTest.java b/commons/src/test/java/com/twitter/common/inject/DefaultProviderTest.java new file mode 100644 index 0000000..48f8454 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/inject/DefaultProviderTest.java @@ -0,0 +1,68 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.inject; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Key; +import com.google.inject.Provides; +import com.google.inject.name.Named; +import com.google.inject.name.Names; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author John Sirois + */ +public class DefaultProviderTest { + public static final Key<String> CUSTOM_STRING = Key.get(String.class, Names.named("custom")); + public static final Key<String> DEFAULT_STRING = Key.get(String.class, Names.named("default")); + public static final Key<String> FINAL_STRING = Key.get(String.class, Names.named("final")); + + @Test + public void testDefault() { + assertEquals("jack", Guice.createInjector(new AbstractModule() { + @Override protected void configure() { + DefaultProvider.bindOrElse(CUSTOM_STRING, DEFAULT_STRING, FINAL_STRING, binder()); + } + + @Provides @Named("default") String provideDefault() { + return "jack"; + } + }).getInstance(FINAL_STRING)); + } + + @Test + public void testCustom() { + assertEquals("jill", Guice.createInjector(new AbstractModule() { + @Override protected void configure() { + DefaultProvider.bindOrElse(CUSTOM_STRING, DEFAULT_STRING, FINAL_STRING, binder()); + + } + + @Provides @Named("default") String provideDefault() { + return "jack"; + } + + @Provides @Named("custom") String provideCustom() { + return "jill"; + } + }).getInstance(FINAL_STRING)); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/io/Base64ZlibCodecTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/io/Base64ZlibCodecTest.java b/commons/src/test/java/com/twitter/common/io/Base64ZlibCodecTest.java new file mode 100644 index 0000000..83289ca --- /dev/null +++ b/commons/src/test/java/com/twitter/common/io/Base64ZlibCodecTest.java @@ -0,0 +1,81 @@ +package com.twitter.common.io; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.util.Random; +import java.util.zip.GZIPOutputStream; + +import org.apache.commons.codec.binary.Base64OutputStream; +import org.junit.Assert; + +import com.twitter.common.io.Base64ZlibCodec.InvalidDataException; + +import junit.framework.TestCase; + +public class Base64ZlibCodecTest extends TestCase { + + public void testEncodeDecode() throws Exception { + testEncodeDecode(0); + for (int i = 1; i < 10000; i *= 10) { + testEncodeDecode(i * 1024); + } + } + + public void testDecodeGzip() throws Exception { + final byte[] input = createRandomBytes(10240); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + final OutputStream os = new GZIPOutputStream(new Base64OutputStream(out)); + os.write(input); + os.close(); + final String encoded = new String(out.toByteArray(), "8859_1"); + assertTrue(encoded.startsWith("H4sIAAAAAAAAA")); + Assert.assertArrayEquals(input, Base64ZlibCodec.decode(encoded)); + } + + public void testInvalidData() throws Exception { + final String plain = createRandomText(10240); + try { + Base64ZlibCodec.decode("this is invalid"); + fail(); + } catch (InvalidDataException e) { + // This is expected + } + } + + public void testCorruptedData() throws Exception { + final char[] encoded = Base64ZlibCodec.encode(createRandomBytes(1024)).toCharArray(); + for (int i = 100; i < encoded.length; ++i) { + if (encoded[i] != 'Z') { + ++encoded[i]; + break; + } + } + try { + Base64ZlibCodec.decode(new String(encoded)); + fail(); + } catch (InvalidDataException e) { + // This is expected + } + } + + private static void testEncodeDecode(int len) throws Exception { + final byte[] input = createRandomBytes(len); + final String encoded = Base64ZlibCodec.encode(input); + assertTrue(encoded.startsWith("eJ")); + Assert.assertArrayEquals(input, Base64ZlibCodec.decode(encoded)); + } + + private static String createRandomText(int len) throws UnsupportedEncodingException { + final byte[] msg = new byte[len]; + new Random().nextBytes(msg); + return new String(msg, "8859_1"); + } + + private static byte[] createRandomBytes(int len) throws UnsupportedEncodingException { + final byte[] msg = new byte[len]; + new Random().nextBytes(msg); + return msg; + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/io/CodecTestUtilities.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/io/CodecTestUtilities.java b/commons/src/test/java/com/twitter/common/io/CodecTestUtilities.java new file mode 100644 index 0000000..8d1a542 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/io/CodecTestUtilities.java @@ -0,0 +1,37 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.io; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +class CodecTestUtilities { + static <T> byte[] serialize(Codec<T> codec, T item) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + codec.serialize(item, out); + return out.toByteArray(); + } + + static <T> T deserialize(Codec<T> codec, byte[] serialized) throws IOException { + return codec.deserialize(new ByteArrayInputStream(serialized)); + } + + static <T> T roundTrip(Codec<T> codec, T item) throws IOException { + return deserialize(codec, serialize(codec, item)); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/io/CompatibilityCodecTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/io/CompatibilityCodecTest.java b/commons/src/test/java/com/twitter/common/io/CompatibilityCodecTest.java new file mode 100644 index 0000000..56aa9f5 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/io/CompatibilityCodecTest.java @@ -0,0 +1,104 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.io; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Serializable; + +import com.google.common.base.Predicate; + +import org.junit.Test; + +import static com.twitter.common.io.CodecTestUtilities.deserialize; +import static com.twitter.common.io.CodecTestUtilities.serialize; +import static org.junit.Assert.assertEquals; + +public class CompatibilityCodecTest { + private final Codec<TestClass> primaryCodec = new SimpleCodec('x'); + private final Codec<TestClass> secondaryCodec = new SimpleCodec('y'); + private final Codec<TestClass> compatibilityCodec = CompatibilityCodec.create(primaryCodec, + secondaryCodec, 1, new Predicate<byte[]>() { + @Override + public boolean apply(byte[] input) { + return input.length > 0 && input[0] == 'x'; + } + }); + private final TestClass t = new TestClass(); + { + t.data = "foo"; + } + + @Test + public void testCompatibilityDeserializesSecondary() throws IOException { + assertCanDeserialize(compatibilityCodec, secondaryCodec); + } + + @Test + public void testCompatibilityDeserializesPrimary() throws IOException { + assertCanDeserialize(compatibilityCodec, primaryCodec); + } + + @Test + public void testCompatibilitySerializesPrimary() throws IOException { + assertCanDeserialize(primaryCodec, compatibilityCodec); + } + + @Test(expected = IOException.class) + public void testCompatibilityDoesNotSerializeSecondary() throws IOException { + assertCanDeserialize(secondaryCodec, compatibilityCodec); + } + + private void assertCanDeserialize(Codec<TestClass> reader, Codec<TestClass> writer) + throws IOException { + assertEquals("foo", deserialize(reader, serialize(writer, t)).data); + } + + public static class TestClass implements Serializable { + public String data; + } + + private static class SimpleCodec implements Codec<TestClass> { + + private final byte firstByte; + + SimpleCodec(char firstByte) { + this.firstByte = (byte) firstByte; + } + + @Override + public TestClass deserialize(InputStream source) throws IOException { + DataInputStream in = new DataInputStream(source); + if (in.readByte() != firstByte) { + throw new IOException("Corrupted stream"); + } + TestClass t = new TestClass(); + t.data = in.readUTF(); + return t; + } + + @Override + public void serialize(TestClass item, OutputStream sink) throws IOException { + DataOutputStream out = new DataOutputStream(sink); + out.writeByte(firstByte); + out.writeUTF(item.data); + } + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/io/FileUtilsTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/io/FileUtilsTest.java b/commons/src/test/java/com/twitter/common/io/FileUtilsTest.java new file mode 100644 index 0000000..9a8a445 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/io/FileUtilsTest.java @@ -0,0 +1,109 @@ +package com.twitter.common.io; + +import java.io.File; +import java.io.IOException; + +import com.google.common.io.Files; +import com.google.common.testing.TearDown; +import com.google.common.testing.junit4.JUnitAsserts; +import com.google.common.testing.junit4.TearDownTestCase; + +import org.junit.Before; +import org.junit.Test; + +import com.twitter.common.base.ExceptionalClosure; +import com.twitter.common.base.ExceptionalFunction; +import com.twitter.common.base.Function; +import com.twitter.common.io.FileUtils.Temporary; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * @author John Sirois + */ +public class FileUtilsTest extends TearDownTestCase { + + private Temporary temporary; + + @Before + public void setUp() { + final File tmpDir = FileUtils.createTempDir(); + addTearDown(new TearDown() { + @Override public void tearDown() throws Exception { + org.apache.commons.io.FileUtils.deleteDirectory(tmpDir); + } + }); + assertEmptyDir(tmpDir); + + temporary = new Temporary(tmpDir); + } + + @Test + public void testCreateDir() { + File tmpDir = temporary.createDir(); + assertEmptyDir(tmpDir); + } + + @Test + public void testCreateFile() throws IOException { + File tmpFile = temporary.createFile(".jake"); + assertEmptyFile(tmpFile); + JUnitAsserts.assertMatchesRegex(".+\\.jake$", tmpFile.getName()); + } + + @Test + public void testDoWithDir() { + assertEquals("42", temporary.doWithDir(new Function<File, String>() { + @Override public String apply(File dir) { + assertEmptyDir(dir); + return "42"; + } + })); + } + + static class MarkerException extends Exception {} + + @Test(expected = MarkerException.class) + public void testDoWithDir_bubbles() throws MarkerException { + temporary.doWithDir(new ExceptionalClosure<File, MarkerException>() { + @Override public void execute (File dir) throws MarkerException { + throw new MarkerException(); + } + }); + } + + @Test + public void testDoWithFile() throws IOException { + assertEquals("37", temporary.doWithFile(new ExceptionalFunction<File, String, IOException>() { + @Override public String apply(File file) throws IOException { + assertEmptyFile(file); + return "37"; + } + })); + } + + @Test(expected = MarkerException.class) + public void testDoWithFile_bubbles() throws MarkerException, IOException { + temporary.doWithFile(new ExceptionalClosure<File, MarkerException>() { + @Override public void execute(File dir) throws MarkerException { + throw new MarkerException(); + } + }); + } + + private void assertEmptyDir(File dir) { + assertNotNull(dir); + assertTrue(dir.exists()); + assertTrue(dir.isDirectory()); + assertEquals(0, dir.list().length); + } + + private void assertEmptyFile(File file) throws IOException { + assertNotNull(file); + assertTrue(file.exists()); + assertTrue(file.isFile()); + assertEquals(0, Files.toByteArray(file).length); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/io/JsonCodecTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/io/JsonCodecTest.java b/commons/src/test/java/com/twitter/common/io/JsonCodecTest.java new file mode 100644 index 0000000..909230b --- /dev/null +++ b/commons/src/test/java/com/twitter/common/io/JsonCodecTest.java @@ -0,0 +1,108 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.io; + +import java.io.IOException; +import java.util.Arrays; +import java.util.BitSet; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; + +import org.junit.Test; + +import static com.twitter.common.io.CodecTestUtilities.serialize; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class JsonCodecTest { + @Test + public void testRoundTrip() throws IOException { + TestClass testOut = createTestClassInstance(); + Codec<TestClass> codec = JsonCodec.create(TestClass.class); + TestClass testIn = CodecTestUtilities.roundTrip(codec, testOut); + assertEquals(testOut.data1, testIn.data1); + assertEquals(testOut.data2, testIn.data2); + assertEquals(testOut.data3, testIn.data3); + assertTrue(Arrays.equals(testOut.data4, testIn.data4)); + } + + @Test + public void testExpectedFormat() throws IOException { + Codec<TestClass> codec = JsonCodec.create(TestClass.class); + TestClass item = createTestClassInstance(); + JsonElement expectedElement = new JsonParser() + .parse("{\"data1\":\"foo\",\"data2\":\"bar\",\"data3\":42,\"data4\":[\"abc\",\"def\"]}"); + JsonElement actualElement = new JsonParser().parse(new String(serialize(codec, item), "utf-8")); + assertEquals(expectedElement.toString(), actualElement.toString()); + } + + private TestClass createTestClassInstance() { + TestClass testOut = new TestClass(); + testOut.data1 = "foo"; + testOut.data2 = "bar"; + testOut.data3 = 42; + testOut.data4 = new String[] { "abc", "def" }; + return testOut; + } + + @Test + public void testThriftExclusionWrongFieldClass() throws IOException { + ThriftTestClass1 test1 = new ThriftTestClass1(); + test1.data1 = "foo"; + test1.__isset_bit_vector = "bar"; + assertEquals("foo", roundTrip(test1).data1); + assertEquals("bar", roundTrip(test1).__isset_bit_vector); + } + + @Test + public void testThriftExclusionRightFieldClass() throws IOException { + ThriftTestClass2 test2 = new ThriftTestClass2(); + test2.data1 = "foo"; + test2.__isset_bit_vector = new BitSet(1); + assertEquals("foo", roundTrip(test2).data1); + assertNull(roundTrip(test2).__isset_bit_vector); + } + + private static <T> T roundTrip(T item) throws IOException { + @SuppressWarnings("unchecked") + Class<T> itemType = (Class<T>) item.getClass(); + return CodecTestUtilities.roundTrip(JsonCodec.create(itemType, + new GsonBuilder() + .setExclusionStrategies(JsonCodec.getThriftExclusionStrategy()) + .create()), item); + } + + public static class TestClass { + private String data1; + private String data2; + private int data3; + private String[] data4; + } + + public static class ThriftTestClass1 { + private String data1; + private String __isset_bit_vector; + } + + public static class ThriftTestClass2 { + private String data1; + private BitSet __isset_bit_vector; + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/io/ThriftCodecTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/io/ThriftCodecTest.java b/commons/src/test/java/com/twitter/common/io/ThriftCodecTest.java new file mode 100644 index 0000000..9328a2e --- /dev/null +++ b/commons/src/test/java/com/twitter/common/io/ThriftCodecTest.java @@ -0,0 +1,57 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.io; + +import static com.twitter.common.io.CodecTestUtilities.roundTrip; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TTransport; +import org.junit.Test; + +import com.google.common.base.Function; +import com.twitter.common.thrift.testing.TestThriftTypes.Struct; + +/** + * @author John Sirois + */ +public class ThriftCodecTest { + + @Test + public void testRoundTripJSON() throws IOException { + testRoundTrip(ThriftCodec.JSON_PROTOCOL); + } + + @Test + public void testRoundTripBinary() throws IOException { + testRoundTrip(ThriftCodec.BINARY_PROTOCOL); + } + + @Test + public void testRoundTripCompact() throws IOException { + testRoundTrip(ThriftCodec.COMPACT_PROTOCOL); + } + + private void testRoundTrip(Function<TTransport, TProtocol> protocolFactory) throws IOException { + Codec<Struct> codec = ThriftCodec.create(Struct.class, protocolFactory); + Struct struct = roundTrip(codec, new Struct("jake", "jones")); + assertEquals("jake", struct.getName()); + assertEquals("jones", struct.getValue()); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/logging/BufferedLogTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/logging/BufferedLogTest.java b/commons/src/test/java/com/twitter/common/logging/BufferedLogTest.java new file mode 100644 index 0000000..df98d8c --- /dev/null +++ b/commons/src/test/java/com/twitter/common/logging/BufferedLogTest.java @@ -0,0 +1,144 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.logging; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.List; + +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableList; +import com.google.common.util.concurrent.MoreExecutors; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.twitter.common.quantity.Amount; +import com.twitter.common.quantity.Time; + +/** + * Tests the BufferedLog. + * + * @author William Farner + */ +public class BufferedLogTest { + + private static final Predicate<Boolean> RETRY_FILTER = new Predicate<Boolean>() { + @Override public boolean apply(Boolean value) { + return !value; + } + }; + private static final int BUFFER_SIZE = 5; + private static final int MAX_BUFFER_SIZE = 10; + + private static final Boolean TRUE = Boolean.TRUE; + private static final Boolean FALSE = Boolean.FALSE; + + private static final List<String> MESSAGES = Arrays.asList("1", "2", "3", "4", "5"); + + private BufferedLog<String, Boolean> bufferedLog; + private Log<String, Boolean> wrappedLog; + + @Before + @SuppressWarnings("unchecked") // Due to createMock. + public void setUp() { + wrappedLog = createMock(Log.class); + + bufferedLog = BufferedLog.<String, Boolean>builder() + .buffer(wrappedLog) + .withRetryFilter(RETRY_FILTER) + .withChunkLength(BUFFER_SIZE) + .withMaxBuffer(MAX_BUFFER_SIZE) + .withFlushInterval(Amount.of(10000, Time.SECONDS)) + .withExecutorService(MoreExecutors.sameThreadExecutor()) + .build(); + } + + @After + public void runTest() { + verify(wrappedLog); + assertThat(bufferedLog.getBacklog(), is(0)); + } + + @Test + public void testBuffers() { + expect(wrappedLog.log(MESSAGES)).andReturn(TRUE); + + replay(wrappedLog); + bufferedLog.log(MESSAGES); + } + + @Test + public void testFlush() { + expect(wrappedLog.log(Arrays.asList("a", "b", "c"))).andReturn(TRUE); + + replay(wrappedLog); + bufferedLog.log("a"); + bufferedLog.log("b"); + bufferedLog.log("c"); + bufferedLog.flush(); + } + + @Test + public void testBufferRetries() { + List<String> bufferAppended = ImmutableList.<String>builder().addAll(MESSAGES).add("6").build(); + + expect(wrappedLog.log(MESSAGES)).andReturn(FALSE); + expect(wrappedLog.log(bufferAppended)).andReturn(TRUE); + + replay(wrappedLog); + bufferedLog.log(MESSAGES); + bufferedLog.log("6"); + } + + @Test + public void testTruncates() { + expect(wrappedLog.log(MESSAGES)).andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a"))).andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b"))).andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c"))).andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c", "d"))) + .andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c", "d", "e"))) + .andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("1", "2", "3", "4", "5", "a", "b", "c", "d", "e", "f"))) + .andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("2", "3", "4", "5", "a", "b", "c", "d", "e", "f", "g"))) + .andReturn(FALSE); + expect(wrappedLog.log(Arrays.asList("3", "4", "5", "a", "b", "c", "d", "e", "f", "g", "h"))) + .andReturn(TRUE); + + replay(wrappedLog); + + bufferedLog.log(MESSAGES); + bufferedLog.log("a"); + bufferedLog.log("b"); + bufferedLog.log("c"); + bufferedLog.log("d"); + bufferedLog.log("e"); + bufferedLog.log("f"); + bufferedLog.log("g"); + bufferedLog.log("h"); + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/logging/LogFormatterTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/logging/LogFormatterTest.java b/commons/src/test/java/com/twitter/common/logging/LogFormatterTest.java new file mode 100644 index 0000000..26e5961 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/logging/LogFormatterTest.java @@ -0,0 +1,59 @@ +package com.twitter.common.logging; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import com.google.common.base.Throwables; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +/** + * @author William Farner + */ +public class LogFormatterTest { + + private static final int THREAD_ID = 105; + private static final long TIME_MILLIS = 1298065054839L; + private static final String TIME_STRING = "0218 21:37:34.839"; + + private LogFormatter formatter; + + @Before + public void setUp() { + formatter = new LogFormatter(); + } + + @Test + public void testSimpleMessage() { + String message = "Configurated the whizzbanger."; + + LogRecord record = makeRecord(Level.INFO, message); + + assertThat(formatter.format(record), is( + String.format("I%s THREAD%d: %s\n", TIME_STRING, THREAD_ID, message))); + } + + @Test + public void testException() { + String message = "The fuzzbizzer failed."; + Throwable exception = new RuntimeException("No such fizzbuzzer."); + + LogRecord record = makeRecord(Level.WARNING, message); + record.setThrown(exception); + + assertThat(formatter.format(record), is( + String.format("W%s THREAD%d: %s\n%s\n", TIME_STRING, THREAD_ID, message, + Throwables.getStackTraceAsString(exception)))); + } + + private static LogRecord makeRecord(Level level, String message) { + LogRecord record = new LogRecord(level, message); + record.setMillis(TIME_MILLIS); + record.setThreadID(THREAD_ID); + return record; + } +} http://git-wip-us.apache.org/repos/asf/aurora/blob/86a547b9/commons/src/test/java/com/twitter/common/logging/LogUtilTest.java ---------------------------------------------------------------------- diff --git a/commons/src/test/java/com/twitter/common/logging/LogUtilTest.java b/commons/src/test/java/com/twitter/common/logging/LogUtilTest.java new file mode 100644 index 0000000..c56d783 --- /dev/null +++ b/commons/src/test/java/com/twitter/common/logging/LogUtilTest.java @@ -0,0 +1,64 @@ +// ================================================================================================= +// Copyright 2011 Twitter, Inc. +// ------------------------------------------------------------------------------------------------- +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this work except in compliance with the License. +// You may obtain a copy of the License in the LICENSE file, or 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 com.twitter.common.logging; + +import org.junit.Test; + +import java.io.File; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +/** + * @author William Farner + */ +public class LogUtilTest { + + @Test + public void testEmptyPattern() { + test(null, LogUtil.DEFAULT_LOG_DIR); + test("", LogUtil.DEFAULT_LOG_DIR); + } + + @Test + public void testLocalDir() { + test(".", "."); + test("./asdf.%g.log", "."); + test("asdf.%g.log", "."); + } + + @Test + public void testRelativeDir() { + test("../asdf.%g.log", ".."); + test("b/asdf.%g.log", "b"); + test("b/c/d/asdf.%g.log", "b/c/d"); + } + + @Test + public void testAbsoluteDir() { + test("/a/b/c/d/logs.%g.%u.log", "/a/b/c/d"); + test("/asdf.log", "/"); + } + + private void test(String pattern, String expected) { + assertThat(LogUtil.getLogManagerLogDir(pattern).getPath(), is(expected)); + } + + private void test(String pattern, File expected) { + test(pattern, expected.getPath()); + } +}
