Java源码示例:com.openpojo.validation.affirm.Affirm
示例1
public void evaluate(final PojoClass pojoClass) {
final List<PojoField> parentPojoFields = new LinkedList<PojoField>();
PojoClass parentPojoClass = pojoClass.getSuperClass();
while (parentPojoClass != null) {
parentPojoFields.addAll(parentPojoClass.getPojoFields());
parentPojoClass = parentPojoClass.getSuperClass();
}
final List<PojoField> childPojoFields = pojoClass.getPojoFields();
for (final PojoField childPojoField : childPojoFields) {
if (!childPojoField.isSynthetic() && !isSerializable(childPojoField, pojoClass) && !inSkipList(childPojoField))
if (contains(childPojoField.getName(), parentPojoFields))
Affirm.fail(MessageFormatter.format("Field=[{0}] shadows field with the same name in parent class=[{1}]",
childPojoField, parentPojoFields));
}
}
示例2
public void run(PojoClass pojoClass) {
final Class<?> clazz = pojoClass.getClazz();
if (Serializable.class.isAssignableFrom(clazz)) {
Object instance = RandomFactory.getRandomValue(clazz);
ensureNoFieldsAreNull(pojoClass, instance);
try {
byte[] serializedObject = serialize(pojoClass, instance);
Object instance2 = deSerialize(serializedObject, instance.getClass());
Affirm.affirmNotNull("Failed to load serialized object [" + instance + "]", instance2);
} catch (Exception e) {
Affirm.fail("Failed to run " + this.getClass().getName() + " - Got exception [" + e + "] on PojoClass " + pojoClass);
}
} else {
logger.warn("Class [" + clazz + "] is not serializable, skipping validation");
}
}
示例3
@Test
@SuppressWarnings("ConstantConditions")
public void shouldGenerateRandomEnum() {
RandomGenerator randomGenerator = EnumRandomGenerator.getInstance();
Enum someEnum = (Enum) randomGenerator.doGenerate(Enum.class);
Affirm.affirmTrue("should never generate null", someEnum != null);
Enum anotherEnum = (Enum) randomGenerator.doGenerate(Enum.class);
try {
Affirm.affirmFalse("Enum's should be different", someEnum.equals(anotherEnum));
} catch (AssertionError error) {
// on occasion they may be the same - 1% chance, try one more time.
anotherEnum = (Enum) randomGenerator.doGenerate(Enum.class);
Affirm.affirmFalse("Enum's should be different", someEnum.equals(anotherEnum));
}
}
示例4
@Test
public void shouldGenerateAppropriateLinkErrorForInvalidASMGeneratedClasses() throws Exception {
final SimpleClassLoader simpleClassLoader = new SimpleClassLoader();
final String className = this.getClass().getPackage().getName() + ".AClassWithBadMethod" + GENERATED_CLASS_POSTFIX;
final String classNameAsPath = className.replace(Java.PACKAGE_DELIMITER, Java.PATH_DELIMITER);
final Class<?> clazz = simpleClassLoader.loadThisClass(AClassWithBadMethodDump.dump(classNameAsPath), className);
Affirm.affirmNotNull("Failed to generate class!", clazz);
try {
PojoClassFactory.getPojoClass(clazz);
Affirm.fail("Should have thrown RuntimeException");
} catch (VerifyError expected) {
expected.printStackTrace();
Affirm.affirmEquals("Invalid Message in exception",
"(class: " + classNameAsPath + ", " +
"method: badMethod signature: ()V) Wrong return type in function",
expected.getMessage());
}
}
示例5
@Test
public final void shouldGetJarSubClasses() {
JARPackageLoader jarPackage = getJarPackageLoader(packageName);
Set<String> classesNames = new LinkedHashSet<String>();
for (Type type : jarPackage.getTypes()) {
classesNames.add(((Class<?>) type).getName());
}
Affirm.affirmEquals(MessageFormatter.format("Classes added/removed to {0} found[{1}]?!", packageName, classesNames),
expectedClassesNames.length, classesNames.size());
for (String expectedClassName : classesNames) {
Affirm.affirmTrue(MessageFormatter.format("Expected class[{0}] not found", expectedClassName),
classesNames.contains(expectedClassName));
}
}
示例6
@Test
public void shouldGetMethodWithGenericParameter() {
PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithGenericParameterMethod.class);
List<PojoMethod> allMethodsAndConstructors = pojoClass.getPojoMethods();
List<PojoMethod> methods = new LinkedList<PojoMethod>();
for (PojoMethod method : allMethodsAndConstructors) {
if (method.isConstructor())
continue;
methods.add(method);
}
Affirm.affirmEquals(pojoClass.getName() + " should have only one generic parameterized method", 1, methods.size());
shouldHaveOneParameterizedParameter(methods, Integer.class);
}
示例7
@Test
public void testIsInterfaceIsAbstractIsConcrete() {
final String message = "Class type check failed on [%s], actual class returned [%s], PojoClass returned [%s]!!";
for (final PojoClass pojoClass : PojoClassFactory.getPojoClassesRecursively(SAMPLE_CLASSES_PKG, null)) {
final Class<?> actualClass = pojoClass.getClazz();
Affirm.affirmTrue(String.format(message, actualClass.getName() + ".isInterface()", actualClass.isInterface(),
pojoClass.isInterface()), pojoClass.isInterface() == actualClass.isInterface());
Affirm.affirmTrue(String.format(message, actualClass.getName() + ".isAbstract()",
Modifier.isAbstract(actualClass.getModifiers())
&& !Modifier.isInterface(actualClass.getModifiers()), pojoClass.isAbstract()),
pojoClass.isAbstract() == (Modifier.isAbstract(actualClass.getModifiers())
&& !Modifier.isInterface(actualClass.getModifiers())));
final boolean expectedValue = !(Modifier.isAbstract(actualClass.getModifiers())
|| actualClass.isInterface()
|| actualClass.isEnum());
final boolean actualValue = pojoClass.isConcrete();
Affirm.affirmTrue(String.format(message, actualClass.getName() + ".isConcrete()", expectedValue, actualValue),
actualValue == expectedValue);
}
}
示例8
@Test
public void multipleAnnotationsShouldBeReturned() {
for (PojoMethod pojoMethod : pojoMethods) {
if (pojoMethod.getName().equals("methodWithMultipleAnnotations")) {
Affirm.affirmEquals(String.format("Annotations added/removed from method=[%s]", pojoMethod),
2,
pojoMethod.getAnnotations().size());
List<Class<?>> expectedAnnotations = new LinkedList<Class<?>>();
expectedAnnotations.add(SomeAnnotation.class);
expectedAnnotations.add(AnotherAnnotation.class);
for (Annotation annotation : pojoMethod.getAnnotations()) {
Affirm.affirmTrue(String.format("Expected annotations [%s] not found, instead found [%s]",
expectedAnnotations, annotation.annotationType()), expectedAnnotations.contains(annotation.annotationType()));
}
return;
}
}
Affirm.fail(String.format("methodWithMultipleAnnotations renamed? expected in [%s]", pojoClass));
}
示例9
@Test
public void testIsSyntheticOnSyntheticClass() {
PojoClass syntheticPojoClass = getPojoClassImplForClass(AClassWithSythetics.class);
Affirm.affirmEquals("Expected 2 constructors", 2, syntheticPojoClass.getPojoConstructors().size());
PojoMethod constructor = null;
for (PojoMethod constructorEntry : syntheticPojoClass.getPojoConstructors()) {
if (constructorEntry.getParameterTypes().length > 0)
constructor = constructorEntry;
}
Assert.assertNotNull(constructor);
Affirm.affirmTrue("Failed to find synthetic constructor", constructor.isSynthetic());
Affirm.affirmEquals("Synthetic Constructor should have just one parameter", 1, constructor.getParameterTypes().length);
PojoClass aSyntheticClass = getPojoClassImplForClass(constructor.getParameterTypes()[0]);
Affirm.affirmTrue("Parameter to synthetic constructor should be synthetic class", aSyntheticClass.isSynthetic());
}
示例10
@Test
public void multipleAnnotationsShouldBeReturned() {
final Class<?> aClassWithAnnotations = AClassWithAnnotations.class;
final PojoClass pojoClass = getPojoClassImplForClass(aClassWithAnnotations);
Affirm.affirmEquals(String.format("Annotations added/removed from Class=[%s]", aClassWithAnnotations), 2, pojoClass
.getAnnotations().size());
final List<Class<?>> expectedAnnotations = new LinkedList<Class<?>>();
expectedAnnotations.add(SomeAnnotation.class);
expectedAnnotations.add(AnotherAnnotation.class);
for (final Annotation annotation : pojoClass.getAnnotations()) {
Affirm.affirmTrue(String.format("Expected annotations [%s] not found, instead found [%s]", expectedAnnotations,
annotation.annotationType()), expectedAnnotations.contains(annotation.annotationType()));
}
}
示例11
@Test
public void testCopy() {
final AClassWithEquality first = new AClassWithEquality(RandomFactory.getRandomValue(String.class), RandomFactory
.getRandomValue(Integer.class));
final AClassWithEquality second = new AClassWithEquality();
Affirm.affirmFalse(String.format("Class with data=[%s], evaluated equals to one without=[%s]!!", BusinessIdentity.toString
(first), BusinessIdentity.toString(second)), first.equals(second));
final PojoClass pojoClass = getPojoClassImplForClass(first.getClass());
pojoClass.copy(first, second);
Affirm.affirmTrue(String.format("Class=[%s] copied to=[%s] and still equals returned false using PojoClass" + " " +
"implementation=[%s]!!", BusinessIdentity.toString(first), BusinessIdentity.toString(second), pojoClass), first.equals
(second));
}
示例12
@Test
public void ensureEnumStaysIntact() {
PojoClass pojoClass = PojoClassFactory.getPojoClass(SomeEnumWithValuesMethod.class);
boolean valuesMethodExists = false;
for (PojoMethod pojoMethod : pojoClass.getPojoMethods()) {
if (pojoMethod.getName().equals("values") && pojoMethod.getPojoParameters().size() > 0 && pojoMethod.isStatic())
valuesMethodExists = true;
}
Affirm.affirmTrue("values method must exist, Enum Class Changed?!", valuesMethodExists);
}
示例13
@Test
public void shouldGetRandomGeneratorBasedOnAssignability() {
final Class<?> type = LinkedList.class;
final DummyRandomGenerator dummyRandomGenerator = new DummyRandomGenerator();
dummyRandomGenerator.setTypes(new Class<?>[] { type });
defaultRandomGeneratorService.registerRandomGenerator(dummyRandomGenerator);
defaultRandomGeneratorService.getRandomGeneratorByType(List.class).doGenerate(List.class);
Affirm.affirmEquals("Incorrect random generator returned (doGenerate should've incremented call count)", 1,
dummyRandomGenerator.getCounter());
}
示例14
@Test
public void canAccessSetter() {
boolean found = false;
for (PojoField pojoField : pojoClass.getPojoFields()) {
if (pojoField.hasSetter()) {
PojoMethod setter = pojoField.getSetter();
Affirm.affirmNotNull("Setter can't be retrieved", setter);
Object randomInstance = RandomFactory.getRandomValue(pojoField.getType());
setter.invoke(pojoClassInstance, randomInstance);
Affirm.affirmSame("Expected same object in and out", randomInstance, pojoField.get(pojoClassInstance));
found = true;
}
}
Affirm.affirmTrue("No Setters were found!", found);
}
示例15
@Test
public void shouldEnusreNoPackageInfoExists() {
final String packageName = this.getClass().getPackage().getName() + ".packagenopackageinfo";
final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(packageName);
Affirm.affirmTrue("No classes in package?", pojoClasses.size() > 0);
for (final PojoClass pojoClass : pojoClasses) {
Affirm.affirmTrue(String.format("package-info added to package [%s]?", packageName),
!pojoClass.getName().endsWith("package-info"));
}
}
示例16
@Test
public void testIsVolatile() {
for (PojoField pojoField : pojoClass.getPojoFields()) {
if (pojoField.getName().equals("volatileString")) {
Affirm.affirmTrue(String.format("isVolatile() check on field=[%s] returned false!!", pojoField), pojoField.isVolatile());
}
}
}
示例17
/**
* Test that the factory gets classes from a package correctly.
*/
@Test
public void testGetPojoClasses() {
List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(DUMMY_PACKAGE, null);
Affirm.affirmNotNull(String.format("PojoClassFactory returned null list while getting list for package=[%s]",
DUMMY_PACKAGE), pojoClasses);
Affirm.affirmEquals(String.format("Classes added/removed from [%s]?", DUMMY_PACKAGE), 2, pojoClasses.size());
for (Class<?> clazz : DUMMY_PACKAGE_CLASSES) {
Affirm.affirmTrue(String.format("Unexpected class=[%s] retrieved from package=[%s], ", clazz, DUMMY_PACKAGE),
pojoClasses.contains(PojoClassFactory.getPojoClass(clazz)));
}
}
示例18
@Test
@SuppressWarnings("ConstantConditions")
public void endToEndTest() {
Enum someEnum = RandomFactory.getRandomValue(Enum.class);
Affirm.affirmNotNull("Should generate Enum", someEnum);
Affirm.affirmTrue("Should use SomeEnum when generating", someEnum.getClass() == SomeEnum.class);
}
示例19
@Test
@SuppressWarnings("unchecked")
public final void shouldReturnSetLogger() throws ClassNotFoundException {
for (String logger : supportedLoggers) {
Class<Logger> loggerClass = (Class<Logger>) Class.forName(logger);
LoggerFactory.setActiveLogger(loggerClass);
Affirm.affirmTrue(String.format("Expected LoggerFactory to be set to [%s] but was [%s]", loggerClass,
LoggerFactory.getLogger((String) null)), LoggerFactory.getLogger((String) null).getClass().equals(loggerClass));
}
}
示例20
public void evaluate(PojoClass pojoClass) {
boolean hasEquals = hasEquals(pojoClass);
boolean hasHashCode = hasHashCode(pojoClass);
if (hasEquals && !hasHashCode)
Affirm.fail("equals implemented but hashcode isn't in Pojo [" + pojoClass + "]");
if (!hasEquals && hasHashCode)
Affirm.fail("hashCode implemented but equals isn't in Pojo [" + pojoClass + "]");
}
示例21
public void evaluate(final PojoClass pojoClass) {
for (PojoField fieldEntry : pojoClass.getPojoFields()) {
if (fieldEntry.isPrimitive() && !ValidationHelper.isStaticFinal(fieldEntry)) {
Affirm.fail(String.format(
"Primitive fields (byte, short, int, long, float, double, boolean, char) not allowed [%s]", fieldEntry));
}
}
}
示例22
public void evaluate(final PojoClass pojoClass) {
for (PojoField fieldEntry : pojoClass.getPojoFields()) {
if (fieldEntry.isStatic() && !fieldEntry.isFinal()) {
Affirm.fail(String.format("Static fields=[%s] not marked final are not allowed", fieldEntry));
}
}
}
示例23
@Test
public void ensureExpectedPojoCount() {
if (this.withExpectedCount) {
final List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(this.pojoPackage,
new FilterPackageInfo());
Affirm.affirmEquals("Classes added / removed?", this.expectedClassCount, pojoClasses.size());
} else {
log.debug("WithExpectedCount is disbabled");
}
}
示例24
@Test
public void shouldNotHaveGettersAndSetters() {
PojoClass pojoClass = PojoClassFactory.getPojoClass(AClassWithFieldsPrefixed.class);
for (PojoField pojoField : pojoClass.getPojoFields()) {
Affirm.affirmFalse(String.format("Getters / Setters not found on field =[%s]", pojoField), pojoField.hasGetter() ||
pojoField.hasSetter());
}
}
示例25
public void run(final PojoClass pojoClass) {
final Object classInstance = ValidationHelper.getBasicInstance(pojoClass);
for (final PojoField fieldEntry : pojoClass.getPojoFields()) {
if (!fieldEntry.isPrimitive() && !fieldEntry.isFinal() && fieldEntry.getAnnotation(BusinessKey.class) == null) {
Affirm.affirmNull(String.format("Expected null value for for field=[%s]", fieldEntry), fieldEntry.get(classInstance));
}
}
}
示例26
/**
* Test method for {@link com.openpojo.reflection.impl.PojoFieldImpl#isStatic()}.
*/
@Test
public void testIsStatic() {
for (PojoField pojoField : pojoClass.getPojoFields()) {
if (pojoField.getName().startsWith("static")) {
Affirm.affirmTrue(String.format("isStatic() check on field=[%s] returned false!!", pojoField), pojoField.isStatic());
}
}
}
示例27
@Test
public void testIsPublic() {
String prefix = "public";
PojoField pojoField = getFieldStartingWith(prefix);
Affirm.affirmNotNull("Field not found [" + prefix + "]", pojoField);
Affirm.affirmTrue("isPublic() check on field=[" + pojoField + "] returned false!!", pojoField.isPublic());
Affirm.affirmFalse("isPrivate() check on field=[" + pojoField + "] returned true!!", pojoField.isPrivate());
Affirm.affirmFalse("isPackagePrivate() check on field=[" + pojoField + "] returned true!!", pojoField.isPackagePrivate());
Affirm.affirmFalse("isProtected() check on field=[" + pojoField + "] returned true!!", pojoField.isProtected());
}
示例28
public static void shouldFailTesterValidation(final Tester tester, final Class<?>... failClasses) {
for (Class<?> clazz : failClasses) {
try {
tester.run(PojoClassFactory.getPojoClass(clazz));
Affirm.fail(String.format("Tester = [%s] failed to detect error while evaluating class= [%s]", tester, clazz));
} catch (AssertionError ae) {
if (ae.getMessage().contains("Tester = [")) {
throw ae;
}
}
}
}
示例29
@Test
public void testToString() {
Logger log = LoggerFactory.getLogger(getCategory());
Affirm.affirmTrue(String.format("toString() failed on [%s]!", SLF4JLogger.class.getName()),
log.toString().startsWith("com.openpojo.log.impl.SLF4JLogger [@")
&& log.toString().endsWith(": logger=org.slf4j.impl.Log4jLoggerAdapter(com.openpojo.log.SL4JLoggerTest)]"));
}
示例30
@Test
public final void shouldGetJarSubPackages() {
JARPackageLoader jarPackage = getJarPackageLoader(packageName);
Set<String> subPackagesNames = jarPackage.getSubPackages();
Affirm.affirmEquals(MessageFormatter.format("SubPackages added/removed to {0} found[{1}]?!", packageName, subPackagesNames)
, expectedSubPackagesNames.length, subPackagesNames.size());
for (String expectedPackageName : expectedSubPackagesNames) {
Affirm.affirmTrue(MessageFormatter.format("Expected package[{0}] not found", expectedPackageName),
subPackagesNames.contains(expectedPackageName));
}
}