src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
AnnotationValues { public static byte getByte(AnnotationValue value) { return valueOfType(value, Byte.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getByte() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "byteValue"); assertThat(AnnotationValues.getByte(value)).isEqualTo((byte) 7); }
AnnotationValues { public static ImmutableList<Byte> getBytes(AnnotationValue value) { return BYTES_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getBytes() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "byteValues"); assertThat(AnnotationValues.getBytes(value)).containsExactly((byte) 8, (byte) 9).inOrder(); }
AnnotationValues { public static short getShort(AnnotationValue value) { return valueOfType(value, Short.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getShort() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "shortValue"); assertThat(AnnotationValues.getShort(value)).isEqualTo((short) 10); }
AnnotationValues { public static ImmutableList<Short> getShorts(AnnotationValue value) { return SHORTS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getShorts() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "shortValues"); assertThat(AnnotationValues.getShorts(value)).containsExactly((short) 11, (short) 12).inOrder(); }
AnnotationValues { public static float getFloat(AnnotationValue value) { return valueOfType(value, Float.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getFloat() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "floatValue"); assertThat(AnnotationValues.getFloat(value)).isEqualTo(13F); }
AnnotationValues { public static ImmutableList<Float> getFloats(AnnotationValue value) { return FLOATS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getFloats() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "floatValues"); assertThat(AnnotationValues.getFloats(value)).containsExactly(14F, 15F).inOrder(); }
AnnotationValues { public static double getDouble(AnnotationValue value) { return valueOfType(value, Double.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getDouble() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "doubleValue"); assertThat(AnnotationValues.getDouble(value)).isEqualTo(16D); }
AnnotationValues { public static ImmutableList<Double> getDoubles(AnnotationValue value) { return DOUBLES_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getDoubles() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "doubleValues"); assertThat(AnnotationValues.getDoubles(value)).containsExactly(17D, 18D).inOrder(); }
AnnotationValues { public static boolean getBoolean(AnnotationValue value) { return valueOfType(value, Boolean.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getBoolean() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "booleanValue"); assertThat(AnnotationValues.getBoolean(value)).isTrue(); }
AnnotationValues { public static ImmutableList<Boolean> getBooleans(AnnotationValue value) { return BOOLEANS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getBooleans() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "booleanValues"); assertThat(AnnotationValues.getBooleans(value)).containsExactly(true, false).inOrder(); }
AnnotationValues { public static char getChar(AnnotationValue value) { return valueOfType(value, Character.class); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getChar() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "charValue"); assertThat(AnnotationValues.getChar(value)).isEqualTo('a'); }
AnnotationValues { public static ImmutableList<Character> getChars(AnnotationValue value) { return CHARS_VISITOR.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getChars() { AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "charValues"); assertThat(AnnotationValues.getChars(value)).containsExactly('b', 'c').inOrder(); }
SerializerFactoryImpl implements SerializerFactory { @Override public Serializer getSerializer(TypeMirror typeMirror) { for (SerializerExtension extension : extensions) { Optional<Serializer> serializer = extension.getSerializer(typeMirror, this, env); if (serializer.isPresent()) { return serializer.get(); } } return IdentitySerializerFactory.getSerializer(typeMirror); } SerializerFactoryImpl( ImmutableList<SerializerExtension> extensions, ProcessingEnvironment env); @Override Serializer getSerializer(TypeMirror typeMirror); }
@Test public void getSerializer_emptyFactories_identitySerializerReturned() throws Exception { SerializerFactoryImpl factory = new SerializerFactoryImpl(ImmutableList.of(), mockProcessingEnvironment); Serializer actualSerializer = factory.getSerializer(typeMirrorOf(String.class)); assertThat(actualSerializer.getClass().getName()) .contains("IdentitySerializerFactory$IdentitySerializer"); } @Test public void getSerializer_factoriesProvided_factoryReturned() throws Exception { SerializerFactoryImpl factory = new SerializerFactoryImpl( ImmutableList.of(new TestStringSerializerFactory()), mockProcessingEnvironment); Serializer actualSerializer = factory.getSerializer(typeMirrorOf(String.class)); assertThat(actualSerializer.getClass().getName()) .contains("TestStringSerializerFactory$TestStringSerializer"); }
ImmutableMapSerializerExtension implements SerializerExtension { @Override public Optional<Serializer> getSerializer( TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv) { if (!isImmutableMap(typeMirror)) { return Optional.empty(); } TypeMirror keyType = getKeyType(typeMirror); TypeMirror valueType = getValueType(typeMirror); Serializer keyTypeSerializer = factory.getSerializer(keyType); Serializer valueTypeSerializer = factory.getSerializer(valueType); if (keyTypeSerializer.isIdentity() && valueTypeSerializer.isIdentity()) { return Optional.empty(); } return Optional.of( new ImmutableMapSerializer( keyType, valueType, keyTypeSerializer, valueTypeSerializer, processingEnv)); } ImmutableMapSerializerExtension(); @Override Optional<Serializer> getSerializer( TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv); }
@Test public void getSerializer_nonImmutableMap_emptyReturned() { TypeMirror typeMirror = typeMirrorOf(String.class); Optional<Serializer> actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment); assertThat(actualSerializer).isEmpty(); } @Test public void getSerializer_immutableMapWithSerializableContainedTypes_emptyReturned() { fakeSerializerFactory.setReturnIdentitySerializer(true); TypeMirror typeMirror = typeMirrorOf(ImmutableMap.class); Optional<Serializer> actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment); assertThat(actualSerializer).isEmpty(); } @Test public void getSerializer_immutableMap_serializerReturned() { TypeMirror typeMirror = typeMirrorOf(ImmutableMap.class); Serializer actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); assertThat(actualSerializer.getClass().getName()) .contains("ImmutableMapSerializerExtension$ImmutableMapSerializer"); } @Test public void proxyFieldType() { TypeMirror typeMirror = declaredTypeOf(ImmutableMap.class, Integer.class, String.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); TypeMirror actualTypeMirror = serializer.proxyFieldType(); assertThat(typeUtils.isSameType(actualTypeMirror, typeMirror)).isTrue(); } @Test public void toProxy() { TypeMirror typeMirror = declaredTypeOf(ImmutableMap.class, Integer.class, String.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); CodeBlock actualCodeBlock = serializer.toProxy(CodeBlock.of("x")); assertThat(actualCodeBlock.toString()) .isEqualTo( String.format( "x.entrySet().stream().collect(%s.toImmutableMap(value$ -> %s.<%s," + " %s>wrapper(element$ -> element$).apply(value$.getKey()), value$ -> %s.<%s," + " %s>wrapper(element$ -> element$).apply(value$.getValue())))", IMMUTABLE_MAP, FUNCTION_WITH_EXCEPTIONS, INTEGER, INTEGER, FUNCTION_WITH_EXCEPTIONS, STRING, STRING)); } @Test public void fromProxy() { TypeMirror typeMirror = declaredTypeOf(ImmutableMap.class, Integer.class, String.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); CodeBlock actualCodeBlock = serializer.fromProxy(CodeBlock.of("x")); assertThat(actualCodeBlock.toString()) .isEqualTo( String.format( "x.entrySet().stream().collect(%s.toImmutableMap(value$ -> %s.<%s," + " %s>wrapper(element$ -> element$).apply(value$.getKey()), value$ -> %s.<%s," + " %s>wrapper(element$ -> element$).apply(value$.getValue())))", IMMUTABLE_MAP, FUNCTION_WITH_EXCEPTIONS, INTEGER, INTEGER, FUNCTION_WITH_EXCEPTIONS, STRING, STRING)); }
ImmutableListSerializerExtension implements SerializerExtension { @Override public Optional<Serializer> getSerializer( TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv) { if (!isImmutableList(typeMirror)) { return Optional.empty(); } TypeMirror containedType = getContainedType(typeMirror); Serializer containedTypeSerializer = factory.getSerializer(containedType); if (containedTypeSerializer.isIdentity()) { return Optional.empty(); } return Optional.of(new ImmutableListSerializer(containedTypeSerializer, processingEnv)); } ImmutableListSerializerExtension(); @Override Optional<Serializer> getSerializer( TypeMirror typeMirror, SerializerFactory factory, ProcessingEnvironment processingEnv); }
@Test public void getSerializer_nonImmutableList_emptyReturned() { TypeMirror typeMirror = typeMirrorOf(String.class); Optional<Serializer> actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment); assertThat(actualSerializer).isEmpty(); } @Test public void getSerializer_immutableListWithSerializableContainedType_emptyReturned() { fakeSerializerFactory.setReturnIdentitySerializer(true); TypeMirror typeMirror = typeMirrorOf(ImmutableList.class); Optional<Serializer> actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment); assertThat(actualSerializer).isEmpty(); } @Test public void getSerializer_immutableList_serializerReturned() { TypeMirror typeMirror = typeMirrorOf(ImmutableList.class); Serializer actualSerializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); assertThat(actualSerializer.getClass().getName()) .contains("ImmutableListSerializerExtension$ImmutableListSerializer"); } @Test public void proxyFieldType() { TypeMirror typeMirror = declaredTypeOf(ImmutableList.class, Integer.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); TypeMirror actualTypeMirror = serializer.proxyFieldType(); assertThat(typeUtils.isSameType(actualTypeMirror, typeMirror)).isTrue(); } @Test public void toProxy() { TypeMirror typeMirror = declaredTypeOf(ImmutableList.class, Integer.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); CodeBlock actualCodeBlock = serializer.toProxy(CodeBlock.of("x")); assertThat(actualCodeBlock.toString()) .isEqualTo( String.format( "x.stream().map(%s.wrapper(value$ -> value$)).collect(%s.toImmutableList())", FUNCTION_WITH_EXCEPTIONS, IMMUTABLE_LIST)); } @Test public void fromProxy() { TypeMirror typeMirror = declaredTypeOf(ImmutableList.class, Integer.class); Serializer serializer = extension.getSerializer(typeMirror, fakeSerializerFactory, mockProcessingEnvironment).get(); CodeBlock actualCodeBlock = serializer.fromProxy(CodeBlock.of("x")); assertThat(actualCodeBlock.toString()) .isEqualTo( String.format( "x.stream().map(%s.wrapper(value$ -> value$)).collect(%s.toImmutableList())", FUNCTION_WITH_EXCEPTIONS, IMMUTABLE_LIST)); }
IdentitySerializerFactory { public static Serializer getSerializer(TypeMirror typeMirror) { return new IdentitySerializer(typeMirror); } private IdentitySerializerFactory(); static Serializer getSerializer(TypeMirror typeMirror); }
@Test public void proxyFieldType_isUnchanged() throws Exception { TypeMirror typeMirror = typeMirrorOf(String.class); TypeMirror actualTypeMirror = IdentitySerializerFactory.getSerializer(typeMirror).proxyFieldType(); assertThat(actualTypeMirror).isSameInstanceAs(typeMirror); } @Test public void toProxy_isUnchanged() throws Exception { TypeMirror typeMirror = typeMirrorOf(String.class); CodeBlock inputExpression = CodeBlock.of("x"); CodeBlock outputExpression = IdentitySerializerFactory.getSerializer(typeMirror).toProxy(inputExpression); assertThat(outputExpression).isSameInstanceAs(inputExpression); } @Test public void fromProxy_isUnchanged() throws Exception { TypeMirror typeMirror = typeMirrorOf(String.class); CodeBlock inputExpression = CodeBlock.of("x"); CodeBlock outputExpression = IdentitySerializerFactory.getSerializer(typeMirror).fromProxy(inputExpression); assertThat(outputExpression).isSameInstanceAs(inputExpression); } @Test public void isIdentity() throws Exception { TypeMirror typeMirror = typeMirrorOf(String.class); boolean actualIsIdentity = IdentitySerializerFactory.getSerializer(typeMirror).isIdentity(); assertThat(actualIsIdentity).isTrue(); }
Reformatter { static String fixup(String s) { StringBuilder out = new StringBuilder(); JavaScanner scanner = new JavaScanner(s); s = scanner.string(); int len = s.length(); for (int start = 0, previous = 0, braces = 0, parens = 0, end = 0; start < len; previous = start, start = end) { end = scanner.tokenEnd(start); switch (s.charAt(start)) { case '(': parens++; break; case ')': parens--; break; case '{': braces++; break; case '}': braces--; break; case ' ': if (s.charAt(previous) != '(' && "\n.,;)".indexOf(s.charAt(end)) < 0) { out.append(' '); } continue; case '\n': if (end < len && s.charAt(end) != '\n') { if (out.length() == 0) { start++; } break; } if (parens == 0 && braces < 2 && s.charAt(previous) != '\n' && out.length() > 0) { out.append('\n'); } continue; default: break; } out.append(s, start, end); } return out.toString(); } }
@Test public void testSimple() { String input = "\n" + "package com.latin.declension; \n" + "\n" + "\n" + "public class Idem { \n" + " \n" + " Eadem idem ; \n" + "\n" + " Eundem eandem ( Idem eiusdem ) {\n" + "\n" + " eiusdem ( eiusdem ) ; \n" + "\n" + " eidem_eidem_eidem( ) ;\n" + "\n" + " }\n" + "\n" + "\n" + " Eodem ( Eadem eodem ) { }\n"; String output = "package com.latin.declension;\n" + "\n" + "public class Idem {\n" + "\n" + " Eadem idem;\n" + "\n" + " Eundem eandem (Idem eiusdem) {\n" + " eiusdem (eiusdem);\n" + " eidem_eidem_eidem();\n" + " }\n" + "\n" + " Eodem (Eadem eodem) { }\n"; assertEquals(output, Reformatter.fixup(input)); } @Test public void testSpecialSpaces() { String input = "\n" + "package com.example.whatever;\n" + "\n" + "public class SomeClass {\n" + " static final String STRING = \" hello world \\n\"; \n" + " static final String STRING_WITH_QUOTES = \" \\\"quote me now \\\" \" ;\n" + " static final int INT = 23 ;\n" + " static final char QUOTE = '\"' ;\n" + " static final char QUOTE2 = '\\\"' ;\n" + "}\n"; String output = "package com.example.whatever;\n" + "\n" + "public class SomeClass {\n" + " static final String STRING = \" hello world \\n\";\n" + " static final String STRING_WITH_QUOTES = \" \\\"quote me now \\\" \";\n" + " static final int INT = 23;\n" + " static final char QUOTE = '\"';\n" + " static final char QUOTE2 = '\\\"';\n" + "}\n"; assertEquals(output, Reformatter.fixup(input)); } @Test public void noTrailingNewline() { String input = "package com.example.whatever;\n\npublic class SomeClass {}"; String output = input + "\n"; assertEquals(output, Reformatter.fixup(input)); }
SimpleServiceLoader { public static <T> ImmutableList<T> load(Class<? extends T> service, ClassLoader loader) { String resourceName = "META-INF/services/" + service.getName(); List<URL> resourceUrls; try { resourceUrls = Collections.list(loader.getResources(resourceName)); } catch (IOException e) { throw new ServiceConfigurationError("Could not look up " + resourceName, e); } ImmutableList.Builder<T> providers = ImmutableList.builder(); for (URL resourceUrl : resourceUrls) { try { providers.addAll(providersFromUrl(resourceUrl, service, loader)); } catch (IOException e) { throw new ServiceConfigurationError("Could not read " + resourceUrl, e); } } return providers.build(); } private SimpleServiceLoader(); static ImmutableList<T> load(Class<? extends T> service, ClassLoader loader); }
@Test public void loadOnce() throws Exception { ClassLoader loader = loaderForJarWithEntries( CharSequence.class.getName(), String.class.getName(), StringBuilder.class.getName()); ImmutableList<CharSequence> providers = SimpleServiceLoader.load(CharSequence.class, loader); assertThat(providers).contains(""); List<Class<?>> classes = providers.stream().map(Object::getClass).collect(toList()); assertThat(classes).containsExactly(String.class, StringBuilder.class).inOrder(); } @Test public void blankLinesAndComments() throws Exception { ClassLoader loader = loaderForJarWithEntries( CharSequence.class.getName(), "", "# this is a comment", " # this is also a comment", " java.lang.String # this is a comment after a class name"); ImmutableList<CharSequence> providers = SimpleServiceLoader.load(CharSequence.class, loader); assertThat(providers).containsExactly(""); } @Test public void loadTwiceFromSameLoader() throws Exception { ClassLoader loader = loaderForJarWithEntries( CharSequence.class.getName(), String.class.getName(), StringBuilder.class.getName()); ImmutableList<CharSequence> providers1 = SimpleServiceLoader.load(CharSequence.class, loader); ImmutableList<CharSequence> providers2 = SimpleServiceLoader.load(CharSequence.class, loader); List<Class<?>> classes1 = providers1.stream().map(Object::getClass).collect(toList()); List<Class<?>> classes2 = providers2.stream().map(Object::getClass).collect(toList()); assertThat(classes2).containsExactlyElementsIn(classes1).inOrder(); } @Test public void loadTwiceFromDifferentLoaders() throws Exception { URL jarUrl = urlForJarWithEntries( CharSequence.class.getName(), String.class.getName(), StringBuilder.class.getName()); ClassLoader loader1 = new URLClassLoader(new URL[] {jarUrl}); ImmutableList<CharSequence> providers1 = SimpleServiceLoader.load(CharSequence.class, loader1); assertThat(providers1).contains(""); ClassLoader loader2 = new URLClassLoader(new URL[] {jarUrl}); ImmutableList<CharSequence> providers2 = SimpleServiceLoader.load(CharSequence.class, loader2); List<Class<?>> classes1 = providers1.stream().map(Object::getClass).collect(toList()); List<Class<?>> classes2 = providers2.stream().map(Object::getClass).collect(toList()); assertThat(classes2).containsExactlyElementsIn(classes1).inOrder(); } @Test public void noProviders() throws Exception { ClassLoader loader = loaderForJarWithEntries(CharSequence.class.getName()); ImmutableList<CharSequence> providers = SimpleServiceLoader.load(CharSequence.class, loader); assertThat(providers).isEmpty(); } @Test public void classNotFound() throws Exception { ClassLoader loader = loaderForJarWithEntries(CharSequence.class.getName(), "this.is.not.a.Class"); try { SimpleServiceLoader.load(CharSequence.class, loader); fail(); } catch (ServiceConfigurationError expected) { assertThat(expected).hasMessageThat().startsWith("Could not load "); } } @Test public void wrongTypeClass() throws Exception { ClassLoader loader = loaderForJarWithEntries(CharSequence.class.getName(), "java.lang.Thread"); try { SimpleServiceLoader.load(CharSequence.class, loader); fail(); } catch (ServiceConfigurationError expected) { assertThat(expected).hasMessageThat().startsWith("Class java.lang.Thread is not assignable"); } } @Test public void couldNotConstruct() throws Exception { ClassLoader loader = loaderForJarWithEntries("java.lang.System", "java.lang.System"); try { SimpleServiceLoader.load(System.class, loader); fail(); } catch (ServiceConfigurationError expected) { assertThat(expected).hasMessageThat().startsWith("Could not construct"); } } @Test public void brokenLoader() { ClassLoader loader = new URLClassLoader(new URL[0]) { @Override public Enumeration<URL> getResources(String name) throws IOException { throw new IOException("bang"); } }; try { SimpleServiceLoader.load(CharSequence.class, loader); fail(); } catch (ServiceConfigurationError expected) { assertThat(expected).hasMessageThat().startsWith("Could not look up"); assertThat(expected).hasCauseThat().hasMessageThat().isEqualTo("bang"); } }
TemplateVars { String toText() { Map<String, Object> vars = toVars(); return parsedTemplate().evaluate(vars); } TemplateVars(); }
@Test public void testHappy() { HappyVars happy = new HappyVars(); happy.integer = 23; happy.string = "wibble"; happy.list = ImmutableList.of(5, 17, 23); assertThat(HappyVars.IGNORED_STATIC_FINAL).isEqualTo("hatstand"); String expectedText = "integer=23 string=wibble list=[5, 17, 23]"; String actualText = happy.toText(); assertThat(actualText).isEqualTo(expectedText); } @Test public void testUnset() { HappyVars sad = new HappyVars(); sad.integer = 23; sad.list = ImmutableList.of(23); try { sad.toText(); fail("Did not get expected exception"); } catch (IllegalArgumentException expected) { } } @Test public void testSubSub() { SubHappyVars vars = new SubHappyVars(); vars.integer = 23; vars.string = "wibble"; vars.list = ImmutableList.of(5, 17, 23); vars.character = 'ß'; String expectedText = "integer=23 string=wibble list=[5, 17, 23] character=ß"; String actualText = vars.toText(); assertThat(actualText).isEqualTo(expectedText); }
JavaScanner { int tokenEnd(int start) { if (start >= s.length()) { return s.length(); } switch (s.charAt(start)) { case ' ': case '\n': return spaceEnd(start); case '/': if (s.charAt(start + 1) == '*') { return blockCommentEnd(start); } else if (s.charAt(start + 1) == '/') { return lineCommentEnd(start); } else { return start + 1; } case '\'': case '"': case '`': return quoteEnd(start); default: return start + 1; } } JavaScanner(String s); }
@Test public void testScanner() { String input = Joiner.on("").join(TOKENS); ImmutableList.Builder<String> tokensBuilder = ImmutableList.builder(); JavaScanner tokenizer = new JavaScanner(input); int end; for (int i = 0; i < input.length(); i = end) { end = tokenizer.tokenEnd(i); tokensBuilder.add(input.substring(i, end)); } assertThat(tokensBuilder.build()).containsExactlyElementsIn(TOKENS).inOrder(); }
TypeVariables { static ImmutableMap<ExecutableElement, TypeMirror> rewriteReturnTypes( Elements elementUtils, Types typeUtils, Collection<ExecutableElement> methods, TypeElement sourceType, TypeElement targetType) { List<? extends TypeParameterElement> sourceTypeParameters = sourceType.getTypeParameters(); List<? extends TypeParameterElement> targetTypeParameters = targetType.getTypeParameters(); Preconditions.checkArgument( sourceTypeParameters.toString().equals(targetTypeParameters.toString()), "%s != %s", sourceTypeParameters, targetTypeParameters); EclipseHack eclipseHack = new EclipseHack(elementUtils, typeUtils); TypeMirror[] targetTypeParameterMirrors = new TypeMirror[targetTypeParameters.size()]; for (int i = 0; i < targetTypeParameters.size(); i++) { targetTypeParameterMirrors[i] = targetTypeParameters.get(i).asType(); } DeclaredType parallelSource = typeUtils.getDeclaredType(sourceType, targetTypeParameterMirrors); return methods.stream() .collect( ImmutableMap.toImmutableMap( m -> m, m -> eclipseHack.methodReturnType(m, parallelSource))); } private TypeVariables(); }
@Test public void noTypeParameters() { TypeElement source1 = elementUtils.getTypeElement(Source1.class.getCanonicalName()); TypeElement target1 = elementUtils.getTypeElement(Target1.class.getCanonicalName()); List<ExecutableElement> sourceMethods = ElementFilter.methodsIn(source1.getEnclosedElements()); Map<ExecutableElement, TypeMirror> types = TypeVariables.rewriteReturnTypes(elementUtils, typeUtils, sourceMethods, source1, target1); assertThat(types).containsExactly(sourceMethods.get(0), sourceMethods.get(0).getReturnType()); } @Test public void simpleTypeParameter() { TypeElement source2 = elementUtils.getTypeElement(Source2.class.getCanonicalName()); TypeElement target2 = elementUtils.getTypeElement(Target2.class.getCanonicalName()); List<ExecutableElement> sourceMethods = ElementFilter.methodsIn(source2.getEnclosedElements()); Map<ExecutableElement, TypeMirror> types = TypeVariables.rewriteReturnTypes(elementUtils, typeUtils, sourceMethods, source2, target2); List<ExecutableElement> targetMethods = ElementFilter.methodsIn(target2.getEnclosedElements()); TypeMirror setFooParameter = targetMethods.get(0).getParameters().get(0).asType(); ExecutableElement getFoo = sourceMethods.get(0); TypeMirror originalGetFooReturn = getFoo.getReturnType(); TypeMirror rewrittenGetFooReturn = types.get(getFoo); assertThat(typeUtils.isAssignable(setFooParameter, originalGetFooReturn)).isFalse(); assertThat(typeUtils.isAssignable(setFooParameter, rewrittenGetFooReturn)).isTrue(); } @Test public void hairyTypeParameters() { TypeElement source3 = elementUtils.getTypeElement(Source3.class.getCanonicalName()); TypeElement target3 = elementUtils.getTypeElement(Target3.class.getCanonicalName()); List<ExecutableElement> sourceMethods = ElementFilter.methodsIn(source3.getEnclosedElements()); Map<ExecutableElement, TypeMirror> types = TypeVariables.rewriteReturnTypes(elementUtils, typeUtils, sourceMethods, source3, target3); List<ExecutableElement> targetMethods = ElementFilter.methodsIn(target3.getEnclosedElements()); TypeMirror setFooParameter = targetMethods.get(0).getParameters().get(0).asType(); ExecutableElement getFoo = sourceMethods.get(0); TypeMirror originalGetFooReturn = getFoo.getReturnType(); TypeMirror rewrittenGetFooReturn = types.get(getFoo); assertThat(typeUtils.isAssignable(setFooParameter, originalGetFooReturn)).isFalse(); assertThat(typeUtils.isAssignable(setFooParameter, rewrittenGetFooReturn)).isTrue(); } @Test public void nestedClasses() { TypeElement outer = elementUtils.getTypeElement(Outer.class.getCanonicalName()); TypeElement inner = elementUtils.getTypeElement(Outer.Inner.class.getCanonicalName()); List<ExecutableElement> outerMethods = ElementFilter.methodsIn(outer.getEnclosedElements()); Map<ExecutableElement, TypeMirror> types = TypeVariables.rewriteReturnTypes(elementUtils, typeUtils, outerMethods, outer, inner); List<ExecutableElement> innerMethods = ElementFilter.methodsIn(inner.getEnclosedElements()); ExecutableElement getFoo = methodNamed(outerMethods, "getFoo"); ExecutableElement getBar = methodNamed(outerMethods, "getBar"); ExecutableElement setFoo = methodNamed(innerMethods, "setFoo"); ExecutableElement setBar = methodNamed(innerMethods, "setBar"); TypeMirror setFooParameter = setFoo.getParameters().get(0).asType(); TypeMirror originalGetFooReturn = getFoo.getReturnType(); TypeMirror rewrittenGetFooReturn = types.get(getFoo); assertThat(typeUtils.isAssignable(setFooParameter, originalGetFooReturn)).isFalse(); assertThat(typeUtils.isAssignable(setFooParameter, rewrittenGetFooReturn)).isTrue(); TypeMirror setBarParameter = setBar.getParameters().get(0).asType(); TypeMirror originalGetBarReturn = getBar.getReturnType(); TypeMirror rewrittenGetBarReturn = types.get(getBar); assertThat(typeUtils.isAssignable(setBarParameter, originalGetBarReturn)).isFalse(); assertThat(typeUtils.isAssignable(setBarParameter, rewrittenGetBarReturn)).isTrue(); }
TypeVariables { static boolean canAssignStaticMethodResult( ExecutableElement method, TypeMirror actualParameterType, TypeMirror targetType, Types typeUtils) { if (!targetType.getKind().equals(TypeKind.DECLARED) || !method.getModifiers().contains(Modifier.STATIC) || method.getParameters().size() != 1) { return false; } List<? extends TypeParameterElement> typeParameters = method.getTypeParameters(); List<? extends TypeMirror> targetTypeArguments = MoreTypes.asDeclared(targetType).getTypeArguments(); if (typeParameters.size() != targetTypeArguments.size()) { return false; } Map<Equivalence.Wrapper<TypeVariable>, TypeMirror> typeVariables = new LinkedHashMap<>(); for (int i = 0; i < typeParameters.size(); i++) { TypeVariable v = MoreTypes.asTypeVariable(typeParameters.get(i).asType()); typeVariables.put(MoreTypes.equivalence().wrap(v), targetTypeArguments.get(i)); } TypeMirror formalParameterType = method.getParameters().get(0).asType(); SubstitutionVisitor substitutionVisitor = new SubstitutionVisitor(typeVariables, typeUtils); TypeMirror substitutedParameterType = substitutionVisitor.visit(formalParameterType, null); if (substitutedParameterType.getKind().equals(TypeKind.WILDCARD)) { WildcardType wildcard = MoreTypes.asWildcard(substitutedParameterType); if (wildcard.getExtendsBound() != null) { substitutedParameterType = wildcard.getExtendsBound(); } } return typeUtils.isAssignable(actualParameterType, substitutedParameterType); } private TypeVariables(); }
@Test public void canAssignStaticMethodResult() { TypeElement immutableMap = elementUtils.getTypeElement(ImmutableMap.class.getCanonicalName()); TypeElement string = elementUtils.getTypeElement(String.class.getCanonicalName()); TypeElement integer = elementUtils.getTypeElement(Integer.class.getCanonicalName()); TypeElement number = elementUtils.getTypeElement(Number.class.getCanonicalName()); TypeMirror immutableMapStringNumber = typeUtils.getDeclaredType(immutableMap, string.asType(), number.asType()); TypeMirror immutableMapStringInteger = typeUtils.getDeclaredType(immutableMap, string.asType(), integer.asType()); TypeElement map = elementUtils.getTypeElement(Map.class.getCanonicalName()); TypeMirror erasedMap = typeUtils.erasure(map.asType()); List<ExecutableElement> immutableMapMethods = ElementFilter.methodsIn(immutableMap.getEnclosedElements()); ExecutableElement copyOf = methodNamed(immutableMapMethods, "copyOf", erasedMap); expect.that( TypeVariables.canAssignStaticMethodResult( copyOf, immutableMapStringInteger, immutableMapStringNumber, typeUtils)) .isTrue(); expect.that( TypeVariables.canAssignStaticMethodResult( copyOf, immutableMapStringNumber, immutableMapStringInteger, typeUtils)) .isFalse(); }
PropertyNames { static String decapitalizeLikeJavaBeans(String propertyName) { if (propertyName != null && propertyName.length() >= 2 && Character.isUpperCase(propertyName.charAt(0)) && Character.isUpperCase(propertyName.charAt(1))) { return propertyName; } return decapitalizeNormally(propertyName); } }
@Test public void decapitalizeLikeJavaBeans() { NORMAL_CASES .forEach( (input, output) -> { expect.that(PropertyNames.decapitalizeLikeJavaBeans(input)).isEqualTo(output); }); expect.that(PropertyNames.decapitalizeLikeJavaBeans(null)).isNull(); expect.that(PropertyNames.decapitalizeLikeJavaBeans("HTMLPage")).isEqualTo("HTMLPage"); expect.that(PropertyNames.decapitalizeLikeJavaBeans("OAuth")).isEqualTo("OAuth"); }
PropertyNames { static String decapitalizeNormally(String propertyName) { if (Strings.isNullOrEmpty(propertyName)) { return propertyName; } return Character.toLowerCase(propertyName.charAt(0)) + propertyName.substring(1); } }
@Test public void decapitalizeNormally() { NORMAL_CASES .forEach( (input, output) -> { expect.that(PropertyNames.decapitalizeNormally(input)).isEqualTo(output); }); expect.that(PropertyNames.decapitalizeNormally(null)).isNull(); expect.that(PropertyNames.decapitalizeNormally("HTMLPage")).isEqualTo("hTMLPage"); expect.that(PropertyNames.decapitalizeNormally("OAuth")).isEqualTo("oAuth"); }
TypeSimplifier { static String packageNameOf(TypeElement type) { return MoreElements.getPackage(type).getQualifiedName().toString(); } TypeSimplifier( Elements elementUtils, Types typeUtils, String packageName, Set<TypeMirror> types, TypeMirror base); }
@Test public void testPackageNameOfString() { assertThat(TypeSimplifier.packageNameOf(typeElementOf(java.lang.String.class))) .isEqualTo("java.lang"); } @Test public void testPackageNameOfMapEntry() { assertThat(TypeSimplifier.packageNameOf(typeElementOf(java.util.Map.Entry.class))) .isEqualTo("java.util"); }
TypeSimplifier { static boolean isCastingUnchecked(TypeMirror type) { return CASTING_UNCHECKED_VISITOR.visit(type, null); } TypeSimplifier( Elements elementUtils, Types typeUtils, String packageName, Set<TypeMirror> types, TypeMirror base); }
@Test public void testIsCastingUnchecked() { TypeElement erasureClass = typeElementOf(Erasure.class); List<VariableElement> fields = ElementFilter.fieldsIn(erasureClass.getEnclosedElements()); assertThat(fields).isNotEmpty(); for (VariableElement field : fields) { String fieldName = field.getSimpleName().toString(); boolean expectUnchecked; if (fieldName.endsWith("Yes")) { expectUnchecked = true; } else if (fieldName.endsWith("No")) { expectUnchecked = false; } else { throw new AssertionError("Fields in Erasure class must end with Yes or No: " + fieldName); } TypeMirror fieldType = field.asType(); boolean actualUnchecked = TypeSimplifier.isCastingUnchecked(fieldType); assertWithMessage("Unchecked-cast status for " + fieldType) .that(actualUnchecked) .isEqualTo(expectUnchecked); } }
SimpleValueType { public static SimpleValueType create( @Nullable String string, int integer, Map<String, Long> map) { return new AutoValue_SimpleValueType(string, integer, map); } @Nullable abstract String string(); abstract int integer(); abstract Map<String, Long> map(); static SimpleValueType create( @Nullable String string, int integer, Map<String, Long> map); }
@Test public void testNestedValueType() { ImmutableMap<Integer, String> numberNames = ImmutableMap.of(1, "un", 2, "deux"); NestedValueType.Nested nested = NestedValueType.Nested.create(numberNames); assertEquals(numberNames, nested.numberNames()); }
PackagelessValueType { public static PackagelessValueType create( @Nullable String string, int integer, Map<String, Long> map) { return new AutoValue_PackagelessValueType(string, integer, map); } @Nullable abstract String string(); abstract int integer(); abstract Map<String, Long> map(); static PackagelessValueType create( @Nullable String string, int integer, Map<String, Long> map); }
@Test public void testNestedValueType() { ImmutableMap<Integer, String> numberNames = ImmutableMap.of(1, "un", 2, "deux"); PackagelessNestedValueType.Nested nested = PackagelessNestedValueType.Nested.create(numberNames); assertEquals(numberNames, nested.numberNames()); }
SuperficialValidation { public static boolean validateElement(Element element) { return element.accept(ELEMENT_VALIDATING_VISITOR, null); } private SuperficialValidation(); static boolean validateElements(Iterable<? extends Element> elements); static boolean validateElement(Element element); static boolean validateType(TypeMirror type); }
@Test public void missingReturnType() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "abstract class TestClass {", " abstract MissingType blah();", "}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void missingGenericReturnType() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "abstract class TestClass {", " abstract MissingType<?> blah();", "}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void missingReturnTypeTypeParameter() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import java.util.Map;", "import java.util.Set;", "", "abstract class TestClass {", " abstract Map<Set<?>, MissingType<?>> blah();", "}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void missingTypeParameter() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "class TestClass<T extends MissingType> {}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void missingParameterType() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "abstract class TestClass {", " abstract void foo(MissingType x);", "}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void missingAnnotation() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "@MissingAnnotation", "class TestClass {}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void handlesRecursiveTypeParams() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "class TestClass<T extends Comparable<T>> {}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isTrue(); } }) .compilesWithoutError(); } @Test public void handlesRecursiveType() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "abstract class TestClass {", " abstract TestClass foo(TestClass x);", "}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isTrue(); } }) .compilesWithoutError(); } @Test public void missingWildcardBound() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "import java.util.Set;", "", "class TestClass {", " Set<? extends MissingType> extendsTest() {", " return null;", " }", "", " Set<? super MissingType> superTest() {", " return null;", " }", "}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void missingIntersection() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "class TestClass<T extends Number & Missing> {}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); } @Test public void invalidAnnotationValue() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines("test.Outer", "package test;", "", "final class Outer {", " @interface TestAnnotation {", " Class[] classes();", " }", "", " @TestAnnotation(classes = Foo)", " static class TestClass {}", "}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith( new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.Outer.TestClass"); assertWithMessage("testClassElement is valid") .that(SuperficialValidation.validateElement(testClassElement)) .isFalse(); } }) .failsToCompile(); }
BasicAnnotationProcessor extends AbstractProcessor { protected static Step asStep(ProcessingStep processingStep) { return new ProcessingStepAsStep(processingStep); } @Override final synchronized void init(ProcessingEnvironment processingEnv); @Override final ImmutableSet<String> getSupportedAnnotationTypes(); @Override final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv); }
@Test public void processingStepAsStepAnnotationsNamesMatchClasses() { Step step = BasicAnnotationProcessor.asStep(new MultiAnnotationProcessingStep()); assertThat(step.annotations()) .containsExactly( AnAnnotation.class.getCanonicalName(), ReferencesAClass.class.getCanonicalName()); }
MoreElements { public static PackageElement getPackage(Element element) { while (element.getKind() != PACKAGE) { element = element.getEnclosingElement(); } return (PackageElement) element; } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void getPackage() { assertThat(MoreElements.getPackage(stringElement)).isEqualTo(javaLangPackageElement); for (Element childElement : stringElement.getEnclosedElements()) { assertThat(MoreElements.getPackage(childElement)).isEqualTo(javaLangPackageElement); } }
MoreElements { public static PackageElement asPackage(Element element) { return element.accept(PackageElementVisitor.INSTANCE, null); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void asPackage() { assertThat(MoreElements.asPackage(javaLangPackageElement)) .isEqualTo(javaLangPackageElement); } @Test public void asPackage_illegalArgument() { try { MoreElements.asPackage(stringElement); fail(); } catch (IllegalArgumentException expected) {} }
MoreElements { public static TypeParameterElement asTypeParameter(Element element) { return element.accept(TypeParameterElementVisitor.INSTANCE, null); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void asTypeParameterElement() { Element typeParameterElement = getOnlyElement( compilation .getElements() .getTypeElement(List.class.getCanonicalName()) .getTypeParameters()); assertThat(MoreElements.asTypeParameter(typeParameterElement)).isEqualTo(typeParameterElement); } @Test public void asTypeParameterElement_illegalArgument() { try { MoreElements.asTypeParameter(javaLangPackageElement); fail(); } catch (IllegalArgumentException expected) { } }
MoreElements { public static TypeElement asType(Element element) { return element.accept(TypeElementVisitor.INSTANCE, null); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void asType() { assertThat(MoreElements.asType(stringElement)).isEqualTo(stringElement); }
MoreElements { public static VariableElement asVariable(Element element) { return element.accept(VariableElementVisitor.INSTANCE, null); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void asVariable() { for (Element variableElement : ElementFilter.fieldsIn(stringElement.getEnclosedElements())) { assertThat(MoreElements.asVariable(variableElement)).isEqualTo(variableElement); } } @Test public void asVariable_illegalArgument() { try { MoreElements.asVariable(javaLangPackageElement); fail(); } catch (IllegalArgumentException expected) {} }
MoreElements { public static ExecutableElement asExecutable(Element element) { return element.accept(ExecutableElementVisitor.INSTANCE, null); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void asExecutable() { for (Element methodElement : ElementFilter.methodsIn(stringElement.getEnclosedElements())) { assertThat(MoreElements.asExecutable(methodElement)).isEqualTo(methodElement); } for (Element methodElement : ElementFilter.constructorsIn(stringElement.getEnclosedElements())) { assertThat(MoreElements.asExecutable(methodElement)).isEqualTo(methodElement); } } @Test public void asExecutable_illegalArgument() { try { MoreElements.asExecutable(javaLangPackageElement); fail(); } catch (IllegalArgumentException expected) {} }
MoreElements { public static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass) { return getAnnotationMirror(element, annotationClass).isPresent(); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void isAnnotationPresent() { TypeElement annotatedAnnotationElement = compilation.getElements().getTypeElement(AnnotatedAnnotation.class.getCanonicalName()); assertThat(MoreElements.isAnnotationPresent(annotatedAnnotationElement, Documented.class)) .isTrue(); assertThat(MoreElements.isAnnotationPresent(annotatedAnnotationElement, InnerAnnotation.class)) .isTrue(); assertThat(MoreElements.isAnnotationPresent(annotatedAnnotationElement, SuppressWarnings.class)) .isFalse(); }
MoreElements { public static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass) { String annotationClassName = annotationClass.getCanonicalName(); for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { TypeElement annotationTypeElement = asType(annotationMirror.getAnnotationType().asElement()); if (annotationTypeElement.getQualifiedName().contentEquals(annotationClassName)) { return Optional.of(annotationMirror); } } return Optional.absent(); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void getAnnotationMirror() { TypeElement element = compilation.getElements().getTypeElement(AnnotatedAnnotation.class.getCanonicalName()); Optional<AnnotationMirror> documented = MoreElements.getAnnotationMirror(element, Documented.class); Optional<AnnotationMirror> innerAnnotation = MoreElements.getAnnotationMirror(element, InnerAnnotation.class); Optional<AnnotationMirror> suppressWarnings = MoreElements.getAnnotationMirror(element, SuppressWarnings.class); expect.that(documented).isPresent(); expect.that(innerAnnotation).isPresent(); expect.that(suppressWarnings).isAbsent(); Element annotationElement = documented.get().getAnnotationType().asElement(); expect.that(MoreElements.isType(annotationElement)).isTrue(); expect.that(MoreElements.asType(annotationElement).getQualifiedName().toString()) .isEqualTo(Documented.class.getCanonicalName()); annotationElement = innerAnnotation.get().getAnnotationType().asElement(); expect.that(MoreElements.isType(annotationElement)).isTrue(); expect.that(MoreElements.asType(annotationElement).getQualifiedName().toString()) .isEqualTo(InnerAnnotation.class.getCanonicalName()); }
MoreElements { @Deprecated public static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils) { Overrides overrides = new Overrides.NativeOverrides(elementUtils); return getLocalAndInheritedMethods(type, overrides); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void getLocalAndInheritedMethods_Old() { Elements elements = compilation.getElements(); Types types = compilation.getTypes(); TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT); TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG); TypeElement childType = elements.getTypeElement(Child.class.getCanonicalName()); @SuppressWarnings("deprecation") Set<ExecutableElement> childTypeMethods = MoreElements.getLocalAndInheritedMethods(childType, elements); Set<ExecutableElement> objectMethods = visibleMethodsFromObject(); assertThat(childTypeMethods).containsAtLeastElementsIn(objectMethods); Set<ExecutableElement> nonObjectMethods = Sets.difference(childTypeMethods, objectMethods); assertThat(nonObjectMethods).containsExactly( getMethod(ParentInterface.class, "bar", longMirror), getMethod(ParentClass.class, "foo"), getMethod(Child.class, "bar"), getMethod(Child.class, "baz"), getMethod(Child.class, "buh", intMirror), getMethod(Child.class, "buh", intMirror, intMirror)) .inOrder();; } @Test public void getLocalAndInheritedMethods() { Elements elements = compilation.getElements(); Types types = compilation.getTypes(); TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT); TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG); TypeElement childType = elements.getTypeElement(Child.class.getCanonicalName()); @SuppressWarnings("deprecation") Set<ExecutableElement> childTypeMethods = MoreElements.getLocalAndInheritedMethods(childType, types, elements); Set<ExecutableElement> objectMethods = visibleMethodsFromObject(); assertThat(childTypeMethods).containsAtLeastElementsIn(objectMethods); Set<ExecutableElement> nonObjectMethods = Sets.difference(childTypeMethods, objectMethods); assertThat(nonObjectMethods).containsExactly( getMethod(ParentInterface.class, "bar", longMirror), getMethod(ParentClass.class, "foo"), getMethod(Child.class, "bar"), getMethod(Child.class, "baz"), getMethod(Child.class, "buh", intMirror), getMethod(Child.class, "buh", intMirror, intMirror)) .inOrder(); } @Test public void getLocalAndInheritedMethods_DaggerBug() { Elements elementUtils = compilation.getElements(); TypeElement main = elementUtils.getTypeElement(Main.ParentComponent.class.getCanonicalName()); Set<ExecutableElement> methods = MoreElements.getLocalAndInheritedMethods( main, compilation.getTypes(), elementUtils); assertThat(methods).hasSize(1); ExecutableElement method = methods.iterator().next(); assertThat(method.getSimpleName().toString()).isEqualTo("injectable"); assertThat(method.getParameters()).isEmpty(); } @Test public void getLocalAndInheritedMethods_AbstractList() { Elements elements = compilation.getElements(); TypeElement abstractType = elements.getTypeElement(AbstractAbstractList.class.getCanonicalName()); Set<ExecutableElement> abstractTypeMethods = MoreElements.getLocalAndInheritedMethods(abstractType, elements); assertThat(abstractMethodNamesFrom(abstractTypeMethods)).containsExactly("get", "size"); TypeElement concreteType = elements.getTypeElement(ConcreteAbstractList.class.getCanonicalName()); Set<ExecutableElement> concreteTypeMethods = MoreElements.getLocalAndInheritedMethods(concreteType, elements); assertThat(abstractMethodNamesFrom(concreteTypeMethods)).isEmpty(); }
MoreElements { public static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils) { return getAllMethods(type, new ExplicitOverrides(typeUtils)); } private MoreElements(); static PackageElement getPackage(Element element); static PackageElement asPackage(Element element); static boolean isType(Element element); static TypeElement asType(Element element); static TypeParameterElement asTypeParameter(Element element); static VariableElement asVariable(Element element); static ExecutableElement asExecutable(Element element); static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass); static Optional<AnnotationMirror> getAnnotationMirror(Element element, Class<? extends Annotation> annotationClass); static Predicate<T> hasModifiers(Modifier... modifiers); static Predicate<T> hasModifiers(final Set<Modifier> modifiers); @Deprecated static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils); static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils); static boolean overrides( ExecutableElement overrider, ExecutableElement overridden, TypeElement type, Types typeUtils); static ImmutableSet<ExecutableElement> getAllMethods( TypeElement type, Types typeUtils, Elements elementUtils); }
@Test public void getAllMethods() { Elements elements = compilation.getElements(); Types types = compilation.getTypes(); TypeMirror intMirror = types.getPrimitiveType(TypeKind.INT); TypeMirror longMirror = types.getPrimitiveType(TypeKind.LONG); TypeElement childType = elements.getTypeElement(Child.class.getCanonicalName()); @SuppressWarnings("deprecation") Set<ExecutableElement> childTypeMethods = MoreElements.getAllMethods(childType, types, elements); Set<ExecutableElement> objectMethods = allMethodsFromObject(); assertThat(childTypeMethods).containsAtLeastElementsIn(objectMethods); Set<ExecutableElement> nonObjectMethods = Sets.difference(childTypeMethods, objectMethods); assertThat(nonObjectMethods).containsExactly( getMethod(ParentInterface.class, "staticMethod"), getMethod(ParentInterface.class, "bar", longMirror), getMethod(ParentClass.class, "staticMethod"), getMethod(ParentClass.class, "foo"), getMethod(ParentClass.class, "privateMethod"), getMethod(Child.class, "staticMethod"), getMethod(Child.class, "bar"), getMethod(Child.class, "baz"), getMethod(Child.class, "buh", intMirror), getMethod(Child.class, "buh", intMirror, intMirror)) .inOrder(); }
MoreTypes { public static Equivalence<TypeMirror> equivalence() { return TypeEquivalence.INSTANCE; } private MoreTypes(); static Equivalence<TypeMirror> equivalence(); static ImmutableSet<TypeElement> referencedTypes(TypeMirror type); static Element asElement(TypeMirror typeMirror); static TypeElement asTypeElement(TypeMirror mirror); static ImmutableSet<TypeElement> asTypeElements(Iterable<? extends TypeMirror> mirrors); static ArrayType asArray(TypeMirror maybeArrayType); static DeclaredType asDeclared(TypeMirror maybeDeclaredType); static ErrorType asError(TypeMirror maybeErrorType); static ExecutableType asExecutable(TypeMirror maybeExecutableType); static IntersectionType asIntersection(TypeMirror maybeIntersectionType); static NoType asNoType(TypeMirror maybeNoType); static NullType asNullType(TypeMirror maybeNullType); static PrimitiveType asPrimitiveType(TypeMirror maybePrimitiveType); static TypeVariable asTypeVariable(TypeMirror maybeTypeVariable); static WildcardType asWildcard(TypeMirror maybeWildcardType); static boolean isType(TypeMirror type); static boolean isTypeOf(final Class<?> clazz, TypeMirror type); static Optional<DeclaredType> nonObjectSuperclass(Types types, Elements elements, DeclaredType type); static TypeMirror asMemberOf(Types types, DeclaredType container, VariableElement variable); static boolean isConversionFromObjectUnchecked(TypeMirror type); }
@Test public void equivalence() { Types types = compilationRule.getTypes(); Elements elements = compilationRule.getElements(); TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType(); TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType(); TypeElement mapElement = elements.getTypeElement(Map.class.getCanonicalName()); TypeElement setElement = elements.getTypeElement(Set.class.getCanonicalName()); TypeElement enumElement = elements.getTypeElement(Enum.class.getCanonicalName()); TypeElement container = elements.getTypeElement(Container.class.getCanonicalName()); TypeElement contained = elements.getTypeElement(Container.Contained.class.getCanonicalName()); TypeElement funkyBounds = elements.getTypeElement(FunkyBounds.class.getCanonicalName()); TypeElement funkyBounds2 = elements.getTypeElement(FunkyBounds2.class.getCanonicalName()); TypeElement funkierBounds = elements.getTypeElement(FunkierBounds.class.getCanonicalName()); TypeMirror funkyBoundsVar = ((DeclaredType) funkyBounds.asType()).getTypeArguments().get(0); TypeMirror funkyBounds2Var = ((DeclaredType) funkyBounds2.asType()).getTypeArguments().get(0); TypeMirror funkierBoundsVar = ((DeclaredType) funkierBounds.asType()).getTypeArguments().get(0); DeclaredType mapOfObjectToObjectType = types.getDeclaredType(mapElement, objectType, objectType); TypeMirror mapType = mapElement.asType(); DeclaredType setOfSetOfObject = types.getDeclaredType(setElement, types.getDeclaredType(setElement, objectType)); DeclaredType setOfSetOfString = types.getDeclaredType(setElement, types.getDeclaredType(setElement, stringType)); DeclaredType setOfSetOfSetOfObject = types.getDeclaredType(setElement, setOfSetOfObject); DeclaredType setOfSetOfSetOfString = types.getDeclaredType(setElement, setOfSetOfString); WildcardType wildcard = types.getWildcardType(null, null); DeclaredType containerOfObject = types.getDeclaredType(container, objectType); DeclaredType containerOfString = types.getDeclaredType(container, stringType); TypeMirror containedInObject = types.asMemberOf(containerOfObject, contained); TypeMirror containedInString = types.asMemberOf(containerOfString, contained); EquivalenceTester<TypeMirror> tester = EquivalenceTester.<TypeMirror>of(MoreTypes.equivalence()) .addEquivalenceGroup(types.getNullType()) .addEquivalenceGroup(types.getNoType(NONE)) .addEquivalenceGroup(types.getNoType(VOID)) .addEquivalenceGroup(objectType) .addEquivalenceGroup(stringType) .addEquivalenceGroup(containedInObject) .addEquivalenceGroup(containedInString) .addEquivalenceGroup(funkyBounds.asType()) .addEquivalenceGroup(funkyBounds2.asType()) .addEquivalenceGroup(funkierBounds.asType()) .addEquivalenceGroup(funkyBoundsVar, funkyBounds2Var) .addEquivalenceGroup(funkierBoundsVar) .addEquivalenceGroup(enumElement.asType()) .addEquivalenceGroup(mapType) .addEquivalenceGroup(mapOfObjectToObjectType) .addEquivalenceGroup(types.getDeclaredType(mapElement, wildcard, wildcard)) .addEquivalenceGroup(types.erasure(mapType), types.erasure(mapOfObjectToObjectType)) .addEquivalenceGroup(types.getDeclaredType(mapElement, objectType, stringType)) .addEquivalenceGroup(types.getDeclaredType(mapElement, stringType, objectType)) .addEquivalenceGroup(types.getDeclaredType(mapElement, stringType, stringType)) .addEquivalenceGroup(setOfSetOfObject) .addEquivalenceGroup(setOfSetOfString) .addEquivalenceGroup(setOfSetOfSetOfObject) .addEquivalenceGroup(setOfSetOfSetOfString) .addEquivalenceGroup(wildcard) .addEquivalenceGroup(types.getWildcardType(objectType, null)) .addEquivalenceGroup(types.getWildcardType(stringType, null)) .addEquivalenceGroup(types.getWildcardType(null, stringType)) .addEquivalenceGroup(types.getDeclaredType(mapElement, stringType, types.getDeclaredType(mapElement, stringType, types.getDeclaredType(setElement, objectType)))) .addEquivalenceGroup(FAKE_ERROR_TYPE) ; for (TypeKind kind : TypeKind.values()) { if (kind.isPrimitive()) { PrimitiveType primitiveType = types.getPrimitiveType(kind); TypeMirror boxedPrimitiveType = types.boxedClass(primitiveType).asType(); tester.addEquivalenceGroup(primitiveType, types.unboxedType(boxedPrimitiveType)); tester.addEquivalenceGroup(boxedPrimitiveType); tester.addEquivalenceGroup(types.getArrayType(primitiveType)); tester.addEquivalenceGroup(types.getArrayType(boxedPrimitiveType)); } } ImmutableSet<Class<?>> testClasses = ImmutableSet.of( ExecutableElementsGroupA.class, ExecutableElementsGroupB.class, ExecutableElementsGroupC.class, ExecutableElementsGroupD.class, ExecutableElementsGroupE.class); for (Class<?> testClass : testClasses) { ImmutableList<TypeMirror> equivalenceGroup = FluentIterable.from( elements.getTypeElement(testClass.getCanonicalName()).getEnclosedElements()) .transform(new Function<Element, TypeMirror>() { @Override public TypeMirror apply(Element input) { return input.asType(); } }) .toList(); tester.addEquivalenceGroup(equivalenceGroup); } tester.test(); }
MoreTypes { public static ImmutableSet<TypeElement> referencedTypes(TypeMirror type) { checkNotNull(type); ImmutableSet.Builder<TypeElement> elements = ImmutableSet.builder(); type.accept(ReferencedTypes.INSTANCE, elements); return elements.build(); } private MoreTypes(); static Equivalence<TypeMirror> equivalence(); static ImmutableSet<TypeElement> referencedTypes(TypeMirror type); static Element asElement(TypeMirror typeMirror); static TypeElement asTypeElement(TypeMirror mirror); static ImmutableSet<TypeElement> asTypeElements(Iterable<? extends TypeMirror> mirrors); static ArrayType asArray(TypeMirror maybeArrayType); static DeclaredType asDeclared(TypeMirror maybeDeclaredType); static ErrorType asError(TypeMirror maybeErrorType); static ExecutableType asExecutable(TypeMirror maybeExecutableType); static IntersectionType asIntersection(TypeMirror maybeIntersectionType); static NoType asNoType(TypeMirror maybeNoType); static NullType asNullType(TypeMirror maybeNullType); static PrimitiveType asPrimitiveType(TypeMirror maybePrimitiveType); static TypeVariable asTypeVariable(TypeMirror maybeTypeVariable); static WildcardType asWildcard(TypeMirror maybeWildcardType); static boolean isType(TypeMirror type); static boolean isTypeOf(final Class<?> clazz, TypeMirror type); static Optional<DeclaredType> nonObjectSuperclass(Types types, Elements elements, DeclaredType type); static TypeMirror asMemberOf(Types types, DeclaredType container, VariableElement variable); static boolean isConversionFromObjectUnchecked(TypeMirror type); }
@Test public void testReferencedTypes() { Elements elements = compilationRule.getElements(); TypeElement testDataElement = elements .getTypeElement(ReferencedTypesTestData.class.getCanonicalName()); ImmutableMap<String, VariableElement> fieldIndex = FluentIterable.from(ElementFilter.fieldsIn(testDataElement.getEnclosedElements())) .uniqueIndex(new Function<VariableElement, String>() { @Override public String apply(VariableElement input) { return input.getSimpleName().toString(); } }); TypeElement objectElement = elements.getTypeElement(Object.class.getCanonicalName()); TypeElement stringElement = elements.getTypeElement(String.class.getCanonicalName()); TypeElement integerElement = elements.getTypeElement(Integer.class.getCanonicalName()); TypeElement setElement = elements.getTypeElement(Set.class.getCanonicalName()); TypeElement mapElement = elements.getTypeElement(Map.class.getCanonicalName()); TypeElement charSequenceElement = elements.getTypeElement(CharSequence.class.getCanonicalName()); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f1").asType())) .containsExactly(objectElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f2").asType())) .containsExactly(setElement, stringElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f3").asType())) .containsExactly(mapElement, stringElement, objectElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f4").asType())) .containsExactly(integerElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f5").asType())) .containsExactly(setElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f6").asType())) .containsExactly(setElement, charSequenceElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f7").asType())) .containsExactly(mapElement, stringElement, setElement, charSequenceElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f8").asType())) .containsExactly(stringElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f9").asType())) .containsExactly(stringElement); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f10").asType())).isEmpty(); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f11").asType())).isEmpty(); assertThat(MoreTypes.referencedTypes(fieldIndex.get("f12").asType())) .containsExactly(setElement, stringElement); }
MoreTypes { public static Element asElement(TypeMirror typeMirror) { return typeMirror.accept(AsElementVisitor.INSTANCE, null); } private MoreTypes(); static Equivalence<TypeMirror> equivalence(); static ImmutableSet<TypeElement> referencedTypes(TypeMirror type); static Element asElement(TypeMirror typeMirror); static TypeElement asTypeElement(TypeMirror mirror); static ImmutableSet<TypeElement> asTypeElements(Iterable<? extends TypeMirror> mirrors); static ArrayType asArray(TypeMirror maybeArrayType); static DeclaredType asDeclared(TypeMirror maybeDeclaredType); static ErrorType asError(TypeMirror maybeErrorType); static ExecutableType asExecutable(TypeMirror maybeExecutableType); static IntersectionType asIntersection(TypeMirror maybeIntersectionType); static NoType asNoType(TypeMirror maybeNoType); static NullType asNullType(TypeMirror maybeNullType); static PrimitiveType asPrimitiveType(TypeMirror maybePrimitiveType); static TypeVariable asTypeVariable(TypeMirror maybeTypeVariable); static WildcardType asWildcard(TypeMirror maybeWildcardType); static boolean isType(TypeMirror type); static boolean isTypeOf(final Class<?> clazz, TypeMirror type); static Optional<DeclaredType> nonObjectSuperclass(Types types, Elements elements, DeclaredType type); static TypeMirror asMemberOf(Types types, DeclaredType container, VariableElement variable); static boolean isConversionFromObjectUnchecked(TypeMirror type); }
@Test public void asElement_throws() { TypeMirror javaDotLang = compilationRule.getElements().getPackageElement("java.lang").asType(); try { MoreTypes.asElement(javaDotLang); fail(); } catch (IllegalArgumentException expected) {} } @Test public void asElement() { Elements elements = compilationRule.getElements(); TypeElement stringElement = elements.getTypeElement("java.lang.String"); assertThat(MoreTypes.asElement(stringElement.asType())).isEqualTo(stringElement); TypeParameterElement setParameterElement = Iterables.getOnlyElement( compilationRule.getElements().getTypeElement("java.util.Set").getTypeParameters()); assertThat(MoreTypes.asElement(setParameterElement.asType())).isEqualTo(setParameterElement); }
MoreTypes { public static Optional<DeclaredType> nonObjectSuperclass(Types types, Elements elements, DeclaredType type) { checkNotNull(types); checkNotNull(elements); checkNotNull(type); TypeMirror superclassType = asTypeElement(type).getSuperclass(); if (!isType(superclassType)) { return Optional.absent(); } DeclaredType superclass = asDeclared(superclassType); if (isObjectType(superclass)) { return Optional.absent(); } if (superclass.getTypeArguments().isEmpty()) { return Optional.of(superclass); } return Optional.of(asDeclared(types.directSupertypes(type).get(0))); } private MoreTypes(); static Equivalence<TypeMirror> equivalence(); static ImmutableSet<TypeElement> referencedTypes(TypeMirror type); static Element asElement(TypeMirror typeMirror); static TypeElement asTypeElement(TypeMirror mirror); static ImmutableSet<TypeElement> asTypeElements(Iterable<? extends TypeMirror> mirrors); static ArrayType asArray(TypeMirror maybeArrayType); static DeclaredType asDeclared(TypeMirror maybeDeclaredType); static ErrorType asError(TypeMirror maybeErrorType); static ExecutableType asExecutable(TypeMirror maybeExecutableType); static IntersectionType asIntersection(TypeMirror maybeIntersectionType); static NoType asNoType(TypeMirror maybeNoType); static NullType asNullType(TypeMirror maybeNullType); static PrimitiveType asPrimitiveType(TypeMirror maybePrimitiveType); static TypeVariable asTypeVariable(TypeMirror maybeTypeVariable); static WildcardType asWildcard(TypeMirror maybeWildcardType); static boolean isType(TypeMirror type); static boolean isTypeOf(final Class<?> clazz, TypeMirror type); static Optional<DeclaredType> nonObjectSuperclass(Types types, Elements elements, DeclaredType type); static TypeMirror asMemberOf(Types types, DeclaredType container, VariableElement variable); static boolean isConversionFromObjectUnchecked(TypeMirror type); }
@Test public void testNonObjectSuperclass() { Types types = compilationRule.getTypes(); Elements elements = compilationRule.getElements(); TypeMirror numberType = elements.getTypeElement(Number.class.getCanonicalName()).asType(); TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType(); TypeMirror integerType = elements.getTypeElement(Integer.class.getCanonicalName()).asType(); TypeElement parent = elements.getTypeElement(Parent.class.getCanonicalName()); TypeElement childA = elements.getTypeElement(ChildA.class.getCanonicalName()); TypeElement childB = elements.getTypeElement(ChildB.class.getCanonicalName()); TypeElement genericChild = elements.getTypeElement(GenericChild.class.getCanonicalName()); TypeMirror genericChildOfNumber = types.getDeclaredType(genericChild, numberType); TypeMirror genericChildOfInteger = types.getDeclaredType(genericChild, integerType); TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType(); TypeMirror interfaceType = elements.getTypeElement(InterfaceType.class.getCanonicalName()).asType(); assertThat(MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) objectType)) .isAbsent(); assertThat(MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) interfaceType)) .isAbsent(); assertThat(MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) parent.asType())) .isAbsent(); Optional<DeclaredType> parentOfChildA = MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) childA.asType()); Optional<DeclaredType> parentOfChildB = MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) childB.asType()); Optional<DeclaredType> parentOfGenericChild = MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) genericChild.asType()); Optional<DeclaredType> parentOfGenericChildOfNumber = MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) genericChildOfNumber); Optional<DeclaredType> parentOfGenericChildOfInteger = MoreTypes.nonObjectSuperclass(types, elements, (DeclaredType) genericChildOfInteger); EquivalenceTester<TypeMirror> tester = EquivalenceTester.<TypeMirror>of(MoreTypes.equivalence()) .addEquivalenceGroup(parentOfChildA.get(), types.getDeclaredType(parent, numberType), parentOfGenericChildOfNumber.get()) .addEquivalenceGroup(parentOfChildB.get(), types.getDeclaredType(parent, stringType)) .addEquivalenceGroup(parentOfGenericChild.get(), parent.asType()) .addEquivalenceGroup(parentOfGenericChildOfInteger.get(), types.getDeclaredType(parent, integerType)); tester.test(); }
MoreTypes { public static boolean isConversionFromObjectUnchecked(TypeMirror type) { return new CastingUncheckedVisitor().visit(type, null); } private MoreTypes(); static Equivalence<TypeMirror> equivalence(); static ImmutableSet<TypeElement> referencedTypes(TypeMirror type); static Element asElement(TypeMirror typeMirror); static TypeElement asTypeElement(TypeMirror mirror); static ImmutableSet<TypeElement> asTypeElements(Iterable<? extends TypeMirror> mirrors); static ArrayType asArray(TypeMirror maybeArrayType); static DeclaredType asDeclared(TypeMirror maybeDeclaredType); static ErrorType asError(TypeMirror maybeErrorType); static ExecutableType asExecutable(TypeMirror maybeExecutableType); static IntersectionType asIntersection(TypeMirror maybeIntersectionType); static NoType asNoType(TypeMirror maybeNoType); static NullType asNullType(TypeMirror maybeNullType); static PrimitiveType asPrimitiveType(TypeMirror maybePrimitiveType); static TypeVariable asTypeVariable(TypeMirror maybeTypeVariable); static WildcardType asWildcard(TypeMirror maybeWildcardType); static boolean isType(TypeMirror type); static boolean isTypeOf(final Class<?> clazz, TypeMirror type); static Optional<DeclaredType> nonObjectSuperclass(Types types, Elements elements, DeclaredType type); static TypeMirror asMemberOf(Types types, DeclaredType container, VariableElement variable); static boolean isConversionFromObjectUnchecked(TypeMirror type); }
@Test public void testIsConversionFromObjectUnchecked_yes() { Elements elements = compilationRule.getElements(); TypeElement unchecked = elements.getTypeElement(Unchecked.class.getCanonicalName()); for (VariableElement field : ElementFilter.fieldsIn(unchecked.getEnclosedElements())) { TypeMirror type = field.asType(); expect .withMessage("Casting to %s is unchecked", type) .that(MoreTypes.isConversionFromObjectUnchecked(type)) .isTrue(); } } @Test public void testIsConversionFromObjectUnchecked_no() { Elements elements = compilationRule.getElements(); TypeElement notUnchecked = elements.getTypeElement(NotUnchecked.class.getCanonicalName()); for (VariableElement field : ElementFilter.fieldsIn(notUnchecked.getEnclosedElements())) { TypeMirror type = field.asType(); expect .withMessage("Casting to %s is not unchecked", type) .that(MoreTypes.isConversionFromObjectUnchecked(type)) .isFalse(); } }
SimpleTypeAnnotationValue implements AnnotationValue { public static AnnotationValue of(TypeMirror value) { return new SimpleTypeAnnotationValue(value); } private SimpleTypeAnnotationValue(TypeMirror value); static AnnotationValue of(TypeMirror value); @Override TypeMirror getValue(); @Override String toString(); @Override R accept(AnnotationValueVisitor<R, P> visitor, P parameter); }
@Test public void arrays() { SimpleTypeAnnotationValue.of(types.getArrayType(objectType)); SimpleTypeAnnotationValue.of(types.getArrayType(primitiveType)); } @Test public void declaredType() { SimpleTypeAnnotationValue.of(objectType); } @Test public void parameterizedType() { try { SimpleTypeAnnotationValue.of( types.getDeclaredType( elements.getTypeElement(List.class.getCanonicalName()), objectType)); fail("Expected an exception"); } catch (IllegalArgumentException expected) { } }
SimpleAnnotationMirror implements AnnotationMirror { public static AnnotationMirror of(TypeElement annotationType) { return of(annotationType, ImmutableMap.of()); } private SimpleAnnotationMirror( TypeElement annotationType, Map<String, ? extends AnnotationValue> namedValues); static AnnotationMirror of(TypeElement annotationType); static AnnotationMirror of( TypeElement annotationType, Map<String, ? extends AnnotationValue> namedValues); @Override DeclaredType getAnnotationType(); @Override Map<ExecutableElement, ? extends AnnotationValue> getElementValues(); @Override String toString(); @Override boolean equals(Object other); @Override int hashCode(); }
@Test public void extraValues() { TypeElement multipleValues = getTypeElement(MultipleValues.class); Map<String, AnnotationValue> values = new HashMap<>(); values.put("value1", intValue(1)); values.put("value2", intValue(2)); values.put("value3", intValue(3)); expectThrows(() -> SimpleAnnotationMirror.of(multipleValues, values)); } @Test public void missingValues() { TypeElement multipleValues = getTypeElement(MultipleValues.class); expectThrows(() -> SimpleAnnotationMirror.of(multipleValues)); } @Test public void notAnAnnotation() { TypeElement stringElement = getTypeElement(String.class); expectThrows(() -> SimpleAnnotationMirror.of(stringElement)); }
AnnotationMirrors { public static Equivalence<AnnotationMirror> equivalence() { return ANNOTATION_MIRROR_EQUIVALENCE; } private AnnotationMirrors(); static Equivalence<AnnotationMirror> equivalence(); static ImmutableMap<ExecutableElement, AnnotationValue> getAnnotationValuesWithDefaults( AnnotationMirror annotation); static AnnotationValue getAnnotationValue( AnnotationMirror annotationMirror, String elementName); static Map.Entry<ExecutableElement, AnnotationValue> getAnnotationElementAndValue( AnnotationMirror annotationMirror, final String elementName); static ImmutableSet<? extends AnnotationMirror> getAnnotatedAnnotations(Element element, final Class<? extends Annotation> annotationType); }
@Test public void testEquivalences() { EquivalenceTester<AnnotationMirror> tester = EquivalenceTester.of(AnnotationMirrors.equivalence()); tester.addEquivalenceGroup( annotationOn(SimplyAnnotated.class), annotationOn(AlsoSimplyAnnotated.class)); tester.addEquivalenceGroup( annotationOn(TestClassBlah.class), annotationOn(TestClassBlah2.class)); tester.addEquivalenceGroup( annotationOn(TestClassFoo.class)); tester.addEquivalenceGroup( annotationOn(TestWithDefaultingOuterDefault.class), annotationOn(TestWithDefaultingOuterBlah.class)); tester.addEquivalenceGroup( annotationOn(TestWithDefaultingOuterFoo.class)); tester.addEquivalenceGroup( annotationOn(TestDefaultNestedAnnotated.class), annotationOn(TestBlahNestedAnnotated.class)); tester.addEquivalenceGroup( annotationOn(TestFooNestedAnnotated.class)); tester.addEquivalenceGroup( annotationOn(TestValueArrayWithDefault.class), annotationOn(TestValueArrayWithEmpty.class)); tester.addEquivalenceGroup( annotationOn(TestValueArrayWithOneDefault.class), annotationOn(TestValueArrayWithOneBlah.class)); tester.addEquivalenceGroup( annotationOn(TestValueArrayWithOneFoo.class)); tester.addEquivalenceGroup( annotationOn(TestValueArrayWithFooAndDefaultBlah.class), annotationOn(TestValueArrayWithFooBlah.class), annotationOn(TestValueArrayWithFooBlah2.class)); tester.addEquivalenceGroup( annotationOn(TestValueArrayWithBlahFoo.class)); tester.test(); }
AnnotationMirrors { public static ImmutableMap<ExecutableElement, AnnotationValue> getAnnotationValuesWithDefaults( AnnotationMirror annotation) { ImmutableMap.Builder<ExecutableElement, AnnotationValue> values = ImmutableMap.builder(); Map<? extends ExecutableElement, ? extends AnnotationValue> declaredValues = annotation.getElementValues(); for (ExecutableElement method : ElementFilter.methodsIn(annotation.getAnnotationType().asElement().getEnclosedElements())) { if (declaredValues.containsKey(method)) { values.put(method, declaredValues.get(method)); } else if (method.getDefaultValue() != null) { values.put(method, method.getDefaultValue()); } else { throw new IllegalStateException( "Unset annotation value without default should never happen: " + MoreElements.asType(method.getEnclosingElement()).getQualifiedName() + '.' + method.getSimpleName() + "()"); } } return values.build(); } private AnnotationMirrors(); static Equivalence<AnnotationMirror> equivalence(); static ImmutableMap<ExecutableElement, AnnotationValue> getAnnotationValuesWithDefaults( AnnotationMirror annotation); static AnnotationValue getAnnotationValue( AnnotationMirror annotationMirror, String elementName); static Map.Entry<ExecutableElement, AnnotationValue> getAnnotationElementAndValue( AnnotationMirror annotationMirror, final String elementName); static ImmutableSet<? extends AnnotationMirror> getAnnotatedAnnotations(Element element, final Class<? extends Annotation> annotationType); }
@Test public void testGetDefaultValuesUnset() { assertThat(annotationOn(StringyUnset.class).getElementValues()).isEmpty(); Iterable<AnnotationValue> values = AnnotationMirrors.getAnnotationValuesWithDefaults( annotationOn(StringyUnset.class)).values(); String value = getOnlyElement(values).accept(new SimpleAnnotationValueVisitor6<String, Void>() { @Override public String visitString(String value, Void ignored) { return value; } }, null); assertThat(value).isEqualTo("default"); } @Test public void testGetDefaultValuesSet() { Iterable<AnnotationValue> values = AnnotationMirrors.getAnnotationValuesWithDefaults( annotationOn(StringySet.class)).values(); String value = getOnlyElement(values).accept(new SimpleAnnotationValueVisitor6<String, Void>() { @Override public String visitString(String value, Void ignored) { return value; } }, null); assertThat(value).isEqualTo("foo"); }
AnnotationMirrors { public static AnnotationValue getAnnotationValue( AnnotationMirror annotationMirror, String elementName) { return getAnnotationElementAndValue(annotationMirror, elementName).getValue(); } private AnnotationMirrors(); static Equivalence<AnnotationMirror> equivalence(); static ImmutableMap<ExecutableElement, AnnotationValue> getAnnotationValuesWithDefaults( AnnotationMirror annotation); static AnnotationValue getAnnotationValue( AnnotationMirror annotationMirror, String elementName); static Map.Entry<ExecutableElement, AnnotationValue> getAnnotationElementAndValue( AnnotationMirror annotationMirror, final String elementName); static ImmutableSet<? extends AnnotationMirror> getAnnotatedAnnotations(Element element, final Class<? extends Annotation> annotationType); }
@Test public void testGetValueEntryFailure() { try { AnnotationMirrors.getAnnotationValue(annotationOn(TestClassBlah.class), "a"); } catch (IllegalArgumentException e) { assertThat(e) .hasMessageThat() .isEqualTo( "@com.google.auto.common.AnnotationMirrorsTest.Outer does not define an element a()"); return; } fail("Should have thrown."); }
AnnotationValues { public static DeclaredType getTypeMirror(AnnotationValue value) { return TypeMirrorVisitor.INSTANCE.visit(value); } private AnnotationValues(); static Equivalence<AnnotationValue> equivalence(); static DeclaredType getTypeMirror(AnnotationValue value); static AnnotationMirror getAnnotationMirror(AnnotationValue value); static VariableElement getEnum(AnnotationValue value); static String getString(AnnotationValue value); static int getInt(AnnotationValue value); static long getLong(AnnotationValue value); static byte getByte(AnnotationValue value); static short getShort(AnnotationValue value); static float getFloat(AnnotationValue value); static double getDouble(AnnotationValue value); static boolean getBoolean(AnnotationValue value); static char getChar(AnnotationValue value); static ImmutableList<DeclaredType> getTypeMirrors(AnnotationValue value); static ImmutableList<AnnotationMirror> getAnnotationMirrors(AnnotationValue value); static ImmutableList<VariableElement> getEnums(AnnotationValue value); static ImmutableList<String> getStrings(AnnotationValue value); static ImmutableList<Integer> getInts(AnnotationValue value); static ImmutableList<Long> getLongs(AnnotationValue value); static ImmutableList<Byte> getBytes(AnnotationValue value); static ImmutableList<Short> getShorts(AnnotationValue value); static ImmutableList<Float> getFloats(AnnotationValue value); static ImmutableList<Double> getDoubles(AnnotationValue value); static ImmutableList<Boolean> getBooleans(AnnotationValue value); static ImmutableList<Character> getChars(AnnotationValue value); static ImmutableList<AnnotationValue> getAnnotationValues(AnnotationValue value); }
@Test public void getTypeMirror() { TypeElement insideClassA = getTypeElement(InsideClassA.class); AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "classValue"); assertThat(AnnotationValues.getTypeMirror(value).asElement()).isEqualTo(insideClassA); } @Test public void getTypeMirrorGenericClass() { TypeElement genericClass = getTypeElement(GenericClass.class); AnnotationValue gvalue = AnnotationMirrors.getAnnotationValue(annotationMirror, "genericClassValue"); assertThat(AnnotationValues.getTypeMirror(gvalue).asElement()).isEqualTo(genericClass); }
BaseActionImpl { public BaseActionImpl() { } BaseActionImpl(); BaseActionImpl(InferenceConfigDefinition kpiDefinition); }
@Test public void testBaseActionImpl() { assertEquals("AVERAGE",ExecutionActions.AVERAGE.toString()); }
OfflineDataProcessingExecutor extends TimerTask { public Boolean executeCypherQuery(String cypherQuery, DataEnrichmentModel dataEnrichmentModel) { GraphDBHandler dbHandler = new GraphDBHandler(); int processedRecords = 1; int recordCount = 0; long queryExecutionStartTime = System.currentTimeMillis(); try { while (processedRecords > 0) { GraphResponse sprintResponse = dbHandler.executeCypherQuery(cypherQuery); JsonObject sprintResponseJson = sprintResponse.getJson(); try { processedRecords = sprintResponseJson.getAsJsonArray("results").get(0).getAsJsonObject() .getAsJsonArray("data").get(0).getAsJsonObject().getAsJsonArray("row").get(0).getAsInt(); } catch (UnsupportedOperationException | IllegalStateException | IndexOutOfBoundsException ex) { log.error(cypherQuery + " - query processing failed", ex); return Boolean.FALSE; } log.debug(" Processed " + processedRecords); recordCount = recordCount + processedRecords; } long queryExecutionEndTime = System.currentTimeMillis(); long queryProcessingTime = (queryExecutionEndTime - queryExecutionStartTime); if (dataEnrichmentModel != null) { dataEnrichmentModel.setRecordsProcessed(recordCount); dataEnrichmentModel.setQueryProcessingTime(queryProcessingTime); } } catch (InsightsCustomException e) { log.error(cypherQuery + " - query processing failed", e); return Boolean.FALSE; } return Boolean.TRUE; } @Override void run(); int executeOfflineProcessing(); Boolean hasJsonFileExtension(String fileName); Boolean processOfflineConfiguration(File jsonFile); DataEnrichmentModel updateLastExecutionTime(DataEnrichmentModel dataEnrichmentModel); Boolean executeCypherQuery(String cypherQuery, DataEnrichmentModel dataEnrichmentModel); Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule); }
@Test public void testExecuteCypherQuery() { String cypherQuery = "MATCH (n:ALM) where not exists (n.processed) with n limit 100 set n.processed=true return count(n)"; DataEnrichmentModel model = new DataEnrichmentModel(); Boolean resultFlag = executor.executeCypherQuery(cypherQuery, model); assertTrue(resultFlag); } @Test public void testExecuteCypherQueryNegative() { String cypherQuery = "MATCH (n:ALM) where not exists (n.processed) with n limit 100 set n.processed=true return n"; DataEnrichmentModel model = new DataEnrichmentModel(); Boolean resultFlag = executor.executeCypherQuery(cypherQuery, model); assertFalse(resultFlag); }
OfflineDataProcessingExecutor extends TimerTask { public Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule) { if (lastRunTime == null && (cronSchedule == null || cronSchedule.trim().length() == 0)) { return Boolean.TRUE; } ZonedDateTime dateTime = null; ZonedDateTime now = ZonedDateTime.now(InsightsUtils.zoneId); Long timeDifferenceInMinutes = null; if (lastRunTime != null && !lastRunTime.isEmpty()) { dateTime = ZonedDateTime.parse(lastRunTime, formatter); } if(cronSchedule != null && cronSchedule.trim().length() > 0) { try { CronExpression convert = new CronExpressionConverter().convert(cronSchedule); if(dateTime == null) { dateTime = now.minusDays(1); } Date cronDate = convert.getNextValidTimeAfter(Date.from(dateTime.toInstant())); if(cronDate.before(new Date())) { return Boolean.TRUE; } } catch (Exception e) { log.error("Unable to parse the CRON expression: "+cronSchedule, e); } }else { if (dateTime != null && now != null) { Duration d = Duration.between(dateTime, now); timeDifferenceInMinutes = d.abs().toMinutes(); } if (timeDifferenceInMinutes > runSchedule) { return Boolean.TRUE; } } return Boolean.FALSE; } @Override void run(); int executeOfflineProcessing(); Boolean hasJsonFileExtension(String fileName); Boolean processOfflineConfiguration(File jsonFile); DataEnrichmentModel updateLastExecutionTime(DataEnrichmentModel dataEnrichmentModel); Boolean executeCypherQuery(String cypherQuery, DataEnrichmentModel dataEnrichmentModel); Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule); }
@Test public void testIsQueryScheduledToRun() { Long runSchedule = 720L; String lastRunTime = "2018/07/16 05:50 PM"; assertTrue(executor.isQueryScheduledToRun(runSchedule, lastRunTime, null)); }
BaseActionImpl { protected String getEsQueryWithDates(JobSchedule schedule, String esQuery) { Long fromDate = InsightsUtils.getDataFromTime(schedule.name()); esQuery = esQuery.replace("__dataFromTime__", fromDate.toString()); Long toDate = InsightsUtils.getDataToTime(schedule.name()); esQuery = esQuery.replace("__dataToTime__", toDate.toString()); return esQuery; } BaseActionImpl(); BaseActionImpl(InferenceConfigDefinition kpiDefinition); }
@Test public void testGetEsQueryWithDates() { String esQuery = "query"; JobSchedule schedule = null; }
CountActionImpl extends BaseActionImpl { @Override protected void execute() throws InsightsJobFailedException { executeNeo4jGraphQuery(); } CountActionImpl(InferenceConfigDefinition kpiDefinition); }
@Test public void testExecute() { load(); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("Jobs", "Success"); }
MinMaxActionImpl extends BaseActionImpl { @Override protected void execute() throws InsightsJobFailedException { executeNeo4jGraphQuery(); } MinMaxActionImpl(InferenceConfigDefinition kpiDefinition); }
@Test public void testExecute() throws InsightsJobFailedException { load(); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("Jobs", "Success"); }
OfflineDataProcessingExecutor extends TimerTask { public int executeOfflineProcessing() { File queryFolderPath = new File(ConfigOptions.OFFLINE_DATA_PROCESSING_RESOLVED_PATH); File[] files = queryFolderPath.listFiles(); int jsonFileCount = 0; if (files == null) { return jsonFileCount; } for (File eachFile : files) { if (eachFile.isFile()) { String fileName = eachFile.getName(); if (hasJsonFileExtension(fileName)) { jsonFileCount++; processOfflineConfiguration(eachFile); } } } return jsonFileCount; } @Override void run(); int executeOfflineProcessing(); Boolean hasJsonFileExtension(String fileName); Boolean processOfflineConfiguration(File jsonFile); DataEnrichmentModel updateLastExecutionTime(DataEnrichmentModel dataEnrichmentModel); Boolean executeCypherQuery(String cypherQuery, DataEnrichmentModel dataEnrichmentModel); Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule); }
@Test public void testExecuteOfflineProcessingNegative() { AssertJUnit.assertNotSame(6, executor.executeOfflineProcessing()); }
OfflineDataProcessingExecutor extends TimerTask { public Boolean hasJsonFileExtension(String fileName) { if (fileName != null && !fileName.isEmpty()) { String extension = FilenameUtils.getExtension(fileName); if (JSON_FILE_EXTENSION.equalsIgnoreCase(extension)) { return Boolean.TRUE; } } return Boolean.FALSE; } @Override void run(); int executeOfflineProcessing(); Boolean hasJsonFileExtension(String fileName); Boolean processOfflineConfiguration(File jsonFile); DataEnrichmentModel updateLastExecutionTime(DataEnrichmentModel dataEnrichmentModel); Boolean executeCypherQuery(String cypherQuery, DataEnrichmentModel dataEnrichmentModel); Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule); }
@Test public void testHasJsonFileExtension() { String fileName = "data-enrichment.JSON"; Boolean hasJsonFileExtension = executor.hasJsonFileExtension(fileName); assertTrue(hasJsonFileExtension); } @Test public void testHasJsonFileExtensionNegative() { String fileName = "neo4j_import_json.py"; Boolean hasJsonFileExtension = executor.hasJsonFileExtension(fileName); AssertJUnit.assertEquals(Boolean.FALSE, hasJsonFileExtension); }
OfflineDataProcessingExecutor extends TimerTask { public Boolean processOfflineConfiguration(File jsonFile) { try { try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) { DataEnrichmentModel[] dataEnrichmentModelArray = new Gson().fromJson(reader, DataEnrichmentModel[].class); List<DataEnrichmentModel> dataEnrichmentModels = Arrays.asList(dataEnrichmentModelArray); for (DataEnrichmentModel dataEnrichmentModel : dataEnrichmentModels) { String cypherQuery = dataEnrichmentModel.getCypherQuery(); Long runSchedule = dataEnrichmentModel.getRunSchedule(); if (cypherQuery == null || cypherQuery.isEmpty() || runSchedule == null ) { log.error(dataEnrichmentModel.getQueryName() + " doesn't have either cypherQuery or runSchedule attribute."); continue; } if (isQueryScheduledToRun(dataEnrichmentModel.getRunSchedule(), dataEnrichmentModel.getLastExecutionTime(), dataEnrichmentModel.getCronSchedule())) { Boolean successFlag = executeCypherQuery(cypherQuery, dataEnrichmentModel); if (successFlag) { updateLastExecutionTime(dataEnrichmentModel); } } } try (JsonWriter writer = new JsonWriter(new FileWriter(jsonFile))) { writer.setIndent(" "); new GsonBuilder().disableHtmlEscaping().create().toJson(dataEnrichmentModels.toArray(), DataEnrichmentModel[].class, writer); } catch (IOException e) { log.error("Unable to update offline configuration file.", e); } } catch (FileNotFoundException e) { log.error("offline configuration file not found.", e); } catch (IOException e) { log.error("Unable to read offline configuration file.", e); } } catch (IllegalStateException | JsonSyntaxException ex) { log.error(jsonFile.getName() + " file is not as per expected format", ex); return Boolean.FALSE; } return Boolean.TRUE; } @Override void run(); int executeOfflineProcessing(); Boolean hasJsonFileExtension(String fileName); Boolean processOfflineConfiguration(File jsonFile); DataEnrichmentModel updateLastExecutionTime(DataEnrichmentModel dataEnrichmentModel); Boolean executeCypherQuery(String cypherQuery, DataEnrichmentModel dataEnrichmentModel); Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule); }
@Test public void testProcessOfflineConfiguration() { File configFile = new File(ConfigOptions.OFFLINE_DATA_PROCESSING_RESOLVED_PATH + ConfigOptions.FILE_SEPERATOR + ConfigOptions.DATA_ENRICHMENT_TEMPLATE); Boolean resultFlag = executor.processOfflineConfiguration(configFile); assertTrue(resultFlag); }
OfflineDataProcessingExecutor extends TimerTask { public DataEnrichmentModel updateLastExecutionTime(DataEnrichmentModel dataEnrichmentModel) { String lastRunTime = InsightsUtils.getLocalDateTime(DATE_TIME_FORMAT); if (dataEnrichmentModel != null) { dataEnrichmentModel.setLastExecutionTime(lastRunTime); } return dataEnrichmentModel; } @Override void run(); int executeOfflineProcessing(); Boolean hasJsonFileExtension(String fileName); Boolean processOfflineConfiguration(File jsonFile); DataEnrichmentModel updateLastExecutionTime(DataEnrichmentModel dataEnrichmentModel); Boolean executeCypherQuery(String cypherQuery, DataEnrichmentModel dataEnrichmentModel); Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule); }
@Test public void testUpdateLastExecutionTime() { DataEnrichmentModel dataEnrichmentModel = new DataEnrichmentModel(); dataEnrichmentModel.setLastExecutionTime("2018/07/16 12:53 PM"); DataEnrichmentModel resultModel = executor.updateLastExecutionTime(dataEnrichmentModel); String currentTime = InsightsUtils.getLocalDateTime("yyyy/MM/dd hh:mm a"); AssertJUnit.assertEquals(currentTime, resultModel.getLastExecutionTime()); } @Test public void testUpdateLastExecutionTimeNegative() { DataEnrichmentModel dataEnrichmentModel = new DataEnrichmentModel(); dataEnrichmentModel.setLastExecutionTime("2018/07/16 12:53 PM"); DataEnrichmentModel resultModel = executor.updateLastExecutionTime(dataEnrichmentModel); String randomTime = "2018/07/16 05:50 PM"; AssertJUnit.assertNotSame(randomTime, resultModel.getLastExecutionTime()); }
HttpMatch { public Method[] findInterfaceMethods(String methodName) { Method[] methods = interfaceClass.getMethods(); List<Method> ret = new ArrayList<Method>(); for (Method method : methods) { if (method.getName().equals(methodName)) ret.add(method); } return ret.toArray(new Method[] {}); } HttpMatch(Class<?> interfaceClass, Class<?> refClass); Method[] findInterfaceMethods(String methodName); Method[] findRefMethods(Method[] interfaceMethods, String operationId, String requestMethod); Method matchRefMethod(Method[] refMethods, String methodName, Set<String> keySet); }
@Test public void testFindInterfaceMethods(){ Method[] findInterfaceMethods = httpMatch.findInterfaceMethods("login"); Assert.assertEquals(findInterfaceMethods.length, 2); findInterfaceMethods = httpMatch.findInterfaceMethods("get"); Assert.assertEquals(findInterfaceMethods.length, 2); findInterfaceMethods = httpMatch.findInterfaceMethods("test"); Assert.assertEquals(findInterfaceMethods.length, 1); }
HttpMatch { public Method[] findRefMethods(Method[] interfaceMethods, String operationId, String requestMethod) { List<Method> ret = new ArrayList<Method>(); for (Method method : interfaceMethods) { Method m; try { m = refClass.getMethod(method.getName(), method.getParameterTypes()); final ApiOperation apiOperation = ReflectionUtils.getAnnotation(m, ApiOperation.class); String nickname = null == apiOperation ? null : apiOperation.nickname(); if (operationId != null) { if (!operationId.equals(nickname)) continue; } else { if (StringUtils.isNotBlank(nickname)) continue; } if (requestMethod != null) { String httpMethod = null == apiOperation ? null : apiOperation.httpMethod(); if (StringUtils.isNotBlank(httpMethod) && !requestMethod.equals(httpMethod)) continue; if (StringUtils.isBlank(httpMethod) && !requestMethod.equalsIgnoreCase(HttpMethod.POST.name())) continue; } ret.add(m); } catch (NoSuchMethodException e) { logger.error("NoSuchMethodException", e); } catch (SecurityException e) { logger.error("SecurityException", e); } } return ret.toArray(new Method[] {}); } HttpMatch(Class<?> interfaceClass, Class<?> refClass); Method[] findInterfaceMethods(String methodName); Method[] findRefMethods(Method[] interfaceMethods, String operationId, String requestMethod); Method matchRefMethod(Method[] refMethods, String methodName, Set<String> keySet); }
@Test public void testFindRefMethods() throws NoSuchMethodException, SecurityException{ Method[] findInterfaceMethods = httpMatch.findInterfaceMethods("login"); Assert.assertEquals(findInterfaceMethods.length, 2); Method[] findRefMethods = httpMatch.findRefMethods(findInterfaceMethods, null, "POST"); Assert.assertEquals(findRefMethods.length, 1); Assert.assertEquals(findRefMethods[0], InterfaceServiceImplTest.class.getDeclaredMethod("login", String.class)); findRefMethods = httpMatch.findRefMethods(findInterfaceMethods, "bypwd", "POST"); Assert.assertEquals(findRefMethods.length, 1); Assert.assertEquals(findRefMethods[0], InterfaceServiceImplTest.class.getDeclaredMethod("login", String.class, String.class)); findRefMethods = httpMatch.findRefMethods(findInterfaceMethods, "other", "POST"); Assert.assertEquals(findRefMethods.length, 0); findRefMethods = httpMatch.findRefMethods(findInterfaceMethods, null, "GET"); Assert.assertEquals(findRefMethods.length, 0); findInterfaceMethods = httpMatch.findInterfaceMethods("get"); Assert.assertEquals(findInterfaceMethods.length, 2); findRefMethods = httpMatch.findRefMethods(findInterfaceMethods, null, "POST"); Assert.assertEquals(findRefMethods.length, 2); }
Reader { public static void read(Swagger swagger, Set<Class<?>> classes) { final Reader reader = new Reader(swagger); for (Class<?> cls : classes) { final ReaderContext context = new ReaderContext(swagger, cls, cls, "", null, false, new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), new ArrayList<Parameter>()); reader.read(context); } } private Reader(Swagger swagger); static void read(Swagger swagger, Set<Class<?>> classes); static void read(Swagger swagger, Map<Class<?>, Object> interfaceMapRef, String httpContext); }
@SuppressWarnings({ "serial" }) @Test public void testApplyParameters(){ Swagger swagger = new Swagger(); Reader.read(swagger, new HashMap<Class<?>, Object>(){{ put(InterfaceServiceTest.class, new InterfaceServiceImplTest()); }}, "/h"); Map<String, Path> paths = swagger.getPaths(); Assert.assertEquals(paths.size(), 4); Path path = swagger.getPaths().get("/h/com.deepoove.swagger.dubbo.api.InterfaceServiceTest/test"); Assert.assertNotNull(path); Operation operation = path.getOperationMap().get(HttpMethod.POST); Assert.assertNotNull(operation); Assert.assertNotNull(operation.getParameters()); Assert.assertEquals(operation.getSummary(), "查询用户"); List<Parameter> parameters = operation.getParameters(); Assert.assertEquals(parameters.get(0).getName(), "para"); Assert.assertEquals(parameters.get(1).getName(), "code"); Assert.assertTrue(parameters.get(0).getRequired()); Assert.assertEquals(parameters.get(0).getDescription(), "参数"); path = swagger.getPaths().get("/h/com.deepoove.swagger.dubbo.api.InterfaceServiceTest/login/bypwd"); Assert.assertNotNull(path); path = swagger.getPaths().get("/h/com.deepoove.swagger.dubbo.api.InterfaceServiceTest/login"); Assert.assertNotNull(path); }
HomePresenter extends BasePresenter<HomeContract.View> implements HomeContract.Presenter { @Override public void fetchUsers() { if (this.getView() != null) { this.getView().onLoading(true); this.addDisposable(mRepository.fetchUsers(this.getView().getPage()). subscribeOn(this.getScheduler().io()) .observeOn(this.getScheduler().ui()) .subscribe( userResponse -> { this.getView().onLoading(false); this.getView().onUserResponse(userResponse); }, error -> { this.getView().onLoading(false); this.getView().onError(error); } )); } } @Inject HomePresenter(@NonNull HomeContract.Repository repository, @NonNull BaseScheduler scheduler); @Override void fetchUsers(); @Override HomeContract.View getView(); }
@Test public void fetchUsers_sucess(){ mPresenter.fetchUsers(); verify(mRepository, times(1)).fetchUsers(2); } @Test public void fetchUsers_returning_loadingSuccess_forView() { mPresenter.fetchUsers(); verify(mView, times(1)).getPage(); verify(mView, times(1)).onLoading(true); mTestScheduler.triggerActions(); verify(mView, times(1)).onLoading(false); } @Test public void fetchUsers_returningSuccess_forView() { mPresenter.fetchUsers(); mTestScheduler.triggerActions(); verify(mView, times(1)).onUserResponse(mUserResponse); verify(mView, never()).onError(null); } @Test public void fetchUsers_returningFailing_forView() { Throwable throwable = new Throwable(); when(mRepository.fetchUsers(2)).thenReturn(Single.error(throwable)); mPresenter.fetchUsers(); mTestScheduler.triggerActions(); verify(mView).onError(throwable); verify(mView, times(1)).onLoading(false); verify(mView, never()).onUserResponse(mUserResponse); }
HomePresenter extends BasePresenter<HomeContract.View> implements HomeContract.Presenter { @Override public HomeContract.View getView() { return super.getView(); } @Inject HomePresenter(@NonNull HomeContract.Repository repository, @NonNull BaseScheduler scheduler); @Override void fetchUsers(); @Override HomeContract.View getView(); }
@Test public void attach_isNotNull_sucess(){ assertNotNull(mPresenter.getView()); } @Test public void detachView_isNull_sucess(){ assertNotNull(mPresenter.getView()); mPresenter.detachView(); assertNull(mPresenter.getView()); }
HomeRepository implements HomeContract.Repository { @Override public Single<UserResponse> fetchUsers(int page) { return this.endPointHelper.fetchUsers(page); } @Inject HomeRepository(EndPointHelper endPointHelper); @Override Single<UserResponse> fetchUsers(int page); }
@Test public void fetchUsers_sucess() { mRepository.fetchUsers(2); verify(mApiEndPointHelper).fetchUsers(2); } @Test public void fetchUsers_noErros_sucess() { TestObserver<UserResponse> subscriber = TestObserver.create(); mApiEndPointHelper.fetchUsers(2).subscribe(subscriber); subscriber.onNext(new UserResponse()); subscriber.assertNoErrors(); subscriber.assertComplete(); }
WsProducer extends DefaultProducer { public static void sendMessage(WebSocket webSocket, String msg, boolean streaming) { if (streaming && msg.length() > STREAM_BUFFER_SIZE) { int p = 0; while (p < msg.length()) { if (msg.length() - p < STREAM_BUFFER_SIZE) { webSocket.sendContinuationFrame(msg.substring(p), true, 0); p = msg.length(); } else if (p == 0) { p = STREAM_BUFFER_SIZE; webSocket.sendTextFrame(msg.substring(0, STREAM_BUFFER_SIZE), false, 0); } else { var substring = msg.substring(p, p + STREAM_BUFFER_SIZE); p += STREAM_BUFFER_SIZE; webSocket.sendContinuationFrame(substring, msg.length() == p, 0); } } } else { webSocket.sendTextFrame(msg); } } WsProducer(WsEndpoint endpoint); @Override WsEndpoint getEndpoint(); @Override void process(Exchange exchange); static void sendMessage(WebSocket webSocket, String msg, boolean streaming); static void sendMessage(WebSocket webSocket, byte[] msg, boolean streaming); static void sendStreamMessage(WebSocket webSocket, InputStream in); static final int STREAM_BUFFER_SIZE; }
@Test public void testSendMessage() { var wsMockHelper = new WebSocketMockHelper(); getTestByteArrayStream().forEach(bytes -> { try { WsProducer.sendMessage(wsMockHelper.getMock(), bytes, false); assertArrayEquals("sendMessage() (bytes, non-streaming) seems flawed", bytes, wsMockHelper.getResultBytes()); wsMockHelper.resetBuffer(); WsProducer.sendMessage(wsMockHelper.getMock(), bytes, true); assertArrayEquals("sendMessage() (bytes, streaming) seems flawed", bytes, wsMockHelper.getResultBytes()); wsMockHelper.resetBuffer(); var string = new String(bytes, StandardCharsets.US_ASCII); WsProducer.sendMessage(wsMockHelper.getMock(), string, false); assertArrayEquals("sendMessage() (String, non-streaming) seems flawed", bytes, wsMockHelper.getResultBytes()); wsMockHelper.resetBuffer(); WsProducer.sendMessage(wsMockHelper.getMock(), string, true); assertArrayEquals("sendMessage() (String, streaming) seems flawed", bytes, wsMockHelper.getResultBytes()); wsMockHelper.resetBuffer(); } catch (Exception e) { throw new RuntimeException(e); } }); }
DefProConfigurationLoader implements ConfigurationLoader { @Override @SuppressWarnings("IllegalCatch") public Configuration load(File file) throws FileNotFoundException { if (!file.exists()) { throw new FileNotFoundException("The given file does not exist"); } try { return new DefProConfiguration(APIProvider.getAPI(file.getAbsolutePath())); } catch (Exception e) { throw new FileNotFoundException(e.getMessage()); } } @Override @SuppressWarnings("IllegalCatch") Configuration load(File file); @Override Configuration load(InputStream input); }
@Test public void nonExistentFile() throws Exception { File file = mock(File.class); when(file.exists()).thenReturn(false); assertThatThrownBy(() -> loader.load(file)).isInstanceOf(FileNotFoundException.class); } @Test public void invalidFile() throws Exception { File file = mock(File.class); when(file.exists()).thenReturn(true); assertThatThrownBy(() -> loader.load(file)).isInstanceOf(FileNotFoundException.class); } @Test public void existentFile() throws Exception { File file = File.createTempFile("defpro", "test"); String content = "int a = 1"; Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE); assertThat(loader.load(file).get(new IntegerProperty("a"))).isEqualTo(1); file.deleteOnExit(); } @Test public void validStream() throws Exception { String content = "int a = 1"; InputStream input = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); assertThat(loader.load(input).get(new IntegerProperty("a"))).isEqualTo(1); } @Test public void invalidStream() throws Exception { InputStream input = mock(InputStream.class); when(input.read(any())).thenThrow(new IOException()); assertThatThrownBy(() -> loader.load(input)).isInstanceOf(IOException.class); }
Teleporter extends Tileable implements TileableListener { public void setDestination(Teleporter destination) { if (!track.getClass().equals(destination.getTrack().getClass())) { throw new IllegalStateException("Both connected teleporters must be either" + " horizontal or vertical"); } this.destination = destination; } Teleporter(Track track); void setDestination(Teleporter destination); Track getTrack(); Teleporter getDestination(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void setDestinationFail() { Teleporter vertTeleporter = new Teleporter(new VerticalTrack()); assertThatThrownBy(() -> vertTeleporter.setDestination(teleporter1)) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> teleporter1.setDestination(vertTeleporter)) .isInstanceOf(IllegalStateException.class); }
Teleporter extends Tileable implements TileableListener { @Override public void ballDisposed(Tileable tileable, Direction direction, Marble marble) { informDispose(direction, marble); } Teleporter(Track track); void setDestination(Teleporter destination); Track getTrack(); Teleporter getDestination(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void informDispose() { Direction direction = Direction.RIGHT; Marble marble = new Marble(MarbleType.BLUE); TileableListener listener = mock(TileableListener.class); teleporter1.addListener(listener); teleporter1.ballDisposed(teleporter1, direction, marble); verify(listener, times(1)).ballDisposed( teleporter1, direction, marble); }
HorizontalTrack extends Track { public boolean isConnected() { Tile tile = getTile(); if (tile == null) { throw new IllegalStateException("The track is not placed on a grid"); } Tile left = tile.get(Direction.LEFT); Tile right = tile.get(Direction.RIGHT); return left != null && right != null; } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void isNotConnected() { Grid grid = new Grid(null, 1, 1); grid.place(0, 0, track); assertThat(track.isConnected()).isFalse(); } @Test public void isNotConnectedLeft() { Grid grid = new Grid(null, 2, 1); grid.place(0, 0, new HorizontalTrack()); grid.place(1, 0, track); assertThat(track.isConnected()).isFalse(); } @Test public void isNotConnectedRight() { Grid grid = new Grid(null, 2, 1); grid.place(0, 0, track); grid.place(1, 0, new HorizontalTrack()); assertThat(track.isConnected()).isFalse(); } @Test public void unplacedNotConnected() { assertThatThrownBy(() -> track.isConnected()).isInstanceOf(IllegalStateException.class); } @Test public void isConnected() { HorizontalTrack hz1 = new HorizontalTrack(); HorizontalTrack hz2 = new HorizontalTrack(); Grid grid = new Grid(null, 3, 1); grid.place(0, 0, hz1); grid.place(1, 0, track); grid.place(2, 0, hz2); assertThat(track.isConnected()).isTrue(); }
HorizontalTrack extends Track { @Override public boolean allowsConnection(Direction direction) { switch (direction) { case LEFT: case RIGHT: return true; default: return false; } } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void allowsLeft() { assertThat(track.allowsConnection(Direction.LEFT)).isTrue(); } @Test public void allowsRight() { assertThat(track.allowsConnection(Direction.RIGHT)).isTrue(); } @Test public void disallowsTop() { assertThat(track.allowsConnection(Direction.TOP)).isFalse(); } @Test public void disallowsBottom() { assertThat(track.allowsConnection(Direction.BOTTOM)).isFalse(); } @Test public void disallowsNull() { assertThatThrownBy(() -> track.allowsConnection(null)) .isInstanceOf(NullPointerException.class); }
DefProConfiguration implements Configuration { @Override @SuppressWarnings("unchecked") public <T> T get(Property<T> property, T defaultValue) { Class<T> type = property.getType(); String key = property.getKey(); Object value; if (property instanceof ListProperty) { ListProperty listProperty = (ListProperty) property; value = getList(listProperty); } else { value = getValue(key, type); } if (value == null) { return defaultValue; } return property.map((T) value); } DefProConfiguration(IDefProAPI api); @Override @SuppressWarnings("unchecked") T get(Property<T> property, T defaultValue); @Override boolean exists(Property<?> property); }
@Test public void getDefaultBooleanProperty() throws Exception { when(api.getBooleanValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new BooleanProperty("a", false))).isFalse(); } @Test public void getDoubleProperty() throws Exception { when(api.getRealValueOf("a")).thenReturn(1.0); assertThat(config.get(new DoubleProperty("a"))).isEqualTo(1.0); } @Test public void getDefaultDoubleProperty() throws Exception { when(api.getRealValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new DoubleProperty("a", 1.0))).isEqualTo(1.0); } @Test public void getIntegerProperty() throws Exception { when(api.getIntegerValueOf("a")).thenReturn(1); assertThat(config.get(new IntegerProperty("a"))).isEqualTo(1); } @Test public void getDefaultIntegerProperty() throws Exception { when(api.getIntegerValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new IntegerProperty("a", 1))).isEqualTo(1); } @Test public void getStringProperty() throws Exception { when(api.getStringValueOf("a")).thenReturn("b"); assertThat(config.get(new StringProperty("a", "c"))).isEqualTo("b"); } @Test public void getDefaultStringProperty() throws Exception { when(api.getStringValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new StringProperty("a", "c"))).isEqualTo("c"); } @Test public void getUnsupportedListProperty() throws Exception { List<Object> list = Lists.newArrayList(new Object()); assertThat(config.get(new ListProperty<>(Object.class, "a", list))).isEqualTo(list); } @Test public void getBooleanListProperty() throws Exception { List<Boolean> list = Lists.newArrayList(false, true); when(api.getListBoolValueOf("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(Boolean.class, "a", Lists.emptyList()))) .isEqualTo(list); } @Test public void getDefaultBooleanListProperty() throws Exception { when(api.getListRealValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new ListProperty<>(Boolean.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); } @Test public void getDoubleListProperty() throws Exception { List<Double> list = Lists.newArrayList(1.0, 2.0); when(api.getListRealValueOf("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(Double.class, "a", Lists.emptyList()))) .isEqualTo(list); } @Test public void getDefaultDoubleListProperty() throws Exception { when(api.getListRealValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new ListProperty<>(Double.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); } @Test public void getIntegerListProperty() throws Exception { List<Integer> list = Lists.newArrayList(1, 2); when(api.getListIntValueOf("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(Integer.class, "a", Lists.emptyList()))) .isEqualTo(list); } @Test public void getDefaultIntegerListProperty() throws Exception { when(api.getListIntValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new ListProperty<>(Integer.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); } @Test public void getStringListProperty() throws Exception { List<String> list = Lists.newArrayList("a", "b"); when(api.getListStringValueOf("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(String.class, "a", Lists.emptyList()))) .isEqualTo(list); } @Test public void getDefaultStringListProperty() throws Exception { when(api.getListStringValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new ListProperty<>(String.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); } @Test public void getBoundedIntegerPropertyDefault() throws Exception { when(api.getIntegerValueOf("a")).thenThrow(new NotExistingVariableException("")); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a", -1), 0, 100))) .isEqualTo(-1); } @Test public void getBoundedIntegerPropertyInner() throws Exception { when(api.getIntegerValueOf("a")).thenReturn(50); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a"), 0, 100))) .isEqualTo(50); } @Test public void getBoundedIntegerPropertyLower() throws Exception { when(api.getIntegerValueOf("a")).thenReturn(-1); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a"), 0, 100))) .isEqualTo(0); } @Test public void getBoundedIntegerPropertyUpper() throws Exception { when(api.getIntegerValueOf("a")).thenReturn(200); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a"), 0, 100))) .isEqualTo(100); } @Test public void getUnsupportedProperty() { Object object = new Object(); assertThat(config.get(new Property<Object>(Object.class, "", object) {})) .isEqualTo(object); } @Test public void getBooleanProperty() throws Exception { when(api.getBooleanValueOf("a")).thenReturn(true); assertThat(config.get(new BooleanProperty("a", false))).isTrue(); }
HorizontalTrack extends Track { @Override public boolean accepts(Direction direction, Marble marble) { return allowsConnection(direction); } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void acceptsLeft() { assertThat(track.accepts(Direction.LEFT, marble)).isTrue(); } @Test public void acceptsRight() { assertThat(track.accepts(Direction.RIGHT, marble)).isTrue(); } @Test public void notAcceptsTop() { assertThat(track.accepts(Direction.TOP, marble)).isFalse(); } @Test public void notAcceptsBottom() { assertThat(track.accepts(Direction.BOTTOM, marble)).isFalse(); }
HorizontalTrack extends Track { @Override public boolean passesMidpoint(Direction direction, Marble marble) { return true; } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void passesMidpointLeft() { assertThat(track.passesMidpoint(Direction.LEFT, marble)).isTrue(); } @Test public void passesMidpointRight() { assertThat(track.passesMidpoint(Direction.RIGHT, marble)).isTrue(); } @Test public void passesMidpointTop() { assertThat(track.passesMidpoint(Direction.TOP, marble)).isTrue(); } @Test public void passesMidpointBottom() { assertThat(track.passesMidpoint(Direction.BOTTOM, marble)).isTrue(); }
HorizontalTrack extends Track { @Override public void accept(Direction direction, Marble marble) { switch (direction) { case LEFT: case RIGHT: informAcceptation(direction, marble); break; default: throw new IllegalArgumentException("The track does not accept balls from the given " + "direction"); } } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void acceptLeft() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.LEFT; track.addListener(listener); track.accept(direction, marble); verify(listener, times(1)).ballAccepted(track, direction, marble); } @Test public void acceptRight() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.RIGHT; track.addListener(listener); track.accept(direction, marble); verify(listener, times(1)).ballAccepted(track, direction, marble); } @Test public void acceptTopException() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.TOP; track.addListener(listener); assertThatThrownBy(() -> track.accept(direction, marble)) .isInstanceOf(IllegalArgumentException.class); verify(listener, never()).ballAccepted(track, direction, marble); } @Test public void acceptBottomException() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.BOTTOM; track.addListener(listener); assertThatThrownBy(() -> track.accept(direction, marble)) .isInstanceOf(IllegalArgumentException.class); verify(listener, never()).ballAccepted(track, direction, marble); }
VerticalTrack extends Track { public boolean isConnected() { Tile tile = getTile(); if (tile == null) { throw new IllegalStateException("The track is not placed on a grid"); } Tile left = tile.get(Direction.TOP); Tile right = tile.get(Direction.BOTTOM); return left != null && right != null; } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void isNotConnected() { Grid grid = new Grid(null, 1, 1); grid.place(0, 0, track); assertThat(track.isConnected()).isFalse(); } @Test public void isNotConnectedBottom() { Grid grid = new Grid(null, 1, 2); grid.place(0, 0, new VerticalTrack()); grid.place(0, 1, track); assertThat(track.isConnected()).isFalse(); } @Test public void isNotConnectedTop() { Grid grid = new Grid(null, 1, 2); grid.place(0, 0, track); grid.place(0, 1, new HorizontalTrack()); assertThat(track.isConnected()).isFalse(); } @Test public void unplacedNotConnected() { assertThatThrownBy(() -> track.isConnected()).isInstanceOf(IllegalStateException.class); } @Test public void isConnected() { Grid grid = new Grid(null, 1, 3); grid.place(0, 0, new VerticalTrack()); grid.place(0, 1, track); grid.place(0, 2, new VerticalTrack()); assertThat(track.isConnected()).isTrue(); }
VerticalTrack extends Track { @Override public boolean allowsConnection(Direction direction) { switch (direction) { case TOP: case BOTTOM: return true; default: return false; } } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void allowsTop() { assertThat(track.allowsConnection(Direction.TOP)).isTrue(); } @Test public void allowsBottom() { assertThat(track.allowsConnection(Direction.BOTTOM)).isTrue(); } @Test public void disallowsLeft() { assertThat(track.allowsConnection(Direction.LEFT)).isFalse(); } @Test public void disallowsBottom() { assertThat(track.allowsConnection(Direction.RIGHT)).isFalse(); } @Test public void disallowsNull() { assertThatThrownBy(() -> track.allowsConnection(null)) .isInstanceOf(NullPointerException.class); }
VerticalTrack extends Track { @Override public boolean accepts(Direction direction, Marble marble) { return allowsConnection(direction); } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void acceptsTop() { assertThat(track.accepts(Direction.TOP, marble)).isTrue(); } @Test public void acceptsBottom() { assertThat(track.accepts(Direction.BOTTOM, marble)).isTrue(); } @Test public void notAcceptsLeft() { assertThat(track.accepts(Direction.LEFT, marble)).isFalse(); } @Test public void notAcceptsRight() { assertThat(track.accepts(Direction.RIGHT, marble)).isFalse(); }
VerticalTrack extends Track { @Override public boolean passesMidpoint(Direction direction, Marble marble) { return true; } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void passesMidpointLeft() { assertThat(track.passesMidpoint(Direction.LEFT, marble)).isTrue(); } @Test public void passesMidpointRight() { assertThat(track.passesMidpoint(Direction.RIGHT, marble)).isTrue(); } @Test public void passesMidpointTop() { assertThat(track.passesMidpoint(Direction.TOP, marble)).isTrue(); } @Test public void passesMidpointBottom() { assertThat(track.passesMidpoint(Direction.BOTTOM, marble)).isTrue(); }
VerticalTrack extends Track { @Override public void accept(Direction direction, Marble marble) { switch (direction) { case TOP: case BOTTOM: informAcceptation(direction, marble); break; default: throw new IllegalArgumentException("The track does not accept balls from the given " + "direction"); } } boolean isConnected(); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void acceptTop() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.TOP; track.addListener(listener); track.accept(direction, marble); verify(listener, times(1)).ballAccepted(track, direction, marble); } @Test public void acceptBottom() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.BOTTOM; track.addListener(listener); track.accept(direction, marble); verify(listener, times(1)).ballAccepted(track, direction, marble); } @Test public void acceptLeftException() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.LEFT; track.addListener(listener); assertThatThrownBy(() -> track.accept(direction, marble)) .isInstanceOf(IllegalArgumentException.class); verify(listener, never()).ballAccepted(track, direction, marble); } @Test public void acceptRightException() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.RIGHT; track.addListener(listener); assertThatThrownBy(() -> track.accept(direction, marble)) .isInstanceOf(IllegalArgumentException.class); verify(listener, never()).ballAccepted(track, direction, marble); }
FilterTrack extends Track implements TileableListener { @Override public boolean isConnected() { return track.isConnected(); } FilterTrack(Track track, MarbleType marbleType); Track getTrack(); MarbleType getMarbleType(); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void setTile(Tile tile); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void isNotConnected() { Grid grid = new Grid(null, 1, 1); grid.place(0, 0, track); assertThat(track.isConnected()).isFalse(); } @Test public void isConnected() { Grid grid = new Grid(null, 3, 1); grid.place(1, 0, track); assertThat(track.isConnected()).isTrue(); }
FilterTrack extends Track implements TileableListener { @Override public boolean allowsConnection(Direction direction) { return track.allowsConnection(direction); } FilterTrack(Track track, MarbleType marbleType); Track getTrack(); MarbleType getMarbleType(); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void setTile(Tile tile); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void allowsLeft() { assertThat(track.allowsConnection(Direction.LEFT)).isTrue(); } @Test public void allowsRight() { assertThat(track.allowsConnection(Direction.RIGHT)).isTrue(); } @Test public void disallowsTop() { assertThat(track.allowsConnection(Direction.TOP)).isFalse(); } @Test public void disallowsBottom() { assertThat(track.allowsConnection(Direction.BOTTOM)).isFalse(); }
FilterTrack extends Track implements TileableListener { @Override public boolean accepts(Direction direction, Marble marble) { return track.accepts(direction, marble); } FilterTrack(Track track, MarbleType marbleType); Track getTrack(); MarbleType getMarbleType(); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void setTile(Tile tile); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void acceptsRight() { assertThat(track.accepts(Direction.RIGHT, new Marble(MarbleType.GREEN))).isTrue(); } @Test public void notAcceptsTop() { assertThat(track.accepts(Direction.TOP, new Marble(MarbleType.GREEN))).isFalse(); } @Test public void notAcceptsBottom() { assertThat(track.accepts(Direction.BOTTOM, new Marble(MarbleType.GREEN))).isFalse(); }
FilterTrack extends Track implements TileableListener { public Track getTrack() { return track; } FilterTrack(Track track, MarbleType marbleType); Track getTrack(); MarbleType getMarbleType(); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void setTile(Tile tile); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void getTrack() { assertThat(track.getTrack()).isEqualTo(inner); }
FilterTrack extends Track implements TileableListener { public MarbleType getMarbleType() { return marbleType; } FilterTrack(Track track, MarbleType marbleType); Track getTrack(); MarbleType getMarbleType(); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void setTile(Tile tile); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void getMarbleType() { assertThat(track.getMarbleType()).isEqualTo(type); }
FilterTrack extends Track implements TileableListener { @Override public void ballDisposed(Tileable tileable, Direction direction, Marble marble) { informDispose(direction, marble); } FilterTrack(Track track, MarbleType marbleType); Track getTrack(); MarbleType getMarbleType(); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void setTile(Tile tile); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); }
@Test public void informDispose() { Tileable tileable = new HorizontalTrack(); Direction direction = Direction.RIGHT; Marble marble = new Marble(MarbleType.BLUE); track.ballDisposed(tileable, direction, marble); }
OneWayTrack extends Track { @Override public boolean isConnected() { return track.isConnected(); } OneWayTrack(Track track, Direction direction); Track getTrack(); Direction getDirection(); @Override void setTile(Tile tile); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); }
@Test public void isNotConnected() { Grid grid = new Grid(null, 1, 1); grid.place(0, 0, track); assertThat(track.isConnected()).isFalse(); } @Test public void isConnected() { Grid grid = new Grid(null, 3, 1); grid.place(1, 0, track); assertThat(track.isConnected()).isTrue(); }
OneWayTrack extends Track { @Override public boolean allowsConnection(Direction direction) { return this.track.allowsConnection(direction); } OneWayTrack(Track track, Direction direction); Track getTrack(); Direction getDirection(); @Override void setTile(Tile tile); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); }
@Test public void allowsLeft() { assertThat(track.allowsConnection(Direction.LEFT)).isTrue(); } @Test public void allowsRight() { assertThat(track.allowsConnection(Direction.RIGHT)).isTrue(); } @Test public void disallowsTop() { assertThat(track.allowsConnection(Direction.TOP)).isFalse(); } @Test public void disallowsBottom() { assertThat(track.allowsConnection(Direction.BOTTOM)).isFalse(); }
OneWayTrack extends Track { @Override public boolean accepts(Direction direction, Marble marble) { return this.track.accepts(direction, marble); } OneWayTrack(Track track, Direction direction); Track getTrack(); Direction getDirection(); @Override void setTile(Tile tile); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); }
@Test public void acceptsLeft() { assertThat(track.accepts(Direction.LEFT, new Marble(MarbleType.GREEN))).isTrue(); } @Test public void notAcceptsTop() { assertThat(track.accepts(Direction.TOP, new Marble(MarbleType.GREEN))).isFalse(); } @Test public void notAcceptsBottom() { assertThat(track.accepts(Direction.BOTTOM, new Marble(MarbleType.GREEN))).isFalse(); }
OneWayTrack extends Track { @Override public void accept(Direction direction, Marble marble) { if (!accepts(direction, marble)) { throw new IllegalArgumentException("The track does not accept balls from the given " + "direction"); } informAcceptation(direction, marble); } OneWayTrack(Track track, Direction direction); Track getTrack(); Direction getDirection(); @Override void setTile(Tile tile); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); }
@Test public void acceptLeft() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.LEFT; track.addListener(listener); track.accept(direction, marble); verify(listener, times(1)).ballAccepted(track, direction, marble); } @Test public void acceptRight() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.RIGHT; track.addListener(listener); track.accept(direction, marble); verify(listener, times(1)).ballAccepted(track, direction, marble); } @Test public void acceptTopException() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.TOP; track.addListener(listener); assertThatThrownBy(() -> track.accept(direction, marble)) .isInstanceOf(IllegalArgumentException.class); verify(listener, never()).ballAccepted(track, direction, marble); } @Test public void acceptBottomException() { TileableListener listener = mock(TileableListener.class); Marble marble = new Marble(MarbleType.BLUE); Direction direction = Direction.BOTTOM; track.addListener(listener); assertThatThrownBy(() -> track.accept(direction, marble)) .isInstanceOf(IllegalArgumentException.class); verify(listener, never()).ballAccepted(track, direction, marble); }
OneWayTrack extends Track { public Track getTrack() { return this.track; } OneWayTrack(Track track, Direction direction); Track getTrack(); Direction getDirection(); @Override void setTile(Tile tile); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); }
@Test public void getTrack() { assertThat(track.getTrack()).isEqualTo(inner); }
OneWayTrack extends Track { public Direction getDirection() { return direction; } OneWayTrack(Track track, Direction direction); Track getTrack(); Direction getDirection(); @Override void setTile(Tile tile); @Override boolean isConnected(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override boolean passesMidpoint(Direction direction, Marble marble); }
@Test public void getDirection() { assertThat(track.getDirection()).isEqualTo(direction); }
Marble implements Entity { public MarbleType getType() { return type; } Marble(MarbleType type); MarbleType getType(); boolean isCompatible(Marble other); }
@Test public void createPinkBall() { Marble marble = new Marble(MarbleType.PINK); assertThat(marble.getType()).isEqualTo(MarbleType.PINK); } @Test public void createBlueBall() { Marble marble = new Marble(MarbleType.BLUE); assertThat(marble.getType()).isEqualTo(MarbleType.BLUE); } @Test public void createGreenBall() { Marble marble = new Marble(MarbleType.GREEN); assertThat(marble.getType()).isEqualTo(MarbleType.GREEN); } @Test public void createYellowBall() { Marble marble = new Marble(MarbleType.YELLOW); assertThat(marble.getType()).isEqualTo(MarbleType.YELLOW); } @Test public void createJoker() { Marble marble = new Marble(MarbleType.JOKER); assertThat(marble.getType()).isEqualTo(MarbleType.JOKER); } @Test public void createBallNull() { Marble marble = new Marble((MarbleType) null); assertThat(marble.getType()).isEqualTo(null); }
Marble implements Entity { public boolean isCompatible(Marble other) { return other != null && (type.equals(MarbleType.JOKER) || other.type.equals(MarbleType.JOKER) || type.equals(other.type)); } Marble(MarbleType type); MarbleType getType(); boolean isCompatible(Marble other); }
@Test public void isCompatibleSameColour() { Marble greenMarble1 = new Marble(MarbleType.GREEN); Marble greenMarble2 = new Marble(MarbleType.GREEN); assertThat(greenMarble1.isCompatible(greenMarble2)).isTrue(); } @Test public void isIncompatibleDifferentColour() { Marble green = new Marble(MarbleType.GREEN); Marble blue = new Marble(MarbleType.BLUE); assertThat(green.isCompatible(blue)).isFalse(); } @Test public void isCompatibleJokerFirst() { Marble joker = new Marble(MarbleType.JOKER); Marble greenMarble = new Marble(MarbleType.GREEN); assertThat(joker.isCompatible(greenMarble)).isTrue(); } @Test public void isCompatibleJokerSecond() { Marble joker = new Marble(MarbleType.JOKER); Marble greenMarble = new Marble(MarbleType.GREEN); assertThat(greenMarble.isCompatible(joker)).isTrue(); } @Test public void isCompatibleBothJokers() { Marble joker1 = new Marble(MarbleType.JOKER); Marble joker2 = new Marble(MarbleType.JOKER); assertThat(joker1.isCompatible(joker2)).isTrue(); } @Test public void isCompatibleNull() { Marble joker = new Marble(MarbleType.JOKER); assertThat(joker.isCompatible(null)).isFalse(); }
Empty extends Tileable { @Override public boolean accepts(Direction direction, Marble marble) { return false; } @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void acceptsLeftFalse() { assertThat(empty.accepts(Direction.LEFT, marble)).isFalse(); } @Test public void acceptsRightFalse() { assertThat(empty.accepts(Direction.RIGHT, marble)).isFalse(); } @Test public void acceptsTopFalse() { assertThat(empty.accepts(Direction.TOP, marble)).isFalse(); } @Test public void acceptsBottomFalse() { assertThat(empty.accepts(Direction.BOTTOM, marble)).isFalse(); }
Empty extends Tileable { @Override public void accept(Direction direction, Marble marble) { throw new IllegalArgumentException("An empty entity does not accept from any direction"); } @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); }
@Test public void acceptLeftIllegalArgumentException() { assertThatThrownBy(() -> empty.accept(Direction.LEFT, null)).isInstanceOf(Exception.class); }
SpawningNexus extends Nexus { public Marble spawn() { if (getContext().isOccupied()) { throw new IllegalStateException("The nexus is already occupied by a marble"); } Marble marble = new Marble(getContext().poll()); accept(direction, marble); getContext().setOccupied(true); return marble; } SpawningNexus(NexusContext context, Direction direction); Marble spawn(); Direction getDirection(); static final Property<Double> JOKER_PROBABILITY; static final Property<List<String>> INITIAL_SEQUENCE; }
@Test public void spawnFailsOnOccupation() { context.setOccupied(true); assertThatThrownBy(() -> nexus.spawn()).isInstanceOf(IllegalStateException.class); } @Test public void spawnInitialSequence() { assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.BLUE); } @Test public void peekInitialSequence() { assertThat(context.peek()).isEqualTo(MarbleType.BLUE); assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.BLUE); } @Test public void spawnJoker() { when(random.nextDouble()).thenReturn(0.4); context.poll(); assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.JOKER); } @Test public void spawnPink() { when(random.nextInt(anyInt())).thenReturn(0); when(random.nextDouble()).thenReturn(0.6); context.poll(); assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.PINK); } @Test public void spawnGreen() { when(random.nextDouble()).thenReturn(0.6); when(random.nextInt(anyInt())).thenReturn(1); context.poll(); assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.GREEN); } @Test public void spawnBlue() { when(random.nextDouble()).thenReturn(0.6); when(random.nextInt(anyInt())).thenReturn(2); context.poll(); assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.BLUE); } @Test public void spawnYellow() { when(random.nextDouble()).thenReturn(0.6); when(random.nextInt(anyInt())).thenReturn(3); context.poll(); assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.YELLOW); } @Test public void add() { when(random.nextDouble()).thenReturn(0.0); context.add(MarbleType.JOKER); context.poll(); assertThat(nexus.spawn().getType()).isEqualTo(MarbleType.JOKER); }
SpawningNexus extends Nexus { public Direction getDirection() { return direction; } SpawningNexus(NexusContext context, Direction direction); Marble spawn(); Direction getDirection(); static final Property<Double> JOKER_PROBABILITY; static final Property<List<String>> INITIAL_SEQUENCE; }
@Test public void getDirection() { assertThat(nexus.getDirection()).isEqualTo(direction); }