src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ModelPathResolver { protected static String getGetter(Object instance, String fieldNameOrGetter) { final String[] GETTER_PREFIXES = {"get", "is", "has"}; final String trimmedFieldNameOrGetter = fieldNameOrGetter != null ? fieldNameOrGetter.trim() : null; if (instance == null || trimmedFieldNameOrGetter == null || trimmedFieldNameOrGetter.length() == 0) { return null; } try { Method method = instance.getClass().getMethod(trimmedFieldNameOrGetter.trim()); if (java.lang.reflect.Modifier.isPublic(method.getModifiers())) { return trimmedFieldNameOrGetter; } } catch (NoSuchMethodException e) { } for (String getterPrefix : GETTER_PREFIXES) { String getterName = getterPrefix + trimmedFieldNameOrGetter.substring(0, 1).toUpperCase() + trimmedFieldNameOrGetter.substring(1); try { Method method = instance.getClass().getMethod(getterName); if (java.lang.reflect.Modifier.isPublic(method.getModifiers())) { return getterName; } } catch (NoSuchMethodException e) { } } return null; } static ResolvedModelPathResult resolveModelPath(String path); static ResolvedModelPathResult resolveModelPath(Map<String, Object> model, String path); static ThreadLocal<Map<String, Object>> modelMapThreadLocal; }
@Test public void getGetter_checkNullSafety() { MatcherAssert.assertThat(ModelPathResolver.getGetter(null, "abc"), Matchers.nullValue()); MatcherAssert.assertThat(ModelPathResolver.getGetter(this, null), Matchers.nullValue()); MatcherAssert.assertThat(ModelPathResolver.getGetter(null, null), Matchers.nullValue()); } @Test public void getGetter_nonexistingFieldNameShouldReturnNull() { MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "xxx"), Matchers.nullValue()); } @Test public void getGetter_testExistingMethodName() { MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "someMethod"), Matchers.is("someMethod")); } @Test public void getGetter_testNonAccessibleExistingMethodName() { MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "nonAccessibleMethod"), Matchers.nullValue()); } @Test public void getGetter_testDifferentKindOfGetterPrefixes() { MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "isGetter"), Matchers.is("isIsGetter")); MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "getGetter"), Matchers.is("getGetGetter")); MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "hasGetter"), Matchers.is("hasHasGetter")); } @Test public void getGetter_testMethodWithParameter() { MatcherAssert.assertThat(ModelPathResolver.getGetter(new GetGetterTestClass(), "methodWithParameter"), Matchers.is("getMethodWithParameter")); }
BeanUtils { public static String getGetterMethodName(VariableElement field) { if (field == null || field.getKind() != ElementKind.FIELD) { return null; } TypeElement typeElement = (TypeElement) ElementUtils.AccessEnclosingElements.getFirstEnclosingElementOfKind(field, ElementKind.CLASS); ExecutableElement getterMethod = getGetterMethod(field, typeElement); if (getterMethod != null) { return getterMethod.getSimpleName().toString(); } if (checkLombokDataAnnotation(typeElement) || checkLombokGetterAnnotationOnType(typeElement) || checkLombokGetterAnnotationOnField(field)) { return TypeUtils.TypeComparison.isTypeEqual(field.asType(), TypeUtils.TypeRetrieval.getTypeMirror(boolean.class)) ? getPrefixedName("is", field.getSimpleName().toString()) : getPrefixedName("get", field.getSimpleName().toString()); } return null; } private BeanUtils(); static boolean hasDefaultNoargsConstructor(TypeElement typeElement); static boolean isDefaultNoargConstructor(ExecutableElement element); static boolean isAttribute(VariableElement field); static AttributeResult[] getAttributesWithInheritance(TypeElement typeElement); static AttributeResult[] getAttributes(TypeElement typeElement); static boolean checkHasGetter(VariableElement field); static boolean checkHasSetter(VariableElement field); static boolean checkLombokDataAnnotation(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnField(VariableElement variableElement); static String getGetterMethodName(VariableElement field); static String getSetterMethodName(VariableElement field); static String getPrefixedName(String prefix, String name); static boolean checkLombokSetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokSetterAnnotationOnField(VariableElement variableElement); }
@Test public void getGetterName_booleanFieldWithLombokGetter() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/FieldLevelTestcases.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { VariableElement field = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_FIELD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("booleanFieldWithGetterAnnotation") .getResult().get(0); MatcherAssert.assertThat(BeanUtils.getGetterMethodName(field), Matchers.is("isBooleanFieldWithGetterAnnotation")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getGetterName_nonBooleanFieldWithLombokGetter() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/FieldLevelTestcases.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { VariableElement field = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_FIELD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("fieldWithImplementedSetterAndGetterAnnotation") .getResult().get(0); MatcherAssert.assertThat(BeanUtils.getGetterMethodName(field), Matchers.is("getFieldWithImplementedSetterAndGetterAnnotation")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getGetterName_nonBooleanFieldWithLombokGetterAndSetter() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/FieldLevelTestcases.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { VariableElement field = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_FIELD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("fieldWithImplementedGetterAndSetters") .getResult().get(0); MatcherAssert.assertThat(BeanUtils.getGetterMethodName(field), Matchers.is("getFieldWithImplementedGetterAndSetters")); } }) .compilationShouldSucceed() .executeTest(); }
TemplateProcessor { public static String processTemplate(String templateString, Map<String, Object> values) { TemplateBlockBinder binder = ParseUtilities.parseString(templateString); return binder.getContent(values); } static String processTemplate(String templateString, Map<String, Object> values); static String processTemplateResourceFile(String templateFileName, Map<String, Object> values); }
@Test public void testTemplateString() { Map<String, Object> map = new HashMap<String, Object>(); map.put("test", "YEP"); MatcherAssert.assertThat(TemplateProcessor.processTemplate("${test}", map), Matchers.is("YEP")); }
TemplateProcessor { public static String processTemplateResourceFile(String templateFileName, Map<String, Object> values) { String templateString = null; try { templateString = ParseUtilities.readResourceToString(templateFileName); } catch (Exception e) { throw new IllegalArgumentException("Cannot open template file '" + templateFileName + "'", e); } return processTemplate(templateString, values); } static String processTemplate(String templateString, Map<String, Object> values); static String processTemplateResourceFile(String templateFileName, Map<String, Object> values); }
@Test public void testTemplateFile() { Map<String, Object> map = new HashMap<String, Object>(); map.put("test", "YEP"); MatcherAssert.assertThat(TemplateProcessor.processTemplateResourceFile("/TestTemplateProcessorTemplateFile.tpl", map), Matchers.is("YEP")); } @Test(expected = IllegalArgumentException.class) public void testTemplateFile_withNonExistingFile() { Map<String, Object> map = new HashMap<String, Object>(); map.put("test", "YEP"); TemplateProcessor.processTemplateResourceFile("/XXX.tpl", map); }
AnnotationUtils { public static String[] getClassArrayAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType) { return getClassArrayAttributeFromAnnotationAsFqn(element, annotationType, "value"); } private AnnotationUtils(); static AnnotationValue getAnnotationValueOfAttribute(AnnotationMirror annotationMirror); static AnnotationValue getAnnotationValueOfAttribute(AnnotationMirror annotationMirror, String key); static AnnotationValue getAnnotationValueOfAttributeWithDefaults(AnnotationMirror annotationMirror); static String[] getMandatoryAttributeValueNames(AnnotationMirror annotationMirror); static String[] getOptionalAttributeValueNames(AnnotationMirror annotationMirror); static AnnotationValue getAnnotationValueOfAttributeWithDefaults(AnnotationMirror annotationMirror, String key); static ExecutableElement getExecutableElementForAnnotationAttributeName(AnnotationMirror annotationMirror, String key); static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType); static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType, String attributeName); static TypeMirror getClassAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType); static TypeMirror getClassAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType, String attributeName); static AnnotationMirror getAnnotationMirror(Element element, Class<? extends Annotation> clazz); static AnnotationMirror getAnnotationMirror(Element element, String fqClassName); static Element getElementForAnnotationMirror(AnnotationMirror annotationMirror); static String[] getClassArrayAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType); static String[] getClassArrayAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType, String attributeName); static TypeMirror[] getClassArrayAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType); static TypeMirror[] getClassArrayAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType, String attributeName); }
@Test public void annotationUtilsTest_arrayClassAttribute_emptyValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_empty") .getResult().get(0); MatcherAssert.assertThat(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class), Matchers.arrayWithSize(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_arrayClassAttribute_StringDoubleFloatValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_atDefaultValue") .getResult().get(0); MatcherAssert.assertThat(Arrays.asList(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class)), Matchers.contains(String.class.getCanonicalName(), Double.class.getCanonicalName(), Float.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_arrayClassAttributeWithExplicitAttributeName_LongIntegerValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_atNamedAttribute") .getResult().get(0); MatcherAssert.assertThat(Arrays.asList(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class, "classArrayAttribute")), Matchers.contains(Long.class.getCanonicalName(), Integer.class.getCanonicalName())); } }) .compilationShouldSucceed() .executeTest(); } @Test public void annotationUtilsTest_arrayClassAttributeWithExplicitAttributeName_LongIntegerAnnotationClassAttributeTestClassValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ANNOTATION).filterByAllOf(ClassArrayAttributeAnnotation.class) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .getResult(); Element testElement = FluentElementFilter.createFluentElementFilter(result) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("test_classArrayAttribute_atNamedAttribute_withUncompiledClass") .getResult().get(0); MatcherAssert.assertThat(Arrays.asList(AnnotationUtils.getClassArrayAttributeFromAnnotationAsFqn(testElement, ClassArrayAttributeAnnotation.class, "classArrayAttribute")), Matchers.contains(Long.class.getCanonicalName(), Integer.class.getCanonicalName(), "io.toolisticon.annotationprocessor.AnnotationClassAttributeTestClass")); } }) .compilationShouldSucceed() .executeTest(); }
BeanUtils { public static boolean isAttribute(VariableElement field) { return checkHasSetter(field) && checkHasGetter(field); } private BeanUtils(); static boolean hasDefaultNoargsConstructor(TypeElement typeElement); static boolean isDefaultNoargConstructor(ExecutableElement element); static boolean isAttribute(VariableElement field); static AttributeResult[] getAttributesWithInheritance(TypeElement typeElement); static AttributeResult[] getAttributes(TypeElement typeElement); static boolean checkHasGetter(VariableElement field); static boolean checkHasSetter(VariableElement field); static boolean checkLombokDataAnnotation(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnField(VariableElement variableElement); static String getGetterMethodName(VariableElement field); static String getSetterMethodName(VariableElement field); static String getPrefixedName(String prefix, String name); static boolean checkLombokSetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokSetterAnnotationOnField(VariableElement variableElement); }
@Test public void isAttribute_fieldWithBothGetterAndSetter() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/FieldLevelTestcases.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { VariableElement field = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_FIELD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("fieldWithImplementedGetterAndSetters") .getResult().get(0); MatcherAssert.assertThat("Must return true for field with getter and setter", BeanUtils.isAttribute(field)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void isAttribute_fieldWithoutSetter() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/FieldLevelTestcases.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { VariableElement field = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_FIELD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("fieldWithoutGetter") .getResult().get(0); MatcherAssert.assertThat("Must return true for field without setter", !BeanUtils.isAttribute(field)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void isAttribute_fieldWithoutGetter() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/FieldLevelTestcases.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { VariableElement field = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_FIELD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("fieldWithoutSetter") .getResult().get(0); MatcherAssert.assertThat("Must return true for field without getter", !BeanUtils.isAttribute(field)); } }) .compilationShouldSucceed() .executeTest(); }
BeanUtils { public static AttributeResult[] getAttributes(TypeElement typeElement) { if (typeElement == null) { return new AttributeResult[0]; } List<VariableElement> fields = FluentElementFilter.createFluentElementFilter(typeElement.getEnclosedElements()) .applyFilter(CoreMatchers.IS_FIELD) .applyFilter(CoreMatchers.BY_MODIFIER).filterByNoneOf(Modifier.STATIC) .getResult(); List<AttributeResult> result = new ArrayList<>(); for (VariableElement field : fields) { AttributeResult attributeResult = new AttributeResult(); attributeResult.setField(field); String getterMethodName = BeanUtils.getGetterMethodName(field); attributeResult.setGetterMethodName(BeanUtils.getGetterMethodName(field)); attributeResult.setSetterMethodName(BeanUtils.getSetterMethodName(field)); if (attributeResult.hasGetter() && attributeResult.hasSetter()) { result.add(attributeResult); } } return result.toArray(new AttributeResult[result.size()]); } private BeanUtils(); static boolean hasDefaultNoargsConstructor(TypeElement typeElement); static boolean isDefaultNoargConstructor(ExecutableElement element); static boolean isAttribute(VariableElement field); static AttributeResult[] getAttributesWithInheritance(TypeElement typeElement); static AttributeResult[] getAttributes(TypeElement typeElement); static boolean checkHasGetter(VariableElement field); static boolean checkHasSetter(VariableElement field); static boolean checkLombokDataAnnotation(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnField(VariableElement variableElement); static String getGetterMethodName(VariableElement field); static String getSetterMethodName(VariableElement field); static String getPrefixedName(String prefix, String name); static boolean checkLombokSetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokSetterAnnotationOnField(VariableElement variableElement); }
@Test public void getAttributes_withTypeHierarchy1() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/TypeHierarchyTestClass.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*InheritingType") .getResult().get(0); BeanUtils.AttributeResult[] results = BeanUtils.getAttributes(typeElement); Set<String> attributeNames = new HashSet<String>(); for (BeanUtils.AttributeResult result : results) { attributeNames.add(result.getFieldName()); } MatcherAssert.assertThat(attributeNames, Matchers.contains("booleanField", "stringField")); } }) .compilationShouldSucceed() .executeTest(); }
BeanUtils { public static AttributeResult[] getAttributesWithInheritance(TypeElement typeElement) { List<AttributeResult> resultList = new ArrayList<AttributeResult>(); resultList.addAll(Arrays.asList(GetAttributesCommand.INSTANCE.execute(typeElement))); for (TypeElement superTypeElement : ElementUtils.AccessTypeHierarchy.getSuperTypeElementsOfKindType(typeElement)) { resultList.addAll(Arrays.asList(GetAttributesCommand.INSTANCE.execute(superTypeElement))); } return resultList.toArray(new AttributeResult[resultList.size()]); } private BeanUtils(); static boolean hasDefaultNoargsConstructor(TypeElement typeElement); static boolean isDefaultNoargConstructor(ExecutableElement element); static boolean isAttribute(VariableElement field); static AttributeResult[] getAttributesWithInheritance(TypeElement typeElement); static AttributeResult[] getAttributes(TypeElement typeElement); static boolean checkHasGetter(VariableElement field); static boolean checkHasSetter(VariableElement field); static boolean checkLombokDataAnnotation(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokGetterAnnotationOnField(VariableElement variableElement); static String getGetterMethodName(VariableElement field); static String getSetterMethodName(VariableElement field); static String getPrefixedName(String prefix, String name); static boolean checkLombokSetterAnnotationOnType(TypeElement typeElement); static boolean checkLombokSetterAnnotationOnField(VariableElement variableElement); }
@Test public void getAttributes_withTypeHierarchy2() { unitTestBuilder .useSource(JavaFileObjectUtils.readFromResource("testcases.beanutils/TypeHierarchyTestClass.java")) .useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*InheritingType") .getResult().get(0); BeanUtils.AttributeResult[] results = BeanUtils.getAttributesWithInheritance(typeElement); Set<String> attributeNames = new HashSet<String>(); for (BeanUtils.AttributeResult result : results) { attributeNames.add(result.getFieldName()); } MatcherAssert.assertThat(attributeNames, Matchers.containsInAnyOrder("booleanField", "stringField", "superBooleanField", "superStringField")); } }) .compilationShouldSucceed() .executeTest(); }
GetAttributesCommandWithInheritance implements CommandWithReturnType<TypeElement, AttributeResult[]> { @Override public AttributeResult[] execute(TypeElement element) { return BeanUtils.getAttributesWithInheritance(element); } @Override AttributeResult[] execute(TypeElement element); final static GetAttributesCommandWithInheritance INSTANCE; }
@Test public void shouldExecuteSuccessfullyDataAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestDataAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyInheritedDataAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestInheritedDataAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(2)); Set<String> fields = new HashSet<String>(); for (BeanUtils.AttributeResult item : attributeResult) { fields.add(item.getFieldName()); } MatcherAssert.assertThat(fields, Matchers.containsInAnyOrder("field1", "field3")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustGetterAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullySetterAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustSetterAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestGetterAndSetterAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyMixedGetterAndSetterAnnotatedClassAndField2() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestMixedGetterAndSetterAnnotatedClassAndField1") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyMixedGetterAndSetterAnnotatedClassAndField2_() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestMixedGetterAndSetterAnnotatedClassAndField2") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAnnotatedField() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustGetterAnnotatedField") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullySetterAnnotatedField() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustSetterAnnotatedField") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedField() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestGetterAndSetterAnnotatedField") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedMethod() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestFieldGetterAndSetterMethods") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedMethodWithInvalidParameterType() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestFieldGetterAndSetterMethodsWithInvalidSetterParameterType") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommandWithInheritance.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); }
GetAttributesCommand implements CommandWithReturnType<TypeElement, AttributeResult[]> { @Override public AttributeResult[] execute(TypeElement element) { return BeanUtils.getAttributes(element); } @Override AttributeResult[] execute(TypeElement element); final static GetAttributesCommand INSTANCE; }
@Test public void shouldExecuteSuccessfullyDataAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestDataAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustGetterAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullySetterAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustSetterAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedClass() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestGetterAndSetterAnnotatedClass") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyMixedGetterAndSetterAnnotatedClassAndField2() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestMixedGetterAndSetterAnnotatedClassAndField1") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyMixedGetterAndSetterAnnotatedClassAndField2_() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestMixedGetterAndSetterAnnotatedClassAndField2") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAnnotatedField() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustGetterAnnotatedField") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullySetterAnnotatedField() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestJustSetterAnnotatedField") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedField() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestGetterAndSetterAnnotatedField") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedMethod() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestFieldGetterAndSetterMethods") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(1)); MatcherAssert.assertThat(attributeResult[0].getFieldName(), Matchers.is("field1")); } }) .compilationShouldSucceed() .executeTest(); } @Test public void shouldExecuteSuccessfullyGetterAndSetterAnnotatedMethodWithInvalidParameterType() { unitTestBuilder.useProcessor( new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.IS_CLASS) .applyFilter(CoreMatchers.BY_REGEX_NAME).filterByOneOf(".*TestFieldGetterAndSetterMethodsWithInvalidSetterParameterType") .getResult().get(0); BeanUtils.AttributeResult[] attributeResult = GetAttributesCommand.INSTANCE.execute(typeElement); MatcherAssert.assertThat(attributeResult.length, Matchers.is(0)); } }) .compilationShouldSucceed() .executeTest(); }
FluentElementFilter { public FluentElementFilter<ELEMENT> removeDuplicates() { return new FluentElementFilter<>((List<ELEMENT>) TransitionFilters.REMOVE_DUPLICATES_ELEMENTS.transition(elements)); } private FluentElementFilter(List<ELEMENT> elements); FluentElementFilter<TARGET_ELEMENT> applyFilter(IsCoreMatcher<ELEMENT, TARGET_ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(IsCoreMatcher<ELEMENT, TARGET_ELEMENT> coreMatcher); FluentElementFilter<TARGET_ELEMENT> applyFilter(IsElementBasedCoreMatcher<TARGET_ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(IsElementBasedCoreMatcher<TARGET_ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyFilter(ImplicitCoreMatcher<ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(ImplicitCoreMatcher<ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyFilter(ImplicitElementBasedCoreMatcher coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(ImplicitElementBasedCoreMatcher coreMatcher); InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA> applyFilter(InclusiveCriteriaCoreMatcher<ELEMENT, CRITERIA> coreMatcher); InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA> applyInvertedFilter(InclusiveCriteriaCoreMatcher<ELEMENT, CRITERIA> coreMatcher); InclusiveCriteriaFluentFilter<Element, CRITERIA> applyFilter(InclusiveCharacteristicElementBasedCoreMatcher<CRITERIA> coreMatcher); InclusiveCriteriaFluentFilter<Element, CRITERIA> applyInvertedFilter(InclusiveCharacteristicElementBasedCoreMatcher<CRITERIA> coreMatcher); ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC> applyFilter(ExclusiveCriteriaCoreMatcher<ELEMENT, CHARACTERISTIC> coreMatcher); ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC> applyInvertedFilter(ExclusiveCriteriaCoreMatcher<ELEMENT, CHARACTERISTIC> coreMatcher); ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC> applyFilter(ExclusiveCriteriaElementBasedCoreMatcher<CHARACTERISTIC> coreMatcher); ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC> applyInvertedFilter(ExclusiveCriteriaElementBasedCoreMatcher<CHARACTERISTIC> coreMatcher); FluentElementFilter<TARGET_ELEMENT> applyTransitionFilter(TransitionFilter<ELEMENT, TARGET_ELEMENT> transitionFilter); FluentElementFilter<TARGET_ELEMENT> applyTransitionFilter(ElementBasedTransitionFilter<TARGET_ELEMENT> transitionFilter); FluentElementFilter<ELEMENT> removeDuplicates(); void executeCommand(Command<ELEMENT> command); List<RETURN_TYPE> executeCommand(CommandWithReturnType<ELEMENT, RETURN_TYPE> command); List<ELEMENT> getResult(); boolean isEmpty(); boolean hasSingleElement(); boolean hasMultipleElements(); boolean hasSize(int size); int getResultSize(); static FluentElementFilter<E> createFluentElementFilter(List<E> elements); static FluentElementFilter<E> createFluentElementFilter(E... elements); }
@Test public void testRemoveDuplicates() { Element element = Mockito.mock(Element.class); MatcherAssert.assertThat("PRECONDITION : MUST contain double Elements", FluentElementFilter.createFluentElementFilter(element, element).getResult(), Matchers.contains(element, element)); MatcherAssert.assertThat(FluentElementFilter.createFluentElementFilter(element, element).removeDuplicates().getResult(), Matchers.contains(element)); }
FluentElementFilter { public void executeCommand(Command<ELEMENT> command) { if (command != null) { for (ELEMENT element : elements) { command.execute(element); } } } private FluentElementFilter(List<ELEMENT> elements); FluentElementFilter<TARGET_ELEMENT> applyFilter(IsCoreMatcher<ELEMENT, TARGET_ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(IsCoreMatcher<ELEMENT, TARGET_ELEMENT> coreMatcher); FluentElementFilter<TARGET_ELEMENT> applyFilter(IsElementBasedCoreMatcher<TARGET_ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(IsElementBasedCoreMatcher<TARGET_ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyFilter(ImplicitCoreMatcher<ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(ImplicitCoreMatcher<ELEMENT> coreMatcher); FluentElementFilter<ELEMENT> applyFilter(ImplicitElementBasedCoreMatcher coreMatcher); FluentElementFilter<ELEMENT> applyInvertedFilter(ImplicitElementBasedCoreMatcher coreMatcher); InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA> applyFilter(InclusiveCriteriaCoreMatcher<ELEMENT, CRITERIA> coreMatcher); InclusiveCriteriaFluentFilter<ELEMENT, CRITERIA> applyInvertedFilter(InclusiveCriteriaCoreMatcher<ELEMENT, CRITERIA> coreMatcher); InclusiveCriteriaFluentFilter<Element, CRITERIA> applyFilter(InclusiveCharacteristicElementBasedCoreMatcher<CRITERIA> coreMatcher); InclusiveCriteriaFluentFilter<Element, CRITERIA> applyInvertedFilter(InclusiveCharacteristicElementBasedCoreMatcher<CRITERIA> coreMatcher); ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC> applyFilter(ExclusiveCriteriaCoreMatcher<ELEMENT, CHARACTERISTIC> coreMatcher); ExclusiveCharacteristicFluentFilter<ELEMENT, CHARACTERISTIC> applyInvertedFilter(ExclusiveCriteriaCoreMatcher<ELEMENT, CHARACTERISTIC> coreMatcher); ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC> applyFilter(ExclusiveCriteriaElementBasedCoreMatcher<CHARACTERISTIC> coreMatcher); ExclusiveCharacteristicFluentFilter<Element, CHARACTERISTIC> applyInvertedFilter(ExclusiveCriteriaElementBasedCoreMatcher<CHARACTERISTIC> coreMatcher); FluentElementFilter<TARGET_ELEMENT> applyTransitionFilter(TransitionFilter<ELEMENT, TARGET_ELEMENT> transitionFilter); FluentElementFilter<TARGET_ELEMENT> applyTransitionFilter(ElementBasedTransitionFilter<TARGET_ELEMENT> transitionFilter); FluentElementFilter<ELEMENT> removeDuplicates(); void executeCommand(Command<ELEMENT> command); List<RETURN_TYPE> executeCommand(CommandWithReturnType<ELEMENT, RETURN_TYPE> command); List<ELEMENT> getResult(); boolean isEmpty(); boolean hasSingleElement(); boolean hasMultipleElements(); boolean hasSize(int size); int getResultSize(); static FluentElementFilter<E> createFluentElementFilter(List<E> elements); static FluentElementFilter<E> createFluentElementFilter(E... elements); }
@Test public void testExecuteCommand() { final Element element = Mockito.mock(Element.class); final ExecutionCounter executionCounter = new ExecutionCounter(); FluentElementFilter.createFluentElementFilter(element).executeCommand(new Command<Element>() { @Override public void execute(Element element1) { MatcherAssert.assertThat(element1, Matchers.is(element)); executionCounter.addExecution(); } }); MatcherAssert.assertThat(executionCounter.getCounter(),Matchers.is(1)); }
IsClassMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isClass(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingCase() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return true for class : ", CoreMatchers.IS_CLASS.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkMismatchingClass_enum() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(IsClassMatcherTest.class); List<Element> enums = ElementUtils.AccessEnclosedElements.getEnclosedElementsOfKind(typeElement, ElementKind.ENUM); MatcherAssert.assertThat("Precondition: must have found a enum", enums.size() >= 1); MatcherAssert.assertThat("Should return false for enum : ", !CoreMatchers.IS_CLASS.getMatcher().check(enums.get(0))); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkNullValuedElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for null valued element : ", !CoreMatchers.IS_CLASS.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); }
IsEnumMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isEnum(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingEnum() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(IsEnumMatcherTest.class); List<? extends Element> enumList = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(typeElement, "TestEnum"); MatcherAssert.assertThat("Precondition: must have found a enum", enumList.size() >= 1); MatcherAssert.assertThat("Should return true for enum : ", CoreMatchers.IS_ENUM.getMatcher().check(enumList.get(0))); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkMisatchingEnum_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non enum : ", !CoreMatchers.IS_ENUM.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkNullValuedElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for null valued element : ", !CoreMatchers.IS_ENUM.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); }
ByGenericTypeMatcher implements CriteriaMatcher<Element, GenericType> { @Override public String getStringRepresentationOfPassedCharacteristic(GenericType toGetStringRepresentationFor) { if (toGetStringRepresentationFor == null) { return null; } StringBuilder stringBuilder = new StringBuilder(); createStringRepresentationRecursively(stringBuilder, toGetStringRepresentationFor); return stringBuilder.toString(); } ByGenericTypeMatcher(); @Override boolean checkForMatchingCharacteristic(Element element, GenericType toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(GenericType toGetStringRepresentationFor); }
@Test public void getStringRepresentationOfPassedCharacteristic_createStringRepresentationCorrectly() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { GenericType genericTypeToConvert = TypeUtils.Generics.createGenericType(Map.class, TypeUtils.Generics.createWildcardWithExtendsBound( TypeUtils.Generics.createGenericType(StringBuilder.class) ), TypeUtils.Generics.createGenericType( Comparator.class, TypeUtils.Generics.createWildcardWithSuperBound( TypeUtils.Generics.createGenericType( List.class, TypeUtils.Generics.createPureWildcard() ) ) ) ); MatcherAssert.assertThat(CoreMatchers.BY_GENERIC_TYPE.getMatcher().getStringRepresentationOfPassedCharacteristic(genericTypeToConvert), org.hamcrest.Matchers.is("java.util.Map<? extends java.lang.StringBuilder, java.util.Comparator<? super java.util.List<?>>>")); } }) .compilationShouldSucceed() .executeTest(); }
ByGenericTypeMatcher implements CriteriaMatcher<Element, GenericType> { @Override public boolean checkForMatchingCharacteristic(Element element, GenericType toCheckFor) { return (element != null && toCheckFor != null) && TypeUtils.Generics.genericTypeEquals(element.asType(), toCheckFor); } ByGenericTypeMatcher(); @Override boolean checkForMatchingCharacteristic(Element element, GenericType toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(GenericType toGetStringRepresentationFor); }
@Test public void getStringRepresentationOfPassedCharacteristic_shouldBeAbleToCompareGenericType() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("testGenericsOnParameter") .getResult(); ExecutableElement method = ElementUtils.CastElement.castMethod(result.get(0)); GenericType genericType = TypeUtils.Generics.createGenericType(Map.class, TypeUtils.Generics.createGenericType(String.class), TypeUtils.Generics.createGenericType( Comparator.class, TypeUtils.Generics.createGenericType(Long.class) ) ); MatcherAssert.assertThat("Should compare successful", CoreMatchers.BY_GENERIC_TYPE.getMatcher().checkForMatchingCharacteristic(method.getParameters().get(0), genericType)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getStringRepresentationOfPassedCharacteristic_shoulNotdBeAbleToCompareGenericType() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("testGenericsOnParameter") .getResult(); ExecutableElement method = ElementUtils.CastElement.castMethod(result.get(0)); GenericType genericType = TypeUtils.Generics.createGenericType(Map.class, TypeUtils.Generics.createGenericType(String.class), TypeUtils.Generics.createGenericType( Comparator.class, TypeUtils.Generics.createGenericType(Double.class) ) ); MatcherAssert.assertThat("Should not compare successful", !CoreMatchers.BY_GENERIC_TYPE.getMatcher().checkForMatchingCharacteristic(method.getParameters().get(0), genericType)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getStringRepresentationOfPassedCharacteristic_shouldBeAbleToCompareGenericTypeWithWildcards() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("testGenericsOnParameter").getResult(); ExecutableElement method = ElementUtils.CastElement.castMethod(result.get(0)); GenericType genericType = TypeUtils.Generics.createGenericType(Map.class, TypeUtils.Generics.createWildcardWithExtendsBound( TypeUtils.Generics.createGenericType(StringBuilder.class) ), TypeUtils.Generics.createGenericType( Comparator.class, TypeUtils.Generics.createWildcardWithSuperBound( TypeUtils.Generics.createGenericType( List.class, TypeUtils.Generics.createPureWildcard() ) ) ) ); MatcherAssert.assertThat("Should compare successful", CoreMatchers.BY_GENERIC_TYPE.getMatcher().checkForMatchingCharacteristic(method.getParameters().get(1), genericType)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getStringRepresentationOfPassedCharacteristic_shouldNotBeAbleToCompareGenericTypeWithWildcards() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = FluentElementFilter.createFluentElementFilter(element.getEnclosedElements()) .applyFilter(CoreMatchers.BY_ELEMENT_KIND).filterByOneOf(ElementKind.METHOD) .applyFilter(CoreMatchers.BY_NAME).filterByOneOf("testGenericsOnParameter") .getResult(); ExecutableElement method = ElementUtils.CastElement.castMethod(result.get(0)); GenericType genericType = TypeUtils.Generics.createGenericType( Map.class, TypeUtils.Generics.createWildcardWithExtendsBound( TypeUtils.Generics.createGenericType(StringBuilder.class) ), TypeUtils.Generics.createGenericType( Comparator.class, TypeUtils.Generics.createWildcardWithSuperBound( TypeUtils.Generics.createGenericType( List.class, TypeUtils.Generics.createWildcardWithExtendsBound(TypeUtils.Generics.createGenericType(String.class)) ) ) ) ); MatcherAssert.assertThat("Should not compare successful", !CoreMatchers.BY_GENERIC_TYPE.getMatcher().checkForMatchingCharacteristic(method.getParameters().get(1), genericType)); } }) .compilationShouldSucceed() .executeTest(); }
AnnotationUtils { public static TypeMirror getClassAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType) { return getClassAttributeFromAnnotationAsTypeMirror(element, annotationType, "value"); } private AnnotationUtils(); static AnnotationValue getAnnotationValueOfAttribute(AnnotationMirror annotationMirror); static AnnotationValue getAnnotationValueOfAttribute(AnnotationMirror annotationMirror, String key); static AnnotationValue getAnnotationValueOfAttributeWithDefaults(AnnotationMirror annotationMirror); static String[] getMandatoryAttributeValueNames(AnnotationMirror annotationMirror); static String[] getOptionalAttributeValueNames(AnnotationMirror annotationMirror); static AnnotationValue getAnnotationValueOfAttributeWithDefaults(AnnotationMirror annotationMirror, String key); static ExecutableElement getExecutableElementForAnnotationAttributeName(AnnotationMirror annotationMirror, String key); static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType); static String getClassAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType, String attributeName); static TypeMirror getClassAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType); static TypeMirror getClassAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType, String attributeName); static AnnotationMirror getAnnotationMirror(Element element, Class<? extends Annotation> clazz); static AnnotationMirror getAnnotationMirror(Element element, String fqClassName); static Element getElementForAnnotationMirror(AnnotationMirror annotationMirror); static String[] getClassArrayAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType); static String[] getClassArrayAttributeFromAnnotationAsFqn(Element element, Class<? extends Annotation> annotationType, String attributeName); static TypeMirror[] getClassArrayAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType); static TypeMirror[] getClassArrayAttributeFromAnnotationAsTypeMirror(Element element, Class<? extends Annotation> annotationType, String attributeName); }
@Test public void getClassAttributeFromAnnotationAsTypeMirror_shouldGetClassAttributeSuccefully() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); TypeMirror result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, ClassAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match String : " , TypeUtils.TypeComparison.isTypeEqual(result, String.class)); result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, ClassAttributeAnnotation.class,"classAttribute"); MatcherAssert.assertThat(result, Matchers.notNullValue()); MatcherAssert.assertThat("Type must match Long : " , TypeUtils.TypeComparison.isTypeEqual(result, Long.class)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getClassAttributeFromAnnotationAsTypeMirror_shouldReturnNullForNonMatchingClassAttributes() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(ClassAttributeTestcase_WithCorrectClassAttribute.class); MatcherAssert.assertThat("PRECONDITION : TypeElement must exist", typeElement, Matchers.notNullValue()); TypeMirror result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, DefaultValueAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, DefaultValueAnnotation.class, "mandatoryValue"); MatcherAssert.assertThat(result, Matchers.nullValue()); result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, ClassArrayAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); result = AnnotationUtils.getClassAttributeFromAnnotationAsTypeMirror(typeElement, NoAttributeAnnotation.class); MatcherAssert.assertThat(result, Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); }
IsMethodMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isMethod(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingMethod() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(IsParameterMatcherTest.class); List<? extends Element> methods = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(typeElement, "testMethod"); MatcherAssert.assertThat("Precondition: found test method", methods.size() == 1); MatcherAssert.assertThat("Should return true for method : ", CoreMatchers.IS_METHOD.getMatcher().check(methods.get(0))); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkMismatchingMethod() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non method : ", !CoreMatchers.IS_METHOD.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkNullValuedElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for null valued element : ", !CoreMatchers.IS_METHOD.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); }
ByAnnotationMatcher implements CriteriaMatcher<Element, Class<? extends Annotation>> { @Override public String getStringRepresentationOfPassedCharacteristic(Class<? extends Annotation> toGetStringRepresentationFor) { return toGetStringRepresentationFor != null ? toGetStringRepresentationFor.getCanonicalName() : null; } @Override String getStringRepresentationOfPassedCharacteristic(Class<? extends Annotation> toGetStringRepresentationFor); @Override boolean checkForMatchingCharacteristic(Element element, Class<? extends Annotation> toCheckFor); }
@Test public void test_getStringRepresentationOfPassedCharacteristic_happyPath() { MatcherAssert.assertThat("Should return cannonical class name of annotation class", unit.getStringRepresentationOfPassedCharacteristic(TestAnnotation.class).equals(TestAnnotation.class.getCanonicalName())); } @Test public void test_getStringRepresentationOfPassedCharacteristic_passedNullValue() { MatcherAssert.assertThat("Should return null for null valued parameter", unit.getStringRepresentationOfPassedCharacteristic(null) == null); }
ByAnnotationMatcher implements CriteriaMatcher<Element, Class<? extends Annotation>> { @Override public boolean checkForMatchingCharacteristic(Element element, Class<? extends Annotation> toCheckFor) { return element != null && toCheckFor != null && element.getAnnotation(toCheckFor) != null; } @Override String getStringRepresentationOfPassedCharacteristic(Class<? extends Annotation> toGetStringRepresentationFor); @Override boolean checkForMatchingCharacteristic(Element element, Class<? extends Annotation> toCheckFor); }
@Test public void test_checkForMatchingCharacteristic_match() { TestAnnotation annotation = Mockito.mock(TestAnnotation.class); Element element = Mockito.mock(Element.class); Mockito.when(element.getAnnotation(TestAnnotation.class)).thenReturn(annotation); MatcherAssert.assertThat("Should find match correctly", unit.checkForMatchingCharacteristic(element, TestAnnotation.class)); } @Test public void test_checkForMatchingCharacteristic_mismatch() { TestAnnotation annotation = Mockito.mock(TestAnnotation.class); Element element = Mockito.mock(Element.class); Mockito.when(element.getAnnotation(TestAnnotation.class)).thenReturn(null); MatcherAssert.assertThat("Should find mismatch correctly", !unit.checkForMatchingCharacteristic(element, TestAnnotation.class)); } @Test public void test_checkForMatchingCharacteristic_nullValuedElement() { MatcherAssert.assertThat("Should retrun false in case of null valued element", !unit.checkForMatchingCharacteristic(null, TestAnnotation.class)); } @Test public void test_checkForMatchingCharacteristic_nullValuedAnnotationType() { Element element = Mockito.mock(Element.class); MatcherAssert.assertThat("Should retrun false in case of null valued annotation", !unit.checkForMatchingCharacteristic(element, null)); } @Test public void test_checkForMatchingCharacteristic_nullValuedParameters() { MatcherAssert.assertThat("Should retrun false in case of null valued parameters", !unit.checkForMatchingCharacteristic(null, null)); }
ByParameterTypeFqnMatcher implements CriteriaMatcher<ExecutableElement, String[]> { @Override public boolean checkForMatchingCharacteristic(ExecutableElement element, String[] toCheckFor) { if (element == null || toCheckFor == null) { return false; } if (element.getParameters().size() != toCheckFor.length) { return false; } for (int i = 0; i < element.getParameters().size(); i++) { TypeMirror parameterTypeMirror = TypeUtils.TypeRetrieval.getTypeMirror(toCheckFor[i]); if (parameterTypeMirror == null) { return false; } if (!element.getParameters().get(i).asType().equals(parameterTypeMirror)) { return false; } } return true; } ByParameterTypeFqnMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, String[] toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(String[] toGetStringRepresentationFor); }
@Test public void byParameterTypeMatcher_match() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: found method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Precondition: first parameter must be of type Boolean but is " + executableElement.getParameters().get(0).asType().toString(), executableElement.getParameters().get(0).asType().toString().equals(Boolean.class.getCanonicalName())); MatcherAssert.assertThat("Precondition: second parameter must be of type String but is " + executableElement.getParameters().get(1).asType().toString(), executableElement.getParameters().get(1).asType().toString().equals(String.class.getCanonicalName())); MatcherAssert.assertThat("Should have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(Boolean.class.getCanonicalName(), String.class.getCanonicalName()))); } }) .compilationShouldSucceed() .executeTest(); } @Test public void byParameterTypeMatcher_noMatch() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(String.class.getCanonicalName(), Boolean.class.getCanonicalName()))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(Boolean.class.getCanonicalName()))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().checkForMatchingCharacteristic(executableElement, Utilities.convertVarargsToArray(Boolean.class.getCanonicalName(), String.class.getCanonicalName(), String.class.getCanonicalName()))); } }) .compilationShouldSucceed() .executeTest(); } @Test public void byParameterTypeMatcher_nullValues() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { List<? extends Element> result = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(element, "methodWithReturnTypeAndParameters"); MatcherAssert.assertThat("Precondition: should have found one method", result.size() == 1); MatcherAssert.assertThat("Precondition: dound method has to be of zype ExecutableElement", result.get(0) instanceof ExecutableElement); ExecutableElement executableElement = ElementUtils.CastElement.castElementList(result, ExecutableElement.class).get(0); MatcherAssert.assertThat("Precondition: method must have 2 parameters", executableElement.getParameters().size() == 2); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().checkForMatchingCharacteristic(null, Utilities.convertVarargsToArray(String.class.getCanonicalName(), Boolean.class.getCanonicalName()))); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().checkForMatchingCharacteristic(executableElement, null)); MatcherAssert.assertThat("Should not have found matching parameters", !CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().checkForMatchingCharacteristic(null, null)); } }) .compilationShouldSucceed() .executeTest(); }
ByParameterTypeFqnMatcher implements CriteriaMatcher<ExecutableElement, String[]> { @Override public String getStringRepresentationOfPassedCharacteristic(String[] toGetStringRepresentationFor) { if (toGetStringRepresentationFor != null) { StringBuilder stringBuilder = new StringBuilder("["); boolean isFirst = true; for (String element : toGetStringRepresentationFor) { if (isFirst) { isFirst = false; } else { stringBuilder.append(", "); } stringBuilder.append(element); } stringBuilder.append("]"); return stringBuilder.toString(); } else { return null; } } ByParameterTypeFqnMatcher(); @Override boolean checkForMatchingCharacteristic(ExecutableElement element, String[] toCheckFor); @Override String getStringRepresentationOfPassedCharacteristic(String[] toGetStringRepresentationFor); }
@Test public void getStringRepresentationOfPassedCharacteristic_nullValue() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should not have found matching parameters", CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().getStringRepresentationOfPassedCharacteristic(null), Matchers.nullValue()); } }) .compilationShouldSucceed() .executeTest(); } @Test public void getStringRepresentationOfPassedCharacteristic_getStringRepreentation() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should have created valid string representation", CoreMatchers.BY_PARAMETER_TYPE_FQN.getMatcher().getStringRepresentationOfPassedCharacteristic(Utilities.convertVarargsToArray(String.class.getCanonicalName(), Boolean.class.getCanonicalName())), Matchers.is("[java.lang.String, java.lang.Boolean]")); } }) .compilationShouldSucceed() .executeTest(); }
IsParameterMatcher implements ImplicitMatcher<ELEMENT> { @Override public boolean check(ELEMENT element) { return ElementUtils.CheckKindOfElement.isParameter(element); } @Override boolean check(ELEMENT element); }
@Test public void checkMatchingParameter() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { TypeElement typeElement = TypeUtils.TypeRetrieval.getTypeElement(IsParameterMatcherTest.class); List<? extends Element> methods = ElementUtils.AccessEnclosedElements.getEnclosedElementsByName(typeElement, "testMethod"); MatcherAssert.assertThat("Precondition: found test method", methods.size() == 1); ExecutableElement testMethod = (ExecutableElement) methods.get(0); MatcherAssert.assertThat("Precondition: found at least one parameter", ((ExecutableElement) methods.get(0)).getParameters().size() >= 1); MatcherAssert.assertThat("Should return true for parameter : ", CoreMatchers.IS_PARAMETER.getMatcher().check(testMethod.getParameters().get(0))); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkMismatchingParameter_class() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for non parameter : ", !CoreMatchers.IS_PARAMETER.getMatcher().check(element)); } }) .compilationShouldSucceed() .executeTest(); } @Test public void checkNullValuedElement() { unitTestBuilder.useProcessor(new AbstractUnitTestAnnotationProcessorClass() { @Override protected void testCase(TypeElement element) { MatcherAssert.assertThat("Should return false for null valued element : ", !CoreMatchers.IS_PARAMETER.getMatcher().check(null)); } }) .compilationShouldSucceed() .executeTest(); }
TimerPresenter implements TimerActivityContract.UserActionsListener { @Override public void setTimer() { timer.set(calendar.getTimeInMillis()); view.close(); } TimerPresenter(Context context, DateFormat formatter, boolean is24HourFormat, Timer timer, TimerActivityContract.View view); @Override void setTimer(); @Override void cancelTimer(); @Override void undoTimer(); @Override void increaseTimerHour(); @Override void decreaseTimerHour(); @Override void increaseTimerMinute(); @Override void decreaseTimerMinute(); @Override void switchAmPm(); @Override void updateTime(); @Override void setupTitle(String timerMode); @Override long getTime(); @Override void setTime(long time); long getTimerDuration(); static void roundTimeUp(Calendar calendar); void setCalendar(Calendar calendar); static final int MINUTE_INCREMENT; static final int MINIMUM_INCREMENT; static final long TIME_INVALID; }
@Test public void setTimer_shouldSetTimerAndCloseView() { presenter.setTimer(); verify(timer).set(testCalendarPm.getTimeInMillis()); verify(view).close(); }
TimerPresenter implements TimerActivityContract.UserActionsListener { @Override public long getTime() { return calendar.getTimeInMillis(); } TimerPresenter(Context context, DateFormat formatter, boolean is24HourFormat, Timer timer, TimerActivityContract.View view); @Override void setTimer(); @Override void cancelTimer(); @Override void undoTimer(); @Override void increaseTimerHour(); @Override void decreaseTimerHour(); @Override void increaseTimerMinute(); @Override void decreaseTimerMinute(); @Override void switchAmPm(); @Override void updateTime(); @Override void setupTitle(String timerMode); @Override long getTime(); @Override void setTime(long time); long getTimerDuration(); static void roundTimeUp(Calendar calendar); void setCalendar(Calendar calendar); static final int MINUTE_INCREMENT; static final int MINIMUM_INCREMENT; static final long TIME_INVALID; }
@Test public void getTime_shouldReturnTimeInMillis() { assertThat(presenter.getTime(), is(testCalendarPm.getTimeInMillis())); }
TimerPresenter implements TimerActivityContract.UserActionsListener { public long getTimerDuration() { long now = System.currentTimeMillis(); return (calendar.getTimeInMillis() - now) / MINUTE_IN_MILLIS; } TimerPresenter(Context context, DateFormat formatter, boolean is24HourFormat, Timer timer, TimerActivityContract.View view); @Override void setTimer(); @Override void cancelTimer(); @Override void undoTimer(); @Override void increaseTimerHour(); @Override void decreaseTimerHour(); @Override void increaseTimerMinute(); @Override void decreaseTimerMinute(); @Override void switchAmPm(); @Override void updateTime(); @Override void setupTitle(String timerMode); @Override long getTime(); @Override void setTime(long time); long getTimerDuration(); static void roundTimeUp(Calendar calendar); void setCalendar(Calendar calendar); static final int MINUTE_INCREMENT; static final int MINIMUM_INCREMENT; static final long TIME_INVALID; }
@Test public void getTimerDuration() { long now = System.currentTimeMillis(); long duration = presenter.getTimerDuration(); assertThat(duration, is((presenter.getTime() - now) / MINUTE_IN_MILLIS)); }
Timer { public static String getFormattedDuration(Context context, long from, long to) { GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone(TIME_ZONE_GMT)); calendar.setTimeInMillis(to - from); Resources resources = context.getResources(); StringBuilder text = new StringBuilder(); int hours = calendar.get(Calendar.HOUR_OF_DAY); if (hours != 0) { final String quantityString = resources.getQuantityString(R.plurals.plurals_hours, hours, hours); text.append(quantityString); } int minutes = calendar.get(Calendar.MINUTE); if (minutes != 0 || text.length() == 0) { if (text.length() != 0) { text.append(' '); } text.append(resources.getQuantityString(R.plurals.plurals_minutes, minutes, minutes)); } return text.toString(); } Timer(Context context); static String getFormattedDuration(Context context, long from, long to); void set(long time); void cancel(); boolean isSet(); }
@Test public void getFormattedDuration_shouldFormatLessThanHour() { long from = System.currentTimeMillis(); long to = from + (long) (TIME_HOUR_MILLIS * 0.5); when(context.getResources()).thenReturn(resources); when(resources.getQuantityString(eq(R.plurals.plurals_minutes), anyInt(), anyInt())).thenReturn(MINUTE); when(resources.getQuantityString(eq(R.plurals.plurals_hours), anyInt(), anyInt())).thenReturn(HOUR); String result = String.valueOf(Timer.getFormattedDuration(context, from, to)); verify(resources, never()).getQuantityString(eq(R.plurals.plurals_hours), anyInt(), anyInt()); verify(resources).getQuantityString(R.plurals.plurals_minutes, 30, 30); assertThat(result, not(nullValue())); assertThat(result, not("")); assertThat(result, containsString(MINUTE)); assertThat(result, not(containsString(HOUR))); } @Test public void getFormattedDuration_shouldFormatMoreThanHour() { long from = System.currentTimeMillis(); long to = from + (long) (TIME_HOUR_MILLIS * 2.5); when(context.getResources()).thenReturn(resources); when(resources.getQuantityString(eq(R.plurals.plurals_minutes), anyInt(), anyInt())).thenReturn(MINUTE); when(resources.getQuantityString(eq(R.plurals.plurals_hours), anyInt(), anyInt())).thenReturn(HOUR); String result = Timer.getFormattedDuration(context, from, to); verify(resources).getQuantityString(R.plurals.plurals_hours, 2, 2); verify(resources).getQuantityString(R.plurals.plurals_minutes, 30, 30); assertThat(result, not(nullValue())); assertThat(result, not("")); assertThat(result, containsString(MINUTE)); assertThat(result, containsString(HOUR)); } @Test public void getFormattedDuration_shouldFormatOClockTime() { long from = System.currentTimeMillis(); long to = from + TIME_HOUR_MILLIS * 3; when(context.getResources()).thenReturn(resources); when(resources.getQuantityString(eq(R.plurals.plurals_minutes), anyInt(), anyInt())).thenReturn(MINUTE); when(resources.getQuantityString(eq(R.plurals.plurals_hours), anyInt(), anyInt())).thenReturn(HOUR); String result = String.valueOf(Timer.getFormattedDuration(context, from, to)); verify(resources).getQuantityString(R.plurals.plurals_hours, 3, 3); verify(resources, never()).getQuantityString(eq(R.plurals.plurals_minutes), anyInt(), anyInt()); assertThat(result, not(nullValue())); assertThat(result, not("")); assertThat(result, not(containsString(MINUTE))); assertThat(result, containsString(HOUR)); }
TimerPresenter implements TimerActivityContract.UserActionsListener { @Override public void cancelTimer() { timer.cancel(); view.close(); } TimerPresenter(Context context, DateFormat formatter, boolean is24HourFormat, Timer timer, TimerActivityContract.View view); @Override void setTimer(); @Override void cancelTimer(); @Override void undoTimer(); @Override void increaseTimerHour(); @Override void decreaseTimerHour(); @Override void increaseTimerMinute(); @Override void decreaseTimerMinute(); @Override void switchAmPm(); @Override void updateTime(); @Override void setupTitle(String timerMode); @Override long getTime(); @Override void setTime(long time); long getTimerDuration(); static void roundTimeUp(Calendar calendar); void setCalendar(Calendar calendar); static final int MINUTE_INCREMENT; static final int MINIMUM_INCREMENT; static final long TIME_INVALID; }
@Test public void cancelTimer_shouldCancelTimerAndCloseView() { presenter.cancelTimer(); verify(timer).cancel(); verify(view).close(); }
TimerPresenter implements TimerActivityContract.UserActionsListener { @Override public void undoTimer() { timer.cancel(); view.undoWifiState(); view.close(); } TimerPresenter(Context context, DateFormat formatter, boolean is24HourFormat, Timer timer, TimerActivityContract.View view); @Override void setTimer(); @Override void cancelTimer(); @Override void undoTimer(); @Override void increaseTimerHour(); @Override void decreaseTimerHour(); @Override void increaseTimerMinute(); @Override void decreaseTimerMinute(); @Override void switchAmPm(); @Override void updateTime(); @Override void setupTitle(String timerMode); @Override long getTime(); @Override void setTime(long time); long getTimerDuration(); static void roundTimeUp(Calendar calendar); void setCalendar(Calendar calendar); static final int MINUTE_INCREMENT; static final int MINIMUM_INCREMENT; static final long TIME_INVALID; }
@Test public void undoTimer_shouldRestoreWifiStateAndCloseView() { presenter.undoTimer(); verify(timer).cancel(); verify(view).undoWifiState(); verify(view).close(); }
TimerPresenter implements TimerActivityContract.UserActionsListener { public static void roundTimeUp(Calendar calendar) { calendar.set(Calendar.SECOND, 0); int remainder = calendar.get(Calendar.MINUTE) % MINUTE_INCREMENT; int increment = -remainder + MINUTE_INCREMENT; calendar.add(Calendar.MINUTE, increment); if (increment < MINIMUM_INCREMENT) { calendar.add(Calendar.MINUTE, MINUTE_INCREMENT); } } TimerPresenter(Context context, DateFormat formatter, boolean is24HourFormat, Timer timer, TimerActivityContract.View view); @Override void setTimer(); @Override void cancelTimer(); @Override void undoTimer(); @Override void increaseTimerHour(); @Override void decreaseTimerHour(); @Override void increaseTimerMinute(); @Override void decreaseTimerMinute(); @Override void switchAmPm(); @Override void updateTime(); @Override void setupTitle(String timerMode); @Override long getTime(); @Override void setTime(long time); long getTimerDuration(); static void roundTimeUp(Calendar calendar); void setCalendar(Calendar calendar); static final int MINUTE_INCREMENT; static final int MINIMUM_INCREMENT; static final long TIME_INVALID; }
@Test public void roundTimeUp_shouldRoundUpWhenLessThanMinimumIncrement() { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.MINUTE, TimerPresenter.MINIMUM_INCREMENT - 1); TimerPresenter.roundTimeUp(calendar); assertThat(calendar.get(Calendar.SECOND), is(0)); assertThat(calendar.get(Calendar.MINUTE), is(TimerPresenter.MINUTE_INCREMENT)); } @Test public void roundTimeUp_shouldRoundUpWhenMinimumIncrement() { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.MINUTE, TimerPresenter.MINIMUM_INCREMENT); TimerPresenter.roundTimeUp(calendar); assertThat(calendar.get(Calendar.SECOND), is(0)); assertThat(calendar.get(Calendar.MINUTE), is(TimerPresenter.MINUTE_INCREMENT)); } @Test public void roundTimeUp_shouldRoundUpWhenMoreThanMinimumIncrement() { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.MINUTE, TimerPresenter.MINIMUM_INCREMENT + 1); TimerPresenter.roundTimeUp(calendar); assertThat(calendar.get(Calendar.MINUTE), is(2 * TimerPresenter.MINUTE_INCREMENT)); } @Test public void roundTimeUp_shouldRoundUpAtLeastOfMinimumIncrement() { Calendar calendar; for (int minute = 0; minute < 60; ++minute) { calendar = new GregorianCalendar(); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, minute); long oldTime = calendar.getTimeInMillis(); TimerPresenter.roundTimeUp(calendar); final long increase = calendar.getTimeInMillis() - oldTime; assertThat("Should round up of at least " + TimerPresenter.MINIMUM_INCREMENT + " minutes failed on " + minute, increase, is(greaterThanOrEqualTo(TimerPresenter.MINIMUM_INCREMENT * MINUTE_IN_MILLIS))); assertThat("Should round up no more than " + TimerPresenter.MINIMUM_INCREMENT + " minutes failed on " + minute, increase, is(lessThan((TimerPresenter.MINUTE_INCREMENT + TimerPresenter.MINIMUM_INCREMENT) * MINUTE_IN_MILLIS))); } }
TimerPresenter implements TimerActivityContract.UserActionsListener { @Override public void setupTitle(String timerMode) { if (AppConfig.MODE_ON_WIFI_ACTIVATION.equals(timerMode)) { view.setDialogTitle(R.string.instructions_on_wifi_activation); } else { view.setDialogTitle(R.string.instructions_on_wifi_deactivation); } } TimerPresenter(Context context, DateFormat formatter, boolean is24HourFormat, Timer timer, TimerActivityContract.View view); @Override void setTimer(); @Override void cancelTimer(); @Override void undoTimer(); @Override void increaseTimerHour(); @Override void decreaseTimerHour(); @Override void increaseTimerMinute(); @Override void decreaseTimerMinute(); @Override void switchAmPm(); @Override void updateTime(); @Override void setupTitle(String timerMode); @Override long getTime(); @Override void setTime(long time); long getTimerDuration(); static void roundTimeUp(Calendar calendar); void setCalendar(Calendar calendar); static final int MINUTE_INCREMENT; static final int MINIMUM_INCREMENT; static final long TIME_INVALID; }
@Test public void setupTitle_shouldSetTitleWithDeactivationMode() { presenter.setupTitle(AppConfig.MODE_ON_WIFI_DEACTIVATION); verify(view).setDialogTitle(R.string.instructions_on_wifi_deactivation); } @Test public void setupTitle_shouldSetTitleWithActivationMode() { presenter.setupTitle(AppConfig.MODE_ON_WIFI_ACTIVATION); verify(view).setDialogTitle(R.string.instructions_on_wifi_activation); } @Test public void setupTitle_shouldHandleInvalidMode() { presenter.setupTitle(null); verify(view).setDialogTitle(R.string.instructions_on_wifi_deactivation); }
ProblemInjector implements ProblemInterceptor { public void handleRequest(final Request request) { for (ProblemInterceptorSupport interceptor : interceptorChain) { if (interceptor.isInjectProblem(request)) { interceptor.handleRequest(request); } } } ProblemInjector(); ProblemInjector(List<ProblemInterceptorSupport> chain); void handleRequest(final Request request); static final String ISSUE_HEADER; }
@Test public void handlerInvokedTest() throws Exception { when(request.getHeader(ProblemInjector.ISSUE_HEADER)).thenReturn("myError, otherError"); injector.handleRequest(request); verify(myProblemInterceptor).handleRequest(request); } @Test public void handlerNotInvokedTest() throws Exception { when(request.getHeader(ProblemInjector.ISSUE_HEADER)).thenReturn("otherError"); injector.handleRequest(request); verify(myProblemInterceptor, never()).handleRequest(request); }
FlightServiceImpl extends FlightService { @Override public Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId) { String id = keyGenerator.generate().toString(); Flight flight = new FlightImpl(id, flightSegmentId, scheduledDepartureTime, scheduledArrivalTime, firstClassBaseCost, economyClassBaseCost, numFirstClassSeats, numEconomyClassSeats, airplaneTypeId); try { flightRepository.save((FlightImpl) flight); return flight; } catch (Exception e) { throw new RuntimeException(e); } } @Override Long countFlights(); @Override Long countFlightSegments(); @Override Long countAirports(); @Override void storeAirportMapping(AirportCodeMapping mapping); @Override AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName); @Override Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId); @Override void storeFlightSegment(FlightSegment flightSeg); @Override void storeFlightSegment(String flightName, String origPort, String destPort, int miles); }
@Test public void createsNewFlight() { Flight newFlight = flightService.createNewFlight( flight.getFlightSegmentId(), flight.getScheduledDepartureTime(), flight.getScheduledArrivalTime(), flight.getFirstClassBaseCost(), flight.getEconomyClassBaseCost(), flight.getNumFirstClassSeats(), flight.getNumEconomyClassSeats(), flight.getAirplaneTypeId() ); assertThat(newFlight.getFlightId(), is(flight.getFlightId())); assertThat(newFlight.getFlightSegmentId(), is(flight.getFlightSegmentId())); assertThat(newFlight.getScheduledDepartureTime(), is(flight.getScheduledDepartureTime())); assertThat(newFlight.getScheduledArrivalTime(), is(flight.getScheduledArrivalTime())); assertThat(newFlight.getFirstClassBaseCost(), is(flight.getFirstClassBaseCost())); assertThat(newFlight.getEconomyClassBaseCost(), is(flight.getEconomyClassBaseCost())); assertThat(newFlight.getNumFirstClassSeats(), is(flight.getNumFirstClassSeats())); verify(flightRepository).save((FlightImpl) newFlight); }
BookingServiceImpl implements BookingService { @Override public void cancelBooking(String user, String bookingId) { try { bookingRepository.delete(bookingId); } catch (Exception e) { throw new RuntimeException(e); } } String bookFlight(String customerId, String flightId); @Override String bookFlight(String customerId, String flightSegmentId, String flightId); @Override Booking getBooking(String user, String bookingId); @Override List<Booking> getBookingsByUser(String user); @Override void cancelBooking(String user, String bookingId); @Override Long count(); }
@Test public void deletesBookingWhenCancelled() { bookingService.cancelBooking(booking.getCustomerId(), booking.getBookingId()); verify(bookingRepository).delete(booking.getBookingId()); }
BookingServiceImpl implements BookingService { public String bookFlight(String customerId, String flightId) { try { Flight f = flightService.getFlightByFlightId(flightId, null); CustomerInfo customerInfo = userService.getCustomerInfo(customerId); BookingImpl newBooking = new BookingImpl(keyGenerator.generate().toString(), new Date(), customerInfo, f); bookingRepository.save(newBooking); return newBooking.getBookingId(); } catch (Exception e) { throw new RuntimeException(e); } } String bookFlight(String customerId, String flightId); @Override String bookFlight(String customerId, String flightSegmentId, String flightId); @Override Booking getBooking(String user, String bookingId); @Override List<Booking> getBookingsByUser(String user); @Override void cancelBooking(String user, String bookingId); @Override Long count(); }
@Test public void getsBookingIdWhenFlightsBooked() { when(flightService.getFlightByFlightId(booking.getFlightId(), null)).thenReturn(flight); when(userService.getCustomerInfo(booking.getCustomerId())).thenReturn(customer); String bookingId = bookingService.bookFlight( booking.getCustomerId(), uniquify("flightSegmentId"), booking.getFlightId() ); assertThat(bookingId, is(booking.getBookingId())); }
BookingServiceImpl implements BookingService { @Override public List<Booking> getBookingsByUser(String user) { try { List<BookingImpl> bookingImpls = bookingRepository.findByCustomerId(user); List<Booking> bookings = new ArrayList<Booking>(); for (Booking b : bookingImpls) { bookings.add(b); } return bookings; } catch (Exception e) { throw new RuntimeException(e); } } String bookFlight(String customerId, String flightId); @Override String bookFlight(String customerId, String flightSegmentId, String flightId); @Override Booking getBooking(String user, String bookingId); @Override List<Booking> getBookingsByUser(String user); @Override void cancelBooking(String user, String bookingId); @Override Long count(); }
@Test public void getsBookingOfSpecifiedUser() { when(bookingRepository.findByCustomerId(booking.getCustomerId())).thenReturn(singletonList(booking)); List<Booking> bookings = bookingService.getBookingsByUser(booking.getCustomerId()); assertThat(bookings, contains(booking)); }
UserCommand implements UserService { @HystrixCommand public CustomerInfo getCustomerInfo(String customerId) { String address = getCustomerServiceAddress(); log.info("Sending GET request to remote customer at {} with customer id {}", address, customerId); ResponseEntity<CustomerInfo> resp = restTemplate.getForEntity(address + "/api/customer/{custid}", CustomerInfo.class, customerId); if (resp.getStatusCode() != HttpStatus.OK) { throw new NoSuchElementException("No such customer with id " + customerId); } log.info("Received response {} from remote customer at {} with customer id {}", resp.getBody(), address, customerId); return resp.getBody(); } UserCommand(RestTemplate restTemplate); @HystrixCommand CustomerInfo getCustomerInfo(String customerId); }
@Test @PactVerification public void fetchesExpectedCustomer() throws IOException { CustomerInfo actual = userService.getCustomerInfo(customerInfo.getId()); assertThat(actual, is(customerInfo)); }
BookingsREST { @GET @Path("/byuser/{user}") @Produces(MediaType.APPLICATION_JSON) public List<BookingInfo> getBookingsByUser(@PathParam("user") String user) { try { List<Booking> list = bs.getBookingsByUser(user); List<BookingInfo> newList = new ArrayList<BookingInfo>(); for (Booking b : list) { newList.add(new BookingInfo(b)); } return newList; } catch (Exception e) { e.printStackTrace(); return null; } } @POST @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) @Path("/bookflights") @Produces(MediaType.APPLICATION_JSON) BookingReceiptInfo bookFlights( @FormParam("userid") String userid, @FormParam("toFlightId") String toFlightId, @FormParam("toFlightSegId") String toFlightSegId, @FormParam("retFlightId") String retFlightId, @FormParam("retFlightSegId") String retFlightSegId, @FormParam("oneWayFlight") boolean oneWay); @GET @Path("/bybookingnumber/{userid}/{number}") @Produces(MediaType.APPLICATION_JSON) BookingInfo getBookingByNumber( @PathParam("number") String number, @PathParam("userid") String userid); @GET @Path("/byuser/{user}") @Produces(MediaType.APPLICATION_JSON) List<BookingInfo> getBookingsByUser(@PathParam("user") String user); @POST @Consumes({"application/x-www-form-urlencoded"}) @Path("/cancelbooking") @Produces(MediaType.APPLICATION_JSON) String cancelBookingsByNumber( @FormParam("number") String number, @FormParam("userid") String userid); }
@Test public void getsAllBookingOfSpecifiedUser() { when(bookingService.getBookingsByUser(userId)).thenReturn(singletonList(booking)); ResponseEntity<BookingInfo[]> responseEntity = restTemplate.getForEntity( "/rest/api/bookings/byuser/{user}", BookingInfo[].class, userId); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); assertThat(asList(responseEntity.getBody()), contains(new BookingInfo(booking))); }
FlightsREST { @POST @Path("/queryflights") @Consumes({"application/x-www-form-urlencoded"}) @Produces("application/json") public TripFlightOptions getTripFlights( @FormParam("fromAirport") String fromAirport, @FormParam("toAirport") String toAirport, @FormParam("fromDate") String fromDate, @FormParam("returnDate") String returnDate, @FormParam("oneWay") boolean oneWay) { Date formattedFromDate = formattedDate(fromDate, "From "); Date formattedReturnDate = formattedDate(returnDate, "Return "); TripFlightOptions options = new TripFlightOptions(); ArrayList<TripLegInfo> legs = new ArrayList<TripLegInfo>(); TripLegInfo toInfo = new TripLegInfo(); List<Flight> toFlights = flightService.getFlightByAirportsAndDate(fromAirport, toAirport, formattedFromDate); toInfo.addFlightsOptions(toFlights); legs.add(toInfo); toInfo.setCurrentPage(0); toInfo.setHasMoreOptions(false); toInfo.setNumPages(1); toInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); if (!oneWay) { TripLegInfo retInfo = new TripLegInfo(); List<Flight> retFlights = flightService.getFlightByAirportsAndDate(toAirport, fromAirport, formattedReturnDate); retInfo.addFlightsOptions(retFlights); legs.add(retInfo); retInfo.setCurrentPage(0); retInfo.setHasMoreOptions(false); retInfo.setNumPages(1); retInfo.setPageSize(TripLegInfo.DEFAULT_PAGE_SIZE); options.setTripLegs(2); } else { options.setTripLegs(1); } options.setTripFlights(legs); return options; } @POST @Path("/queryflights") @Consumes({"application/x-www-form-urlencoded"}) @Produces("application/json") TripFlightOptions getTripFlights( @FormParam("fromAirport") String fromAirport, @FormParam("toAirport") String toAirport, @FormParam("fromDate") String fromDate, @FormParam("returnDate") String returnDate, @FormParam("oneWay") boolean oneWay); @POST @Path("/browseflights") @Consumes({"application/x-www-form-urlencoded"}) @Produces("application/json") TripFlightOptions browseFlights( @FormParam("fromAirport") String fromAirport, @FormParam("toAirport") String toAirport, @FormParam("oneWay") boolean oneWay); }
@Test public void getsFlightsWithUnderlyingService() { when(flightService.getFlightByAirportsAndDate( departFlight.getFlightSegment().getOriginPort(), departFlight.getFlightSegment().getDestPort(), departFlight.getScheduledDepartureTime())).thenReturn(singletonList(departFlight)); when(flightService.getFlightByAirportsAndDate( departFlight.getFlightSegment().getDestPort(), departFlight.getFlightSegment().getOriginPort(), returnFlight.getScheduledDepartureTime())).thenReturn(singletonList(returnFlight)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add("fromAirport", departFlight.getFlightSegment().getOriginPort()); form.add("toAirport", departFlight.getFlightSegment().getDestPort()); form.add("fromDate", isoDateTime(departFlight.getScheduledDepartureTime())); form.add("returnDate", isoDateTime(returnFlight.getScheduledDepartureTime())); form.add("oneWay", String.valueOf(false)); ResponseEntity<TripFlightOptions> responseEntity = restTemplate.exchange( "/rest/api/flights/queryflights", HttpMethod.POST, new HttpEntity<>(form, headers), TripFlightOptions.class ); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); TripFlightOptions flightOptions = responseEntity.getBody(); assertThat(flightOptions.getTripLegs(), is(2)); List<TripLegInfo> tripFlights = flightOptions.getTripFlights(); assertThat(tripFlights.get(0).getFlightsOptions(), contains(toFlightInfo(departFlight))); assertThat(tripFlights.get(1).getFlightsOptions(), contains(toFlightInfo(returnFlight))); } @Test public void browsesFlightsWithUnderlyingService() { when(flightService.getFlightByAirports( departFlight.getFlightSegment().getOriginPort(), departFlight.getFlightSegment().getDestPort())).thenReturn(singletonList(departFlight)); when(flightService.getFlightByAirports( departFlight.getFlightSegment().getDestPort(), departFlight.getFlightSegment().getOriginPort())).thenReturn(singletonList(returnFlight)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add("fromAirport", departFlight.getFlightSegment().getOriginPort()); form.add("toAirport", departFlight.getFlightSegment().getDestPort()); form.add("oneWay", String.valueOf(false)); ResponseEntity<TripFlightOptions> responseEntity = restTemplate.exchange( "/rest/api/flights/browseflights", HttpMethod.POST, new HttpEntity<>(form, headers), TripFlightOptions.class ); assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK)); TripFlightOptions flightOptions = responseEntity.getBody(); assertThat(flightOptions.getTripLegs(), is(2)); List<TripLegInfo> tripFlights = flightOptions.getTripFlights(); assertThat(tripFlights.get(0).getFlightsOptions(), contains(toFlightInfo(departFlight))); assertThat(tripFlights.get(1).getFlightsOptions(), contains(toFlightInfo(returnFlight))); }
LoginCookieUpdateFilter extends ZuulFilter { @Override public boolean shouldFilter() { RequestContext ctx = RequestContext.getCurrentContext(); return ctx.getRequest().getRequestURI().endsWith("/api/login") && ctx.getResponseStatusCode() == 200 && ctx.getResponse().getHeader(SET_COOKIE) == null; } @Override String filterType(); @Override int filterOrder(); @Override boolean shouldFilter(); @Override Object run(); }
@Test public void skippedPathNotEndsWithLogin() { context.setResponseStatusCode(200); when(response.getHeader(SET_COOKIE)).thenReturn(null); when(request.getRequestURI()).thenReturn("/login"); assertThat(this.filter.shouldFilter(), is(false)); when(request.getRequestURI()).thenReturn("/api/login/validate"); assertThat(this.filter.shouldFilter(), is(false)); when(request.getRequestURI()).thenReturn("/api/login/"); assertThat(this.filter.shouldFilter(), is(false)); } @Test public void skippedWhenStatusIsNot200() { when(response.getHeader(SET_COOKIE)).thenReturn(null); when(request.getRequestURI()).thenReturn("/api/login"); when(response.getStatus()).thenReturn(404); assertThat(this.filter.shouldFilter(), is(false)); } @Test public void skippedWhenCookieHeaderIsNotNull() { context.setResponseStatusCode(200); when(request.getRequestURI()).thenReturn("/api/login"); when(response.getHeader(SET_COOKIE)).thenReturn("sessionid=abc"); assertThat(this.filter.shouldFilter(), is(false)); }
UriRewriteFilter extends ZuulFilter { @Override public boolean shouldFilter() { RequestContext context = RequestContext.getCurrentContext(); String uri = context.get("requestURI").toString(); return uri.startsWith("/rest/"); } @Override String filterType(); @Override int filterOrder(); @Override boolean shouldFilter(); @Override Object run(); }
@Test public void skippedIfRestNotInRequestURI() { context.set("requestURI", "/api/login"); assertThat(this.filter.shouldFilter(), is(false)); } @Test public void skippedIfRequestURINotStartsWithRest() { context.set("requestURI", "/abc/rest/api/login"); assertThat(this.filter.shouldFilter(), is(false)); }
CustomerServiceImpl extends CustomerServiceSupport { public Customer createCustomer(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddressImpl address) { CustomerImpl customer = new CustomerImpl(username, password, status, total_miles, miles_ytd, address, phoneNumber, phoneNumberType); customerRepository.save(customer); return customer; } @Override Long count(); @Override Long countSessions(); Customer createCustomer(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddressImpl address); CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode); @Override Customer updateCustomer(Customer customer); @Override void invalidateSession(String sessionid); }
@Test public void savesCustomerIntoDatabase() { Customer customer = customerService.createCustomer( this.customer.getCustomerId(), this.customer.getPassword(), this.customer.getStatus(), this.customer.getTotal_miles(), this.customer.getMiles_ytd(), this.customer.getPhoneNumber(), this.customer.getPhoneNumberType(), this.customer.getAddress() ); assertThat(customer, is(this.customer)); verify(customerRepository).save((CustomerImpl) customer); }
CustomerServiceImpl extends CustomerServiceSupport { public CustomerAddressImpl createAddress (String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode){ return new CustomerAddressImpl(streetAddress1, streetAddress2, city, stateProvince, country, postalCode); } @Override Long count(); @Override Long countSessions(); Customer createCustomer(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddressImpl address); CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode); @Override Customer updateCustomer(Customer customer); @Override void invalidateSession(String sessionid); }
@Test public void createsCustomerAddress() { CustomerAddress address = customerService.createAddress( this.address.getStreetAddress1(), this.address.getStreetAddress2(), this.address.getCity(), this.address.getStateProvince(), this.address.getCountry(), this.address.getPostalCode() ); assertThat(address, is(this.address)); }
CustomerServiceImpl extends CustomerServiceSupport { @Override protected CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration) { CustomerSessionImpl cSession = new CustomerSessionImpl(sessionId, customerId, creation, expiration); sessionRepository.save(cSession); return cSession; } @Override Long count(); @Override Long countSessions(); Customer createCustomer(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddressImpl address); CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode); @Override Customer updateCustomer(Customer customer); @Override void invalidateSession(String sessionid); }
@Test public void savesSessionIntoDatabase() { CustomerSession session = customerService.createSession(customer.getCustomerId()); Date now = new Date(); assertThat(session.getId(), is(sessionId)); assertThat(session.getCustomerid(), is(customer.getCustomerId())); assertThat(session.getTimeoutTime().after(now), is(true)); verify(sessionRepository).save((CustomerSessionImpl) session); }
CustomerServiceImpl extends CustomerServiceSupport { @Override public void invalidateSession(String sessionid) { sessionRepository.delete(sessionid); } @Override Long count(); @Override Long countSessions(); Customer createCustomer(String username, String password, MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber, PhoneType phoneNumberType, CustomerAddressImpl address); CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode); @Override Customer updateCustomer(Customer customer); @Override void invalidateSession(String sessionid); }
@Test public void deletesSessionFromDatabaseWhenInvalidated() { customerService.invalidateSession(sessionId); verify(sessionRepository).delete(sessionId); }
RemoteCustomerLoader implements CustomerLoader { @Override public void loadCustomers(long numCustomers) { restTemplate.postForEntity( getCustomerServiceAddress() + "/info/loader/load?number={numberOfCustomers}", null, String.class, numCustomers ); } RemoteCustomerLoader(RestTemplate restTemplate); @Override void loadCustomers(long numCustomers); }
@Test @PactVerification public void requestsRemoteToLoadCustomers() throws IOException { customerLoader.loadCustomers(5); }
FlightServiceImpl extends FlightService { @Override protected FlightSegment getFlightSegment(String fromAirport, String toAirport) { FlightSegment segment = flightSegmentRepository.findByOriginPortAndDestPort(fromAirport, toAirport); if (segment == null) { segment = new FlightSegmentImpl(); } return segment; } @Override Long countFlights(); @Override Long countFlightSegments(); @Override Long countAirports(); @Override void storeAirportMapping(AirportCodeMapping mapping); @Override AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName); @Override Flight createNewFlight(String flightSegmentId, Date scheduledDepartureTime, Date scheduledArrivalTime, BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost, int numFirstClassSeats, int numEconomyClassSeats, String airplaneTypeId); @Override void storeFlightSegment(FlightSegment flightSeg); @Override void storeFlightSegment(String flightName, String origPort, String destPort, int miles); }
@Test public void getsEmptyListIfNoFlightAvailableOnRequestedDate() { when(segmentRepository.findByOriginPortAndDestPort( flight.getFlightSegment().getOriginPort(), flight.getFlightSegment().getDestPort() )).thenReturn(((FlightSegmentImpl) flight.getFlightSegment())); List<Flight> flights = flightService.getFlightByAirportsAndDepartureDate( flight.getFlightSegment().getOriginPort(), flight.getFlightSegment().getDestPort(), new Date()); assertThat(flights.isEmpty(), is(true)); } @Test public void getsFlightsOnRequestedAirportAndDate() { when(segmentRepository.findByOriginPortAndDestPort( flight.getFlightSegment().getOriginPort(), flight.getFlightSegment().getDestPort() )).thenReturn(((FlightSegmentImpl) flight.getFlightSegment())); when(flightRepository.findByFlightSegmentIdAndScheduledDepartureTime( flight.getFlightSegment().getFlightName(), flight.getScheduledDepartureTime() )).thenReturn(singletonList(flight)); List<Flight> flights = flightService.getFlightByAirportsAndDepartureDate( flight.getFlightSegment().getOriginPort(), flight.getFlightSegment().getDestPort(), flight.getScheduledDepartureTime()); assertThat(flights, contains(flight)); } @Test public void getsFlightsOnRequestedAirport() { when(segmentRepository.findByOriginPortAndDestPort( flight.getFlightSegment().getOriginPort(), flight.getFlightSegment().getDestPort() )).thenReturn(((FlightSegmentImpl) flight.getFlightSegment())); when(flightRepository.findByFlightSegmentId(flight.getFlightSegment().getFlightName())).thenReturn(singletonList(flight)); List<Flight> flights = flightService.getFlightByAirports( flight.getFlightSegment().getOriginPort(), flight.getFlightSegment().getDestPort()); assertThat(flights, contains(flight)); }
SlimAdapter extends AbstractSlimAdapter { private boolean isTypeMatch(Type type, Type targetType) { if (type instanceof Class && targetType instanceof Class) { if (((Class) type).isAssignableFrom((Class) targetType)) { return true; } } else if (type instanceof ParameterizedType && targetType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; ParameterizedType parameterizedTargetType = (ParameterizedType) targetType; if (isTypeMatch(parameterizedType.getRawType(), ((ParameterizedType) targetType).getRawType())) { Type[] types = parameterizedType.getActualTypeArguments(); Type[] targetTypes = parameterizedTargetType.getActualTypeArguments(); if (types == null || targetTypes == null || types.length != targetTypes.length) { return false; } int len = types.length; for (int i = 0; i < len; i++) { if (!isTypeMatch(types[i], targetTypes[i])) { return false; } } return true; } } return false; } protected SlimAdapter(); static SlimAdapter create(); static T create(Class<T> clazz); SlimAdapter updateData(List<?> data); List<?> getData(); @Override Object getItem(int position); @Override int getItemCount(); SlimAdapter enableDiff(); SlimAdapter enableDiff(SlimDiffUtil.Callback diffCallback); @Override SlimViewHolder onCreateViewHolder(ViewGroup parent, int viewType); SlimAdapter registerDefault(final int layoutRes, final SlimInjector slimInjector); SlimAdapter register(final int layoutRes, final SlimInjector<T> slimInjector); SlimAdapter attachTo(RecyclerView... recyclerViews); @Override int getItemViewType(int position); SlimAdapter enableLoadMore(SlimMoreLoader slimMoreLoader); @Override void onAttachedToRecyclerView(RecyclerView recyclerView); @Override void onDetachedFromRecyclerView(RecyclerView recyclerView); }
@Test public void isTypeMatch() throws Exception { }
Traceur { public static void enableLogging() { enableLogging(new TraceurConfig(true)); } private Traceur(); static void enableLogging(); @SuppressWarnings({"unchecked", "rawtypes"}) synchronized static void enableLogging(TraceurConfig config); static synchronized void disableLogging(); static TraceurConfig getConfig(); }
@Test public void callSiteIsShownInStackTrace() throws Exception { try { StreamFactory.createNullPointerExceptionObservable().blockingFirst(); } catch (Throwable t) { final String exceptionAsString = exceptionAsString(t); printStackTrace("Default Stacktrace", exceptionAsString); assertThat(exceptionAsString).doesNotContain("StreamFactory"); } Traceur.enableLogging(); try { StreamFactory.createNullPointerExceptionObservable().blockingFirst(); Assertions.failBecauseExceptionWasNotThrown(Throwable.class); } catch (Throwable t) { final String exceptionAsString = exceptionAsString(t); printStackTrace("Traceur Stacktrace", exceptionAsString); assertThat(exceptionAsString).contains("StreamFactory"); } } @Test public void filtersStackTraces() throws Exception { Traceur.enableLogging(new TraceurConfig(false)); try { StreamFactory.createNullPointerExceptionObservable().blockingFirst(); Assertions.failBecauseExceptionWasNotThrown(Throwable.class); } catch (Throwable t) { final String exceptionAsString = exceptionAsString(t); printStackTrace("Exception without filtering", exceptionAsString); assertThat(exceptionAsString).contains("TraceurException.java"); assertThat(exceptionAsString).contains("ObservableOnAssembly.<init>"); } Traceur.enableLogging(new TraceurConfig(true)); try { StreamFactory.createNullPointerExceptionObservable().blockingFirst(); Assertions.failBecauseExceptionWasNotThrown(Throwable.class); } catch (Throwable t) { final String exceptionAsString = exceptionAsString(t); printStackTrace("Exception with filtering", exceptionAsString); assertThat(exceptionAsString).doesNotContain("TraceurException.java"); assertThat(exceptionAsString).doesNotContain("ObservableOnAssembly.<init>"); } } @Test public void usingRetryDoesNotFail() { Traceur.enableLogging(); StreamFactory.createNullPointerExceptionObservable() .doOnError(new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { } }) .retry(1) .test() .assertError(new Predicate<Throwable>() { @Override public boolean test(@NonNull Throwable throwable) throws Exception { return throwable instanceof NullPointerException && throwable.getCause() instanceof TraceurException; } }); }
RefsetImporter { public static IModuleDependencyRefset importModuleDependencyRefset( Set<InputStream> refsetFiles) throws ImportException { Set<ModuleDependencyRow> members = new HashSet<ModuleDependencyRow>(); for(InputStream refsetFile : refsetFiles) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(refsetFile)); String line = br.readLine(); String[] cols = line.split("[\t]"); assert(cols.length >= 6); if (cols.length == 8 && cols[6].equals("sourceEffectiveTime") && cols[7].equals("targetEffectiveTime")) { while (null != (line = br.readLine())) { cols = line.split("[\t]"); boolean active = cols[2].equals("1"); ModuleDependencyRow m = new ModuleDependencyRow(cols[0], cols[1], active , cols[3], cols[4], cols[5], cols[6], cols[7]); members.add(m); } } else { throw new ImportException("Malformed module dependency reference set with " + cols.length + " columns "+Arrays.asList(cols)); } } catch (IOException e) { log.error("Problem reading refset file "+refsetFile, e); throw new ImportException("Problem reading refset file ", e); } finally { if(br != null) { try { br.close(); } catch(Exception e) {} } } } try { return new ModuleDependencyRefset(members, !Boolean.getBoolean("mdrs.ignoreErrors")); } catch (ValidationException e) { throw new ImportException("Can not continue import with invalid MDRS", e); } } static IModuleDependencyRefset importModuleDependencyRefset( Set<InputStream> refsetFiles); }
@Test public void testImportModuleDependencyRefset() throws ImportException { Set<InputStream> refsetFiles = new HashSet<InputStream>(); refsetFiles.add(this.getClass().getResourceAsStream( "/der2_ssRefset_ModuleDependencyFull_AU1000036_20121130.txt")); IModuleDependencyRefset dr = RefsetImporter.importModuleDependencyRefset(refsetFiles); Map<String, Map<String, ModuleDependency>> deps = dr.getModuleDependencies(); ModuleDependency md = deps.get("32506021000036107").get("20121130"); Assert.assertEquals("32506021000036107", md.getId()); Assert.assertEquals("20121130", md.getVersion()); Assert.assertEquals(2, md.getDependencies().size()); Assert.assertTrue(md.getDependencies().contains(new ModuleDependency("900000000000207008", "20120731"))); Assert.assertTrue(md.getDependencies().contains(new ModuleDependency("900000000000012004", "20120731"))); md = deps.get("32570491000036106").get("20120531"); Assert.assertEquals("32570491000036106", md.getId()); Assert.assertEquals("20120531", md.getVersion()); Assert.assertEquals(3, md.getDependencies().size()); Assert.assertTrue(md.getDependencies().contains(new ModuleDependency("32506021000036107", "20120531"))); Assert.assertTrue(md.getDependencies().contains(new ModuleDependency("900000000000207008", "20120131"))); Assert.assertTrue(md.getDependencies().contains(new ModuleDependency("900000000000012004", "20120131"))); Assert.assertNull(deps.get("900000000000012004")); }
RF2Importer extends BaseImporter { @Override public Iterator<Ontology> getOntologyVersions(IProgressMonitor monitor) throws ImportException { return new OntologyInterator(monitor); } RF2Importer(RF2Input input); RF2Importer(Collection<Input> inputs); @Override Iterator<Ontology> getOntologyVersions(IProgressMonitor monitor); @Override List<String> getProblems(); }
@Test public void testExtractVersionRows() { try { final RF2Input input = new RF2Input(); input.setInputType(InputType.CLASSPATH); input.setReleaseType(ReleaseType.FULL); input.setModuleDependenciesRefsetFiles(Collections.singleton("/der2_ssRefset_ModuleDependencyFull_AU1000036_20121130.txt")); input.setConceptsFiles(Collections.singleton("/rf2_full_con_test.txt")); input.setRelationshipsFiles(Collections.singleton("/rf2_full_rel_test.txt")); final RF2Importer rf2i = new RF2Importer(input); final Iterator<Ontology> itr = rf2i.getOntologyVersions(null); while (itr.hasNext()) { Ontology o = itr.next(); System.err.println(o); } } catch(Exception e) { e.printStackTrace(); Assert.assertTrue(false); } }
RF1Importer extends BaseImporter { public VersionRows extractVersionRows() { List<ConceptRow> crs = new ArrayList<ConceptRow>(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(conceptsFile)); String line = br.readLine(); while (null != (line = br.readLine())) { line = new String(line.getBytes(), "UTF8"); if (line.trim().length() < 1) { continue; } int idx1 = line.indexOf('\t'); int idx2 = line.indexOf('\t', idx1 + 1); int idx3 = line.indexOf('\t', idx2 + 1); int idx4 = line.indexOf('\t', idx3 + 1); int idx5 = line.indexOf('\t', idx4 + 1); if (idx1 < 0 || idx2 < 0 || idx3 < 0 || idx4 < 0 || idx5 < 0) { br.close(); throw new RuntimeException( "Concepts: Mis-formatted " + "line, expected at least 6 tab-separated fields, " + "got: " + line); } final String conceptId = line.substring(0, idx1); final String conceptStatus = line.substring(idx1 + 1, idx2); final String fullySpecifiedName = line.substring(idx2 + 1, idx3); final String ctv3Id = line.substring(idx3 + 1, idx4); final String snomedId = line.substring(idx4 + 1, idx5); final String isPrimitive = line.substring(idx5 + 1); crs.add(new ConceptRow(conceptId, conceptStatus, fullySpecifiedName, ctv3Id, snomedId, isPrimitive)); } } catch (Exception e) { throw new RuntimeException(e); } finally { if(br != null) { try { br.close(); } catch(Exception e) {} } } List<RelationshipRow> rrs = new ArrayList<RelationshipRow>(); try { br = new BufferedReader( new InputStreamReader(relationshipsFile)); String line = br.readLine(); while (null != (line = br.readLine())) { if (line.trim().length() < 1) { continue; } int idx1 = line.indexOf('\t'); int idx2 = line.indexOf('\t', idx1 + 1); int idx3 = line.indexOf('\t', idx2 + 1); int idx4 = line.indexOf('\t', idx3 + 1); int idx5 = line.indexOf('\t', idx4 + 1); int idx6 = line.indexOf('\t', idx5 + 1); if (idx1 < 0 || idx2 < 0 || idx3 < 0 || idx4 < 0 || idx5 < 0 || idx6 < 0) { br.close(); throw new RuntimeException("Concepts: Mis-formatted " + "line, expected 7 tab-separated fields, " + "got: " + line); } final String relationshipId = line.substring(0, idx1); final String conceptId1 = line.substring(idx1 + 1, idx2); final String relationshipType = line.substring(idx2 + 1, idx3); final String conceptId2 = line.substring(idx3 + 1, idx4); final String characteristicType = line.substring(idx4 + 1, idx5); final String refinability = line.substring(idx5 + 1, idx6); final String relationshipGroup = line.substring(idx6 + 1); rrs.add(new RelationshipRow(relationshipId, conceptId1, relationshipType, conceptId2, characteristicType, refinability, relationshipGroup)); } } catch (Exception e) { throw new RuntimeException(e); } finally { if(br != null) { try { br.close(); } catch(Exception e) {} } } VersionRows vr = new VersionRows(version); vr.getConceptRows().addAll(crs); vr.getRelationshipRows().addAll(rrs); return vr; } RF1Importer(InputStream conceptsFile, InputStream relationshipsFile, String version); Iterator<Ontology> getOntologyVersions( IProgressMonitor monitor); void clear(); List<String> getProblems(); boolean usesConcreteDomains(); VersionRows extractVersionRows(); SnomedMetadata getMetadata(); }
@Test public void testExtractVersionRows() { try { RF1Importer rf1i = new RF1Importer( this.getClass().getResourceAsStream("/rf1_con_test.txt"), this.getClass().getResourceAsStream("/rf1_rel_test.txt"), "20110731"); VersionRows vr1 = rf1i.extractVersionRows(); Assert.assertEquals("20110731", vr1.getVersionName()); Assert.assertEquals(11, vr1.getConceptRows().size()); Assert.assertEquals(13, vr1.getRelationshipRows().size()); } catch(Exception e) { e.printStackTrace(); Assert.assertTrue(false); } }
ModuleDependencyRefset extends Refset implements IModuleDependencyRefset { @Override public Map<String, Map<String, ModuleDependency>> getModuleDependencies() { return dependencies; } ModuleDependencyRefset(Set<ModuleDependencyRow> members, boolean validate); @Override Map<String, Map<String, ModuleDependency>> getModuleDependencies(); }
@Test public void testIncomplete() throws ValidationException { Set<ModuleDependencyRow> members = new HashSet<ModuleDependencyRow>(); members.add(new ModuleDependencyRow("a", "20010101", true, "A", MDRS_ID, "B", "20010101", "10010101")); members.add(new ModuleDependencyRow("b", "10010101", true, "B", MDRS_ID, "C", "10010101", "10010101")); ModuleDependencyRefset mdrs = new ModuleDependencyRefset(members, true); Assert.assertEquals(2, mdrs.getModuleDependencies().size()); }
DialogManagerImpl implements DialogManager { @Override public boolean isDialogShowing(final int dialogId) { final Dialog dialog = mDialogInstances.get(dialogId); if (dialog != null) { return dialog.isShowing(); } final DialogFragment dialogFragment = mDialogFragmentInstances.get(dialogId); if (dialogFragment != null && dialogFragment.getDialog() != null) { return dialogFragment.getDialog().isShowing(); } return false; } DialogManagerImpl(@NonNull final FragmentManager fragmentManager); @Override void setCallback(@Nullable final DialogManagerCallback callback); @Nullable @Override DialogManagerCallback getCallback(); @Override void setListener(@Nullable final DialogManagerListener listener); @Nullable @Override DialogManagerListener getListener(); @Override void showDialog(final int dialogId); @Override void showDialog(final int dialogId, @Nullable final Bundle config); @Override void showDialogFragment(final int dialogId); @Override void showDialogFragment(final int dialogId, @Nullable final Bundle config); @Override boolean isDialogShowing(final int dialogId); @Override void dismissDialog(final int dialogId); @NonNull @Override Parcelable saveState(); @Override void restoreState(@Nullable final Parcelable state, final boolean showNow); @Override void recreateAll(final boolean showNow); @Override void unhideAll(); @Override void hideAll(); @Override void dismissAll(); @Override void dispose(); }
@Test public void isDialogShowing() { final DialogManagerCallback callback = createCallbackMock(); final Dialog dialogMock = createDialogMock(); when(callback.onCreateDialog(eq(KNOWN_DIALOG), isNull())).thenReturn(dialogMock); mDialogManager.setCallback(callback); mDialogManager.showDialog(KNOWN_DIALOG); assertTrue(mDialogManager.isDialogShowing(KNOWN_DIALOG)); dialogMock.hide(); assertFalse(mDialogManager.isDialogShowing(KNOWN_DIALOG)); }
DialogManagerImpl implements DialogManager { @Override public void dismissDialog(final int dialogId) { final Dialog dialog = mDialogInstances.get(dialogId); if (dialog != null) { dialog.dismiss(); mDialogInstances.remove(dialogId); mDialogConfigs.remove(dialogId); return; } final DialogFragment dialogFragment = mDialogFragmentInstances.get(dialogId); if (dialogFragment != null) { dialogFragment.dismiss(); mDialogFragmentInstances.remove(dialogId); mDialogConfigs.remove(dialogId); } } DialogManagerImpl(@NonNull final FragmentManager fragmentManager); @Override void setCallback(@Nullable final DialogManagerCallback callback); @Nullable @Override DialogManagerCallback getCallback(); @Override void setListener(@Nullable final DialogManagerListener listener); @Nullable @Override DialogManagerListener getListener(); @Override void showDialog(final int dialogId); @Override void showDialog(final int dialogId, @Nullable final Bundle config); @Override void showDialogFragment(final int dialogId); @Override void showDialogFragment(final int dialogId, @Nullable final Bundle config); @Override boolean isDialogShowing(final int dialogId); @Override void dismissDialog(final int dialogId); @NonNull @Override Parcelable saveState(); @Override void restoreState(@Nullable final Parcelable state, final boolean showNow); @Override void recreateAll(final boolean showNow); @Override void unhideAll(); @Override void hideAll(); @Override void dismissAll(); @Override void dispose(); }
@Test public void dismissDialog() { final DialogManagerCallback callback = createCallbackMock(); final Dialog dialogMock = createDialogMock(); when(callback.onCreateDialog(eq(KNOWN_DIALOG), isNull())).thenReturn(dialogMock); mDialogManager.setCallback(callback); mDialogManager.showDialog(KNOWN_DIALOG); assertTrue(mDialogManager.isDialogShowing(KNOWN_DIALOG)); mDialogManager.dismissDialog(KNOWN_DIALOG); assertFalse(mDialogManager.isDialogShowing(KNOWN_DIALOG)); }
DialogManagerImpl implements DialogManager { @Override public void recreateAll(final boolean showNow) { final Collection<DialogInfo> configs = new LinkedHashSet<>(mDialogConfigs.values()); dismissAll(); recreateFromConfigs(configs, showNow); } DialogManagerImpl(@NonNull final FragmentManager fragmentManager); @Override void setCallback(@Nullable final DialogManagerCallback callback); @Nullable @Override DialogManagerCallback getCallback(); @Override void setListener(@Nullable final DialogManagerListener listener); @Nullable @Override DialogManagerListener getListener(); @Override void showDialog(final int dialogId); @Override void showDialog(final int dialogId, @Nullable final Bundle config); @Override void showDialogFragment(final int dialogId); @Override void showDialogFragment(final int dialogId, @Nullable final Bundle config); @Override boolean isDialogShowing(final int dialogId); @Override void dismissDialog(final int dialogId); @NonNull @Override Parcelable saveState(); @Override void restoreState(@Nullable final Parcelable state, final boolean showNow); @Override void recreateAll(final boolean showNow); @Override void unhideAll(); @Override void hideAll(); @Override void dismissAll(); @Override void dispose(); }
@Test public void recreateAll() { final DialogManagerCallback callback = createCallbackMock(); final Dialog[] dialogMocks = new Dialog[]{createDialogMock(), createDialogMock()}; when(callback.onCreateDialog(eq(KNOWN_DIALOG), isNull())).thenReturn(dialogMocks[0]); when(callback.onCreateDialog(eq(ANOTHER_DIALOG), isNull())).thenReturn(dialogMocks[1]); mDialogManager.setCallback(callback); mDialogManager.showDialog(KNOWN_DIALOG); mDialogManager.showDialog(ANOTHER_DIALOG); assertTrue(mDialogManager.isDialogShowing(KNOWN_DIALOG)); assertTrue(mDialogManager.isDialogShowing(ANOTHER_DIALOG)); mDialogManager.hideAll(); assertFalse(mDialogManager.isDialogShowing(KNOWN_DIALOG)); assertFalse(mDialogManager.isDialogShowing(ANOTHER_DIALOG)); mDialogManager.recreateAll(true); assertTrue(mDialogManager.isDialogShowing(KNOWN_DIALOG)); assertTrue(mDialogManager.isDialogShowing(ANOTHER_DIALOG)); mDialogManager.dismissAll(); assertFalse(mDialogManager.isDialogShowing(KNOWN_DIALOG)); assertFalse(mDialogManager.isDialogShowing(ANOTHER_DIALOG)); }
DialogManagerImpl implements DialogManager { @Override public void dispose() { dismissAll(); mCallback = null; mListener = null; mFragmentManagerRef.clear(); } DialogManagerImpl(@NonNull final FragmentManager fragmentManager); @Override void setCallback(@Nullable final DialogManagerCallback callback); @Nullable @Override DialogManagerCallback getCallback(); @Override void setListener(@Nullable final DialogManagerListener listener); @Nullable @Override DialogManagerListener getListener(); @Override void showDialog(final int dialogId); @Override void showDialog(final int dialogId, @Nullable final Bundle config); @Override void showDialogFragment(final int dialogId); @Override void showDialogFragment(final int dialogId, @Nullable final Bundle config); @Override boolean isDialogShowing(final int dialogId); @Override void dismissDialog(final int dialogId); @NonNull @Override Parcelable saveState(); @Override void restoreState(@Nullable final Parcelable state, final boolean showNow); @Override void recreateAll(final boolean showNow); @Override void unhideAll(); @Override void hideAll(); @Override void dismissAll(); @Override void dispose(); }
@Test public void dispose() { mDialogManager.setCallback(createCallbackMock()); mDialogManager.setListener(createListenerMock()); mDialogManager.dispose(); assertNull(mDialogManager.getCallback()); assertNull(mDialogManager.getListener()); }
Rectangle { @Override public boolean equals(Object obj) { if (!(obj instanceof Rectangle)) return false; Rectangle otherRect = (Rectangle) obj; return origin.equals(otherRect.origin) && dimension.equals(otherRect.dimension); } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void equals() { assertEquals(new Rectangle(new Vector(1, 2), new Vector(2, 2)), new Rectangle(new Vector(1, 2), new Vector(2, 2))); assertFalse(new Rectangle(new Vector(1, 2), new Vector(2, 2)) .equals(new Rectangle(new Vector(1, 2), new Vector(2, 3)))); }
TreePath implements Comparable<TreePath<CompositeT>> { public boolean isEmpty() { return myPath.isEmpty(); } TreePath(CompositeT composite); TreePath(CompositeT from, CompositeT to); private TreePath(List<Integer> path); static void sort(List<? extends CompositeT> composites); static TreePath<CompositeT> deserialize(String text); CompositeT get(CompositeT root); boolean isValid(CompositeT root); boolean isEmpty(); int getLastIndex(); TreePath<CompositeT> getParent(); TreePath<CompositeT> getChild(int index); String serialize(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(TreePath<CompositeT> o); @Override String toString(); }
@Test public void isEmpty() { TreePath<TestComposite> path = new TreePath<>(child1, child1); assertTrue(path.isEmpty()); }
TreePath implements Comparable<TreePath<CompositeT>> { public int getLastIndex() { if (myPath.isEmpty()) { throw new IllegalStateException(); } return myPath.get(myPath.size() - 1); } TreePath(CompositeT composite); TreePath(CompositeT from, CompositeT to); private TreePath(List<Integer> path); static void sort(List<? extends CompositeT> composites); static TreePath<CompositeT> deserialize(String text); CompositeT get(CompositeT root); boolean isValid(CompositeT root); boolean isEmpty(); int getLastIndex(); TreePath<CompositeT> getParent(); TreePath<CompositeT> getChild(int index); String serialize(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(TreePath<CompositeT> o); @Override String toString(); }
@Test public void lastIndex() { TreePath<TestComposite> path = new TreePath<>(child2); assertEquals(1, path.getLastIndex()); }
TreePath implements Comparable<TreePath<CompositeT>> { public CompositeT get(CompositeT root) { if (!isValid(root)) { throw new IllegalStateException("Invalid context"); } CompositeT current = root; for (Integer i : myPath) { current = current.children().get(i); } return current; } TreePath(CompositeT composite); TreePath(CompositeT from, CompositeT to); private TreePath(List<Integer> path); static void sort(List<? extends CompositeT> composites); static TreePath<CompositeT> deserialize(String text); CompositeT get(CompositeT root); boolean isValid(CompositeT root); boolean isEmpty(); int getLastIndex(); TreePath<CompositeT> getParent(); TreePath<CompositeT> getChild(int index); String serialize(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(TreePath<CompositeT> o); @Override String toString(); }
@Test public void restoreFromNonRoot() { TestComposite composite = new TestComposite(); child1.children().add(composite); TreePath<TestComposite> path = new TreePath<>(composite, child1); assertSame(composite, path.get(child1)); } @Test public void saveRestore() { TreePath<TestComposite> path1 = new TreePath<>(child1); assertSame(child1, path1.get(root)); }
BaseId implements Serializable { @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj.getClass() != getClass()) return false; BaseId otherId = (BaseId) obj; return Objects.equals(getId(), otherId.getId()); } protected BaseId(); protected BaseId(String id); protected BaseId(String id, String name); String getId(); String getName(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void idEquality() { MyId id1 = new MyId("abc.def"); MyId id2 = new MyId("abc.defz"); MyId id3 = new MyId("abc.def"); assertEquals(id1, id3); assertFalse(id2.equals(id3)); }
BaseId implements Serializable { public String getName() { return ourNames.get(myId); } protected BaseId(); protected BaseId(String id); protected BaseId(String id, String name); String getId(); String getName(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void nameDiscovery () { new MyId("e.f", "newName1"); MyId id2 = new MyId("e.f"); assertEquals("newName1", id2.getName()); }
BaseId implements Serializable { @Override public String toString() { String name = getName(); return name != null ? name + " [" + getId() + "]" : getId(); } protected BaseId(); protected BaseId(String id); protected BaseId(String id, String name); String getId(); String getName(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test public void stringRepresentation() { assertEquals("newName1 [g.h]", new MyId("g.h", "newName1").toString()); assertEquals("i.j", new MyId("i.j").toString()); }
BaseId implements Serializable { public String getId() { return myId; } protected BaseId(); protected BaseId(String id); protected BaseId(String id, String name); String getId(); String getName(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Slow @Test public void idRandomness() { int[] stats = new int[128]; for (int i = 0; i < 62000; i++) { String id = new BaseId() {}.getId(); for (int j = 0; j < id.length(); j++) { stats[id.charAt(j)] ++; } } checkUniform(stats, 'A', 'Z', 22000); checkUniform(stats, 'a', 'z', 22000); checkUniform(stats, '0', '9', 22000); }
Listeners { public Registration add(final ListenerT l) { if (isEmpty()) { beforeFirstAdded(); } if (myFireDepth > 0) { myListeners.add(new ListenerOp<>(l, true)); } else { if (myListeners == null) { myListeners = new ArrayList<>(1); } myListeners.add(l); myListenersCount++; } return new Registration() { @Override protected void doRemove() { if (myFireDepth > 0) { myListeners.add(new ListenerOp<>(l, false)); } else { myListeners.remove(l); myListenersCount--; } if (isEmpty()) { afterLastRemoved(); } } }; } boolean isEmpty(); Registration add(final ListenerT l); void fire(ListenerCaller<ListenerT> h); }
@Test public void addAndRemoveRegistrationInFire() { myListeners.add(new Listener() { @Override public void act() { myListeners.add(createInnerListener()).remove(); } }); fireAndCheck(1); } @Test public void addRemoveAddInFire() { myListeners.add(new Listener() { @Override public void act() { Listener l = createInnerListener(); myListeners.add(l).remove(); myListeners.add(l); } }); fireAndCheck(2); }
CompositeRegistration extends Registration { public CompositeRegistration add(Registration r) { myRegistrations.add(r); return this; } CompositeRegistration(Registration... regs); CompositeRegistration add(Registration r); CompositeRegistration add(Registration... rs); boolean isEmpty(); }
@Test public void removalOrderManualAdd() { CompositeRegistration r = new CompositeRegistration(); r.add(createReg(1)).add(createReg(0)); r.remove(); assertEquals(2, myRemoveCounter); }
Vector { public Vector sub(Vector v) { return add(v.negate()); } Vector(int x, int y); Vector add(Vector v); Vector sub(Vector v); Vector negate(); Vector max(Vector v); Vector min(Vector v); Vector mul(int i); Vector div(int i); int dotProduct(Vector v); double length(); DoubleVector toDoubleVector(); Vector abs(); boolean isParallel(Vector to); Vector orthogonal(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); int getX(); int getY(); int get(Axis axis); static final Vector ZERO; final int x; final int y; }
@Test public void sub() { assertThat(new Vector(1, 2).sub(new Vector(2, 2)), is(new Vector(-1, 0))); }
MappingContext { public <ValueT> ValueT get(MappingContextProperty<ValueT> property) { Object value = myProperties.get(property); if (value == null) { throw new IllegalStateException("Property " + property + " wasn't found"); } @SuppressWarnings("unchecked") ValueT result = (ValueT) value; return result; } Registration addListener(MappingContextListener l); Mapper<? super S, ?> getMapper(Mapper<?, ?> ancestor, S source); Set<Mapper<? super S, ?>> getMappers(Mapper<?, ?> ancestor, S source); void put(MappingContextProperty<ValueT> property, ValueT value); ValueT get(MappingContextProperty<ValueT> property); boolean contains(MappingContextProperty<?> property); ValueT remove(MappingContextProperty<ValueT> property); static final MappingContextProperty<CompositeRegistration> ON_DISPOSE; }
@Test(expected = IllegalStateException.class) public void unknownPropertyFails() { context.get(TEST); }
MappingContext { public <ValueT> ValueT remove(MappingContextProperty<ValueT> property) { if (!myProperties.containsKey(property)) { throw new IllegalStateException("Property " + property + " wasn't found"); } @SuppressWarnings("unchecked") ValueT result = (ValueT) myProperties.remove(property); return result; } Registration addListener(MappingContextListener l); Mapper<? super S, ?> getMapper(Mapper<?, ?> ancestor, S source); Set<Mapper<? super S, ?>> getMappers(Mapper<?, ?> ancestor, S source); void put(MappingContextProperty<ValueT> property, ValueT value); ValueT get(MappingContextProperty<ValueT> property); boolean contains(MappingContextProperty<?> property); ValueT remove(MappingContextProperty<ValueT> property); static final MappingContextProperty<CompositeRegistration> ON_DISPOSE; }
@Test(expected = IllegalStateException.class) public void removeUnknownProperty() { context.remove(TEST); }
MappingContext { public <ValueT> void put(MappingContextProperty<ValueT> property, ValueT value) { if (myProperties.containsKey(property)) { throw new IllegalStateException("Property " + property + " is already defined"); } if (value == null) { throw new IllegalArgumentException("Trying to set null as a value of " + property); } myProperties.put(property, value); } Registration addListener(MappingContextListener l); Mapper<? super S, ?> getMapper(Mapper<?, ?> ancestor, S source); Set<Mapper<? super S, ?>> getMappers(Mapper<?, ?> ancestor, S source); void put(MappingContextProperty<ValueT> property, ValueT value); ValueT get(MappingContextProperty<ValueT> property); boolean contains(MappingContextProperty<?> property); ValueT remove(MappingContextProperty<ValueT> property); static final MappingContextProperty<CompositeRegistration> ON_DISPOSE; }
@Test(expected = IllegalStateException.class) public void putAllowedOnce() { context.put(TEST, "value"); context.put(TEST, "another value"); } @Test(expected = IllegalArgumentException.class) public void nullNotAllowed() { context.put(TEST, null); }
ByTargetIndex implements Disposable { @Override public void dispose() { myRegistration.remove(); } ByTargetIndex(MappingContext ctx); Collection<Mapper<?, ?>> getMappers(Object target); @Override void dispose(); static final MappingContextProperty<ByTargetIndex> KEY; }
@Test public void addWhenFinderDisposed() { finder.dispose(); Item anotherChild = new Item(); child.getObservableChildren().add(anotherChild); assertNotFound(anotherChild); }
Mapper { public final void detachRoot() { if (myMappingContext == null) { throw new IllegalStateException(); } if (myParent != null) { throw new IllegalStateException("Dispose can be called only on the root mapper"); } detach(); } protected Mapper(SourceT source, TargetT target); final Mapper<?, ?> getParent(); final boolean isAttached(); final MappingContext getMappingContext(); final Mapper<? super S, ?> getDescendantMapper(S source); final SourceT getSource(); final TargetT getTarget(); final void attachRoot(); final void attachRoot(MappingContext ctx); final void detachRoot(); final Iterable<Synchronizer> synchronizers(); final Iterable<Mapper<?, ?>> children(); final ObservableList<MapperT> createChildList(); final ObservableSet<MapperT> createChildSet(); final Property<MapperT> createChildProperty(); }
@Test public void rolesAreCleanedOnDetach() { assertFalse(target.getObservableChildren().isEmpty()); assertFalse(target.getChildren().isEmpty()); assertFalse(target.getTransformedChildren().isEmpty()); mapper.detachRoot(); assertTrue(target.getObservableChildren().isEmpty()); assertTrue(target.getChildren().isEmpty()); assertTrue(target.getTransformedChildren().isEmpty()); }
Synchronizers { public static Synchronizer forEventSource(final EventSource<?> src, final Runnable r) { return new RegistrationSynchronizer() { @Override protected Registration doAttach(SynchronizerContext ctx) { r.run(); return src.addHandler(new EventHandler<Object>() { @Override public void onEvent(Object event) { r.run(); } }); } }; } private Synchronizers(); static SimpleRoleSynchronizer<SourceT, TargetT> forSimpleRole( Mapper<?, ?> mapper, List<SourceT> source, List<TargetT> target, MapperFactory<SourceT, TargetT> factory); static RoleSynchronizer<MappedT, TargetT> forObservableRole( Mapper<?, ?> mapper, SourceT source, Transformer<SourceT, ObservableList<MappedT>> transformer, List<TargetItemT> target, MapperFactory<MappedT, TargetT> factory); static RoleSynchronizer<SourceT, TargetT> forObservableRole( Mapper<?, ?> mapper, ObservableList<SourceT> source, List<TargetItemT> target, MapperFactory<SourceT, TargetT> factory); static RoleSynchronizer<SourceT, KindTargetT> forConstantRole( Mapper<?, ?> mapper, final SourceT source, final List<TargetT> target, MapperFactory<SourceT, KindTargetT> factory); static RoleSynchronizer<SourceT, TargetT> forSingleRole( Mapper<?, ?> mapper, ReadableProperty<SourceT> source, WritableProperty<TargetT> target, MapperFactory<SourceT, TargetT> factory); static Synchronizer forPropsOneWay(final ReadableProperty<? extends ValueT> source, final WritableProperty<? super ValueT> target); static Synchronizer forPropsTwoWay(final Property<ValueT> source, final Property<ValueT> target); static Synchronizer forProperty(ReadableProperty<ValueT> property, Runnable sync); static Synchronizer forCollection( final ObservableCollection<ElementT> collection, final Runnable sync); static Synchronizer forRegistration(final Supplier<Registration> reg); static Synchronizer forRegistration(final Registration r); static Synchronizer forDisposable(final Disposable disposable); static Synchronizer forDisposables(final Disposable... disposables); static Synchronizer composite(final Synchronizer... syncs); static Synchronizer forEventSource(final EventSource<?> src, final Runnable r); static Synchronizer forEventSource(final EventSource<EventT> src, final Consumer<EventT> h); static Synchronizer measuringSynchronizer(final String name, final Synchronizer sync); static Synchronizer empty(); }
@Test public void forEventSourceOnAttach() { final Value<Integer> runNum = new Value<>(0); Property<Boolean> prop = new ValueProperty<>(); final Synchronizer synchronizer = Synchronizers.forEventSource(prop, new Runnable() { @Override public void run() { runNum.set(runNum.get() + 1); } }); Mapper<Void, Void> mapper = new Mapper<Void, Void>(null, null) { @Override protected void registerSynchronizers(SynchronizersConfiguration conf) { super.registerSynchronizers(conf); conf.add(synchronizer); } }; mapper.attachRoot(); assertEquals(1, (int) runNum.get()); } @Test public void forEventSourceHandler() { final Property<Integer> prop = new ValueProperty<>(); final List<Integer> handled = new ArrayList<>(); Mapper<Void, Void> mapper = new Mapper<Void, Void>(null, null) { @Override protected void registerSynchronizers(SynchronizersConfiguration conf) { super.registerSynchronizers(conf); conf.add(Synchronizers.forEventSource( prop, new Consumer<PropertyChangeEvent<Integer>>() { @Override public void accept(PropertyChangeEvent<Integer> item) { handled.add(item.getNewValue()); } })); } }; mapper.attachRoot(); assertTrue(handled.isEmpty()); prop.set(1); prop.set(2); prop.set(3); assertEquals(Arrays.asList(1, 2, 3), handled); mapper.detachRoot(); prop.set(4); assertEquals(Arrays.asList(1, 2, 3), handled); }
Synchronizers { public static <ValueT> Synchronizer forPropsOneWay(final ReadableProperty<? extends ValueT> source, final WritableProperty<? super ValueT> target) { return new RegistrationSynchronizer() { @Override protected Registration doAttach(SynchronizerContext ctx) { target.set(source.get()); return source.addHandler(new EventHandler<PropertyChangeEvent<? extends ValueT>>() { @Override public void onEvent(PropertyChangeEvent<? extends ValueT> event) { target.set(event.getNewValue()); } }); } }; } private Synchronizers(); static SimpleRoleSynchronizer<SourceT, TargetT> forSimpleRole( Mapper<?, ?> mapper, List<SourceT> source, List<TargetT> target, MapperFactory<SourceT, TargetT> factory); static RoleSynchronizer<MappedT, TargetT> forObservableRole( Mapper<?, ?> mapper, SourceT source, Transformer<SourceT, ObservableList<MappedT>> transformer, List<TargetItemT> target, MapperFactory<MappedT, TargetT> factory); static RoleSynchronizer<SourceT, TargetT> forObservableRole( Mapper<?, ?> mapper, ObservableList<SourceT> source, List<TargetItemT> target, MapperFactory<SourceT, TargetT> factory); static RoleSynchronizer<SourceT, KindTargetT> forConstantRole( Mapper<?, ?> mapper, final SourceT source, final List<TargetT> target, MapperFactory<SourceT, KindTargetT> factory); static RoleSynchronizer<SourceT, TargetT> forSingleRole( Mapper<?, ?> mapper, ReadableProperty<SourceT> source, WritableProperty<TargetT> target, MapperFactory<SourceT, TargetT> factory); static Synchronizer forPropsOneWay(final ReadableProperty<? extends ValueT> source, final WritableProperty<? super ValueT> target); static Synchronizer forPropsTwoWay(final Property<ValueT> source, final Property<ValueT> target); static Synchronizer forProperty(ReadableProperty<ValueT> property, Runnable sync); static Synchronizer forCollection( final ObservableCollection<ElementT> collection, final Runnable sync); static Synchronizer forRegistration(final Supplier<Registration> reg); static Synchronizer forRegistration(final Registration r); static Synchronizer forDisposable(final Disposable disposable); static Synchronizer forDisposables(final Disposable... disposables); static Synchronizer composite(final Synchronizer... syncs); static Synchronizer forEventSource(final EventSource<?> src, final Runnable r); static Synchronizer forEventSource(final EventSource<EventT> src, final Consumer<EventT> h); static Synchronizer measuringSynchronizer(final String name, final Synchronizer sync); static Synchronizer empty(); }
@Test public void forPropsOneWay() { final Property<Integer> integerProperty = new ValueProperty<>(); final Property<Number> numberProperty = new ValueProperty<>(); Mapper<Void, Void> mapper = new Mapper<Void, Void>(null, null) { @Override protected void registerSynchronizers(SynchronizersConfiguration conf) { super.registerSynchronizers(conf); conf.add(Synchronizers.forPropsOneWay(integerProperty, numberProperty)); } }; mapper.attachRoot(); integerProperty.set(1); assertEquals(1, numberProperty.get()); }
Vector { public Vector negate() { return new Vector(-x, -y); } Vector(int x, int y); Vector add(Vector v); Vector sub(Vector v); Vector negate(); Vector max(Vector v); Vector min(Vector v); Vector mul(int i); Vector div(int i); int dotProduct(Vector v); double length(); DoubleVector toDoubleVector(); Vector abs(); boolean isParallel(Vector to); Vector orthogonal(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); int getX(); int getY(); int get(Axis axis); static final Vector ZERO; final int x; final int y; }
@Test public void negate() { assertThat(new Vector(1, 2).negate(), is(new Vector(-1, -2))); }
Vector { public Vector max(Vector v) { return new Vector(Math.max(x, v.x), Math.max(y, v.y)); } Vector(int x, int y); Vector add(Vector v); Vector sub(Vector v); Vector negate(); Vector max(Vector v); Vector min(Vector v); Vector mul(int i); Vector div(int i); int dotProduct(Vector v); double length(); DoubleVector toDoubleVector(); Vector abs(); boolean isParallel(Vector to); Vector orthogonal(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); int getX(); int getY(); int get(Axis axis); static final Vector ZERO; final int x; final int y; }
@Test public void max() { assertThat(new Vector(1, 2).max(new Vector(2, 1)), is(new Vector(2, 2))); }
Vector { public Vector min(Vector v) { return new Vector(Math.min(x, v.x), Math.min(y, v.y)); } Vector(int x, int y); Vector add(Vector v); Vector sub(Vector v); Vector negate(); Vector max(Vector v); Vector min(Vector v); Vector mul(int i); Vector div(int i); int dotProduct(Vector v); double length(); DoubleVector toDoubleVector(); Vector abs(); boolean isParallel(Vector to); Vector orthogonal(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); int getX(); int getY(); int get(Axis axis); static final Vector ZERO; final int x; final int y; }
@Test public void min() { assertThat(new Vector(1, 2).min(new Vector(2, 1)), is(new Vector(1, 1))); }
Rectangles { public static int upperDistance(Rectangle inner, Rectangle outer) { assertOuterInner(outer, inner); return topLeft(inner).y - topLeft(outer).y; } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void upperDistance() { assertEquals(15, Rectangles.upperDistance(INNER, OUTER)); } @Test(expected = IllegalArgumentException.class) public void badUpperDistance() { Rectangles.upperDistance(OUTER, INNER); }
Rectangles { public static int lowerDistance(Rectangle inner, Rectangle outer) { assertOuterInner(outer, inner); return bottomLeft(outer).y - bottomLeft(inner).y; } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void lowerDistance() { assertEquals(145, Rectangles.lowerDistance(INNER, OUTER)); } @Test(expected = IllegalArgumentException.class) public void badLowerDistance() { Rectangles.lowerDistance(OUTER, INNER); }
Rectangles { public static int leftDistance(Rectangle inner, Rectangle outer) { assertOuterInner(outer, inner); return topLeft(inner).x - topLeft(outer).x; } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void leftDistance() { assertEquals(10, Rectangles.leftDistance(INNER, OUTER)); } @Test(expected = IllegalArgumentException.class) public void badLeftDistance() { Rectangles.leftDistance(OUTER, INNER); }
Rectangles { public static int rightDistance(Rectangle inner, Rectangle outer) { assertOuterInner(outer, inner); return topRight(outer).x - topRight(inner).x; } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void rightDistance() { assertEquals(60, Rectangles.rightDistance(INNER, OUTER)); } @Test(expected = IllegalArgumentException.class) public void badRightDistance() { Rectangles.rightDistance(OUTER, INNER); }
Rectangle { public Rectangle add(Vector v) { return new Rectangle(origin.add(v), dimension); } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void add() { assertEquals(new Rectangle(new Vector(1, 2), new Vector(2, 2)), new Rectangle(new Vector(0, 0), new Vector(2, 2)).add(new Vector(1, 2))); }
Rectangles { public static Rectangle extendUp(Rectangle r, int distance) { Vector change = new Vector(0, distance); return new Rectangle(r.origin.sub(change), r.dimension.add(change)); } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void extendUp() { assertEquals(new Rectangle(new Vector(10, 19), new Vector(30, 41)), Rectangles.extendUp(INNER, 1)); }
Rectangles { public static Rectangle extendDown(Rectangle r, int distance) { return r.changeDimension(r.dimension.add(new Vector(0, distance))); } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void extendDown() { assertEquals(new Rectangle(new Vector(10, 20), new Vector(30, 41)), Rectangles.extendDown(INNER, 1)); }
Rectangles { public static Rectangle extendLeft(Rectangle r, int distance) { Vector change = new Vector(distance, 0); return new Rectangle(r.origin.sub(change), r.dimension.add(change)); } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void extendLeft() { assertEquals(new Rectangle(new Vector(9, 20), new Vector(31, 40)), Rectangles.extendLeft(INNER, 1)); }
Rectangles { public static Rectangle extendRight(Rectangle r, int distance) { return r.changeDimension(r.dimension.add(new Vector(distance, 0))); } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void extendRight() { assertEquals(new Rectangle(new Vector(10, 20), new Vector(31, 40)), Rectangles.extendRight(INNER, 1)); }
Rectangles { public static Rectangle extendSides(int left, Rectangle r, int right) { return extendRight(extendLeft(r, left), right); } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void extendSides() { assertEquals(new Rectangle(new Vector(9, 20), new Vector(32, 40)), Rectangles.extendSides(1, INNER, 1)); }
Rectangles { public static Rectangle shrinkRight(Rectangle r, int distance) { if (r.dimension.x < distance) { throw new IllegalArgumentException("To small rectangle = " + r + ", distance = " + distance); } return r.changeDimension(r.dimension.sub(new Vector(distance, 0))); } private Rectangles(); static Rectangle zeroOrigin(Rectangle r); static int upperDistance(Rectangle inner, Rectangle outer); static int lowerDistance(Rectangle inner, Rectangle outer); static int leftDistance(Rectangle inner, Rectangle outer); static int rightDistance(Rectangle inner, Rectangle outer); static Rectangle extendUp(Rectangle r, int distance); static Rectangle extendDown(Rectangle r, int distance); static Rectangle extendLeft(Rectangle r, int distance); static Rectangle extendRight(Rectangle r, int distance); static Rectangle extendSides(int left, Rectangle r, int right); static Rectangle shrinkRight(Rectangle r, int distance); }
@Test public void shrinkRight() { assertEquals(new Rectangle(new Vector(10, 20), new Vector(29, 40)), Rectangles.shrinkRight(INNER, 1)); } @Test(expected = IllegalArgumentException.class) public void shrinkRightIncorrect() { Rectangles.shrinkRight(INNER, INNER.dimension.x + 1); }
DoubleRectangle { @Override public int hashCode() { return origin.hashCode() * 31 + dimension.hashCode(); } DoubleRectangle(double x, double y, double w, double h); DoubleRectangle(DoubleVector origin, DoubleVector dimension); static DoubleRectangle span(DoubleVector leftTop, DoubleVector rightBottom); DoubleVector getCenter(); double getLeft(); double getRight(); double getTop(); double getBottom(); double getWidth(); double getHeight(); Range<Double> xRange(); Range<Double> yRange(); boolean contains(DoubleVector v); DoubleRectangle union(DoubleRectangle rect); boolean intersects(DoubleRectangle rect); DoubleRectangle intersect(DoubleRectangle r); DoubleRectangle add(DoubleVector v); DoubleRectangle subtract(DoubleVector v); double distance(DoubleVector to); Iterable<DoubleSegment> getParts(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); final DoubleVector origin; final DoubleVector dimension; }
@Test public void hashCodeWorks() { assertEquals(new DoubleRectangle(DoubleVector.ZERO, DoubleVector.ZERO).hashCode(), new DoubleRectangle(DoubleVector.ZERO, DoubleVector.ZERO).hashCode()); }
Rectangle { public Rectangle sub(Vector v) { return new Rectangle(origin.sub(v), dimension); } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void sub() { assertEquals(new Rectangle(new Vector(0, 0), new Vector(2, 2)), new Rectangle(new Vector(1, 2), new Vector(2, 2)).sub(new Vector(1, 2))); }
Colors { public static Color forName(String colorName) { Color res = colorsList.get(colorName.toLowerCase()); if (res != null) { return res; } else { throw new IllegalArgumentException(); } } private Colors(); static boolean isColorName(String colorName); static Color forName(String colorName); static double generateHueColor(); static Color generateColor(double s, double v); static Color rgbFromHsv(double h, double s); static Color rgbFromHsv(double h, double s, double v); static double[] hsvFromRgb(Color color); static Color darker(Color c); static Color lighter(Color c); static Color darker(Color c, double factor); static Color lighter(Color c, double factor); static Color mimicTransparency(Color color, double alpha, Color background); static Color withOpacity(Color c, double opacity); static double contrast(Color color, Color other); static double luminance(Color color); static boolean solid(Color c); static Color[] distributeEvenly(int count, double saturation); static Persister<Color> colorPersister(final Color defaultValue); static final double DEFAULT_FACTOR; }
@Test(expected = IllegalArgumentException.class) public void unknownColor() { Colors.forName("unknown"); }
Color { public static Color parseHex(String hexColor) { if (!hexColor.startsWith("#")) { throw new IllegalArgumentException(); } hexColor = hexColor.substring(1); if (hexColor.length() != 6) { throw new IllegalArgumentException(); } Integer r = Integer.valueOf(hexColor.substring(0, 2), 16); Integer g = Integer.valueOf(hexColor.substring(2, 4), 16); Integer b = Integer.valueOf(hexColor.substring(4, 6), 16); return new Color(r, g, b); } Color(int r, int g, int b, int a); Color(int r, int g, int b); static Color parseColor(String text); static Color parseHex(String hexColor); int getRed(); int getGreen(); int getBlue(); int getAlpha(); Color changeAlpha(int newAlpha); @Override boolean equals(Object o); String toCssColor(); String toHexColor(); @Override int hashCode(); @Override String toString(); static final Color TRANSPARENT; static final Color WHITE; static final Color BLACK; static final Color LIGHT_GRAY; static final Color VERY_LIGHT_GRAY; static final Color GRAY; static final Color RED; static final Color LIGHT_GREEN; static final Color GREEN; static final Color DARK_GREEN; static final Color BLUE; static final Color DARK_BLUE; static final Color LIGHT_BLUE; static final Color YELLOW; static final Color LIGHT_YELLOW; static final Color VERY_LIGHT_YELLOW; static final Color MAGENTA; static final Color LIGHT_MAGENTA; static final Color DARK_MAGENTA; static final Color CYAN; static final Color LIGHT_CYAN; static final Color ORANGE; static final Color PINK; static final Color LIGHT_PINK; }
@Test public void parseHex() { assertEquals(Color.RED, Color.parseHex(Color.RED.toHexColor())); }
Color { public static Color parseColor(String text) { int firstParen = findNext(text, "(", 0); String prefix = text.substring(0, firstParen); int firstComma = findNext(text, ",", firstParen + 1); int secondComma = findNext(text, ",", firstComma + 1); int thirdComma = -1; if (prefix.equals(RGBA)) { thirdComma = findNext(text, ",", secondComma + 1); } else if (prefix.equals(COLOR)) { thirdComma = text.indexOf(",", secondComma + 1); } else if (!prefix.equals(RGB)) { throw new IllegalArgumentException(); } int lastParen = findNext(text, ")", thirdComma + 1); int red = Integer.parseInt(text.substring(firstParen + 1, firstComma).trim()); int green = Integer.parseInt(text.substring(firstComma + 1, secondComma).trim()); int blue; int alpha; if (thirdComma == -1) { blue = Integer.parseInt(text.substring(secondComma + 1, lastParen).trim()); alpha = 255; } else { blue = Integer.parseInt(text.substring(secondComma + 1, thirdComma).trim()); alpha = Integer.parseInt(text.substring(thirdComma + 1, lastParen).trim()); } return new Color(red, green, blue, alpha); } Color(int r, int g, int b, int a); Color(int r, int g, int b); static Color parseColor(String text); static Color parseHex(String hexColor); int getRed(); int getGreen(); int getBlue(); int getAlpha(); Color changeAlpha(int newAlpha); @Override boolean equals(Object o); String toCssColor(); String toHexColor(); @Override int hashCode(); @Override String toString(); static final Color TRANSPARENT; static final Color WHITE; static final Color BLACK; static final Color LIGHT_GRAY; static final Color VERY_LIGHT_GRAY; static final Color GRAY; static final Color RED; static final Color LIGHT_GREEN; static final Color GREEN; static final Color DARK_GREEN; static final Color BLUE; static final Color DARK_BLUE; static final Color LIGHT_BLUE; static final Color YELLOW; static final Color LIGHT_YELLOW; static final Color VERY_LIGHT_YELLOW; static final Color MAGENTA; static final Color LIGHT_MAGENTA; static final Color DARK_MAGENTA; static final Color CYAN; static final Color LIGHT_CYAN; static final Color ORANGE; static final Color PINK; static final Color LIGHT_PINK; }
@Test public void parseRgba() { assertEquals(Color.RED, Color.parseColor("rgba(255,0,0,255)")); } @Test public void parseRgb() { assertEquals(Color.RED, Color.parseColor("rgb(255,0,0)")); } @Test public void parseColor() { assertEquals(Color.BLUE, Color.parseColor("color(0,0,255,255)")); } @Test public void parseColorRgb() { assertEquals(Color.BLUE, Color.parseColor("color(0,0,255)")); } @Test public void parseRgbWithSpaces() { assertEquals(Color.RED, Color.parseColor("rgb(255, 0, 0)")); } @Test(expected = IllegalArgumentException.class) public void noLastNumber() { Color.parseColor("rgb(255, 0, )"); } @Test(expected = IllegalArgumentException.class) public void unknownPrefix() { Color.parseColor("rbg(255, 0, )"); }
Enums { public static <EnumT extends Enum<EnumT>> EnumT valueOf(Class<EnumT> cls, String name) { for (EnumT e : cls.getEnumConstants()) { if (Objects.equals(name, e.toString())) { return e; } } throw new IllegalArgumentException(name); } private Enums(); static EnumT valueOf(Class<EnumT> cls, String name); }
@Test public void enumParsing() { Assert.assertEquals(TestEnum.A, Enums.valueOf(TestEnum.class, "aaa")); } @Test(expected = IllegalArgumentException.class) public void illegalArgument() { Enums.valueOf(TestEnum.class, "A"); }
Rectangle { public boolean contains(Rectangle r) { return contains(r.origin) && contains(r.origin.add(r.dimension)); } Rectangle(Vector origin, Vector dimension); Rectangle(int x, int y, int width, int height); Rectangle add(Vector v); Rectangle sub(Vector v); boolean contains(Rectangle r); boolean contains(Vector v); Rectangle union(Rectangle rect); boolean intersects(Rectangle rect); Rectangle intersect(Rectangle r); boolean innerIntersects(Rectangle rect); Rectangle changeDimension(Vector dim); double distance(Vector to); Range<Integer> xRange(); Range<Integer> yRange(); @Override int hashCode(); @Override boolean equals(Object obj); DoubleRectangle toDoubleRectangle(); Vector center(); Segment[] getBoundSegments(); Vector[] getBoundPoints(); @Override String toString(); final Vector origin; final Vector dimension; }
@Test public void contains() { Rectangle rect = new Rectangle(new Vector(0, 0), new Vector(1, 2)); assertFalse(rect.contains(new Vector(-1, -1))); assertTrue(rect.contains(new Vector(1, 1))); }
Asyncs { public static <ValueT> Async<ValueT> constant(final ValueT val) { return new Async<ValueT>() { @Override public Registration onSuccess(Consumer<? super ValueT> successHandler) { successHandler.accept(val); return Registration.EMPTY; } @Override public Registration onResult(Consumer<? super ValueT> successHandler, Consumer<Throwable> failureHandler) { return onSuccess(successHandler); } @Override public Registration onFailure(Consumer<Throwable> failureHandler) { return Registration.EMPTY; } @Override public <ResultT> Async<ResultT> map(Function<? super ValueT, ? extends ResultT> success) { ResultT result; try { result = success.apply(val); } catch (Throwable t) { return Asyncs.failure(t); } return Asyncs.constant(result); } @Override public <ResultT> Async<ResultT> flatMap(Function<? super ValueT, Async<ResultT>> success) { Async<ResultT> result; try { result = success.apply(val); } catch (Throwable t) { return Asyncs.failure(t); } return result == null ? Asyncs.<ResultT>constant(null) : result; } }; } private Asyncs(); static boolean isFinished(Async<?> async); static Async<ValueT> constant(final ValueT val); static Async<ValueT> failure(final Throwable t); static Async<Void> toVoid(Async<ResultT> a); static Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second); static Async<Void> parallel(Async<?>... asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs, boolean alwaysSucceed); @GwtIncompatible static Async<Void> threadSafeParallel(Collection<? extends Async<?>> asyncs); @GwtIncompatible static Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs); static Async<List<ItemT>> composite(List<Async<ItemT>> asyncs); static void onAnyResult(Async<?> async, final Runnable r); static Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s); static Registration delegate(Async<? extends ValueT> from, final AsyncResolver<? super ValueT> to); static Async<Pair<FirstT, SecondT>> pair(Async<FirstT> first, Async<SecondT> second); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit); }
@Test public void constantAsync() { assertThat(Asyncs.constant(239), result(equalTo(239))); } @Test public void selectException() { Async<Integer> a = Asyncs.constant(1); assertThat( a.flatMap(new Function<Integer, Async<Object>>() { @Override public Async<Object> apply(Integer input) { throw new RuntimeException("test"); } }), failed()); } @Test public void selectReturnsNull() { Async<Integer> async = Asyncs.constant(1); assertThat( async.flatMap(new Function<Integer, Async<Object>>() { @Override public Async<Object> apply(Integer input) { return null; } }), result(nullValue())); }
Asyncs { public static <ValueT> Async<ValueT> failure(final Throwable t) { return new Async<ValueT>() { @Override public Registration onSuccess(Consumer<? super ValueT> successHandler) { return Registration.EMPTY; } @Override public Registration onResult(Consumer<? super ValueT> successHandler, Consumer<Throwable> failureHandler) { return onFailure(failureHandler); } @Override public Registration onFailure(Consumer<Throwable> failureHandler) { failureHandler.accept(t); return Registration.EMPTY; } @Override public <ResultT> Async<ResultT> map(Function<? super ValueT, ? extends ResultT> success) { return Asyncs.failure(t); } @Override public <ResultT> Async<ResultT> flatMap(Function<? super ValueT, Async<ResultT>> success) { return Asyncs.failure(t); } }; } private Asyncs(); static boolean isFinished(Async<?> async); static Async<ValueT> constant(final ValueT val); static Async<ValueT> failure(final Throwable t); static Async<Void> toVoid(Async<ResultT> a); static Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second); static Async<Void> parallel(Async<?>... asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs, boolean alwaysSucceed); @GwtIncompatible static Async<Void> threadSafeParallel(Collection<? extends Async<?>> asyncs); @GwtIncompatible static Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs); static Async<List<ItemT>> composite(List<Async<ItemT>> asyncs); static void onAnyResult(Async<?> async, final Runnable r); static Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s); static Registration delegate(Async<? extends ValueT> from, final AsyncResolver<? super ValueT> to); static Async<Pair<FirstT, SecondT>> pair(Async<FirstT> first, Async<SecondT> second); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit); }
@Test public void failureAsync() { assertThat(Asyncs.<Integer>failure(new Throwable()), failed()); }
Asyncs { static <SourceT, TargetT, AsyncResultT extends SourceT> Async<TargetT> map(Async<AsyncResultT> async, final Function<SourceT, ? extends TargetT> f, final ResolvableAsync<TargetT> resultAsync) { async.onResult(new Consumer<AsyncResultT>() { @Override public void accept(AsyncResultT item) { TargetT apply; try { apply = f.apply(item); } catch (Exception e) { resultAsync.failure(e); return; } resultAsync.success(apply); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { resultAsync.failure(throwable); } }); return resultAsync; } private Asyncs(); static boolean isFinished(Async<?> async); static Async<ValueT> constant(final ValueT val); static Async<ValueT> failure(final Throwable t); static Async<Void> toVoid(Async<ResultT> a); static Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second); static Async<Void> parallel(Async<?>... asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs, boolean alwaysSucceed); @GwtIncompatible static Async<Void> threadSafeParallel(Collection<? extends Async<?>> asyncs); @GwtIncompatible static Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs); static Async<List<ItemT>> composite(List<Async<ItemT>> asyncs); static void onAnyResult(Async<?> async, final Runnable r); static Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s); static Registration delegate(Async<? extends ValueT> from, final AsyncResolver<? super ValueT> to); static Async<Pair<FirstT, SecondT>> pair(Async<FirstT> first, Async<SecondT> second); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit); }
@Test public void map() { Async<Integer> c = Asyncs.constant(239); Async<Integer> mapped = c.map(new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input + 1; } }); assertThat(mapped, result(equalTo(240))); } @Test(expected = IllegalArgumentException.class) public void ignoreHandlerException() { SimpleAsync<Integer> async = new SimpleAsync<>(); Async<Integer> res = async.map(new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input + 1; } }); res.onSuccess(new Consumer<Integer>() { @Override public void accept(Integer item) { throw new IllegalArgumentException(); } }); res.onFailure(new Consumer<Throwable>() { @Override public void accept(Throwable item) { fail(); } }); async.success(1); }
Asyncs { static <SourceT, TargetT> Async<TargetT> select(Async<SourceT> async, final Function<? super SourceT, Async<TargetT>> f, final ResolvableAsync<TargetT> resultAsync) { async.onResult(new Consumer<SourceT>() { @Override public void accept(SourceT item) { Async<TargetT> async1; try { async1 = f.apply(item); } catch (Exception e) { resultAsync.failure(e); return; } if (async1 == null) { resultAsync.success(null); } else { delegate(async1, resultAsync); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { resultAsync.failure(throwable); } }); return resultAsync; } private Asyncs(); static boolean isFinished(Async<?> async); static Async<ValueT> constant(final ValueT val); static Async<ValueT> failure(final Throwable t); static Async<Void> toVoid(Async<ResultT> a); static Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second); static Async<Void> parallel(Async<?>... asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs); static Async<Void> parallel(Collection<? extends Async<?>> asyncs, boolean alwaysSucceed); @GwtIncompatible static Async<Void> threadSafeParallel(Collection<? extends Async<?>> asyncs); @GwtIncompatible static Async<List<ItemT>> parallelResult(Collection<Async<ItemT>> asyncs); static Async<List<ItemT>> composite(List<Async<ItemT>> asyncs); static void onAnyResult(Async<?> async, final Runnable r); static Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s); static Registration delegate(Async<? extends ValueT> from, final AsyncResolver<? super ValueT> to); static Async<Pair<FirstT, SecondT>> pair(Async<FirstT> first, Async<SecondT> second); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async); @GwtIncompatible("Uses threading primitives") static ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit); }
@Test public void select() { Async<Integer> c = Asyncs.constant(239); assertThat( c.flatMap(new Function<Integer, Async<Integer>>() { @Override public Async<Integer> apply(Integer input) { return Asyncs.constant(input + 1); } }), result(equalTo(240))); }