Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fixes #29

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion easy-random-core/src/main/java/org/jeasy/random/EasyRandom.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public EasyRandom(final EasyRandomParameters easyRandomParameters) {
);
exclusionPolicy = easyRandomParameters.getExclusionPolicy();
parameters = easyRandomParameters;
recordFactory = new RecordFactory();
recordFactory = new RecordFactory(this);
}

/**
Expand Down Expand Up @@ -246,4 +246,12 @@ private Collection<RandomizerRegistry> loadRegistries() {
ServiceLoader.load(RandomizerRegistry.class).forEach(registries::add);
return registries;
}

public RandomizerProvider getRandomizerProvider() {
return randomizerProvider;
}

public ObjectFactory getObjectFactory() {
return objectFactory;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ private Class<?> getParametrizedType(Field field, Class<?> fieldTargetType) {
}
}
if (actualTypeArgument == null) {
return field.getClass();
return field.getType();
}
Class<?> aClass;
String typeName = null;
Expand Down
58 changes: 33 additions & 25 deletions easy-random-core/src/main/java/org/jeasy/random/RecordFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@
*/
package org.jeasy.random;

import static org.jeasy.random.util.ReflectionUtils.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.RecordComponent;
import java.lang.reflect.Type;
import org.jeasy.random.api.RandomizerContext;

/**
Expand All @@ -39,22 +37,36 @@
*/
public class RecordFactory extends ObjenesisObjectFactory {

private EasyRandom easyRandom;
private final EasyRandom easyRandom;
private final RecordFieldPopulator recordFieldPopulator;

public RecordFactory(EasyRandom easyRandom) {
this.easyRandom = easyRandom;
recordFieldPopulator =
new RecordFieldPopulator(
easyRandom,
easyRandom.getRandomizerProvider(),
new ArrayPopulator(easyRandom),
new CollectionPopulator(easyRandom),
new MapPopulator(easyRandom, easyRandom.getObjectFactory()),
new OptionalPopulator(easyRandom)
);
}

@Override
public <T> T createInstance(Class<T> type, RandomizerContext context) {
if (easyRandom == null) {
easyRandom = new EasyRandom(context.getParameters());
}

return createRandomRecord(type, (RandomizationContext) context);
}

private <T> boolean isRecord(final Class<T> type) {
return type.isRecord();
}

private <T> T createRandomRecord(Class<T> recordType, RandomizationContext context) {
// generate random values for record components
Field[] fields = recordType.getDeclaredFields();
RecordComponent[] recordComponents = recordType.getRecordComponents();
Object[] randomValues = new Object[recordComponents.length];

if (context.hasExceededRandomizationDepth()) {
for (int i = 0; i < recordComponents.length; i++) {
Class<?> type = recordComponents[i].getType();
Expand All @@ -64,25 +76,21 @@ private <T> T createRandomRecord(Class<T> recordType, RandomizationContext conte
for (int i = 0; i < recordComponents.length; i++) {
context.pushStackItem(new RandomizationContextStackItem(recordType, null));
Class<?> type = recordComponents[i].getType();
Type genericType = recordComponents[i].getGenericType();
if (isArrayType(type)) {
randomValues[i] = new ArrayPopulator(easyRandom).getRandomArray(type, context);
} else if (isMapType(type)) {
randomValues[i] =
new MapPopulator(easyRandom, context.getParameters().getObjectFactory())
.getRandomMap(genericType, type, context);
} else if (isOptionalType(type)) {
randomValues[i] = new OptionalPopulator(easyRandom).getRandomOptional(genericType, context);
} else if (isCollectionType(type)) {
randomValues[i] =
new CollectionPopulator(easyRandom).getRandomCollection(genericType, type, context);
} else {
randomValues[i] = easyRandom.doPopulateBean(type, context);
try {
if (isRecord(type)) {
randomValues[i] = easyRandom.doPopulateBean(type, context);
} else {
randomValues[i] = this.recordFieldPopulator.populateField(fields[i], recordType, context);
}
} catch (IllegalAccessException e) {
throw new ObjectCreationException(
"Unable to create a random instance of recordType " + recordType,
e
);
}
context.popStackItem();
}
}

// create a random instance with random values
try {
Constructor<T> canonicalConstructor = getCanonicalConstructor(recordType);
Expand All @@ -107,7 +115,7 @@ private <T> Constructor<T> getCanonicalConstructor(Class<T> recordType) {
// should not happen, from Record javadoc:
// "A record class has the following mandated members: a public canonical constructor ,
// whose descriptor is the same as the record descriptor;"
throw new RuntimeException("Invalid record definition", e);
throw new ObjectCreationException("Invalid record definition", e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
/*
* The MIT License
*
* Copyright (c) 2020, Mahmoud Ben Hassine ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jeasy.random;

import static org.jeasy.random.util.ReflectionUtils.*;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import org.jeasy.random.api.ContextAwareRandomizer;
import org.jeasy.random.api.Randomizer;
import org.jeasy.random.api.RandomizerProvider;
import org.jeasy.random.randomizers.misc.SkipRandomizer;

/**
* Component that encapsulates the logic of generating a random value for a given field.
* It collaborates with a:
* <ul>
* <li>{@link EasyRandom} whenever the field is a user defined type.</li>
* <li>{@link ArrayPopulator} whenever the field is an array type.</li>
* <li>{@link CollectionPopulator} whenever the field is a collection type.</li>
* <li>{@link CollectionPopulator}whenever the field is a map type.</li>
* </ul>
*
* @author Mahmoud Ben Hassine ([email protected])
*/
class RecordFieldPopulator {

private final EasyRandom easyRandom;

private final ArrayPopulator arrayPopulator;

private final CollectionPopulator collectionPopulator;

private final MapPopulator mapPopulator;

private final OptionalPopulator optionalPopulator;

private final RandomizerProvider randomizerProvider;

RecordFieldPopulator(
final EasyRandom easyRandom,
final RandomizerProvider randomizerProvider,
final ArrayPopulator arrayPopulator,
final CollectionPopulator collectionPopulator,
final MapPopulator mapPopulator,
OptionalPopulator optionalPopulator
) {
this.easyRandom = easyRandom;
this.randomizerProvider = randomizerProvider;
this.arrayPopulator = arrayPopulator;
this.collectionPopulator = collectionPopulator;
this.mapPopulator = mapPopulator;
this.optionalPopulator = optionalPopulator;
}

Object populateField(final Field field, Class<?> enclosingType, final RandomizationContext context)
throws IllegalAccessException {
Randomizer<?> randomizer = getRandomizer(field, context, enclosingType);
if (randomizer instanceof SkipRandomizer) {
return null;
}
//context.pushStackItem(new RandomizationContextStackItem(null, field));
if (randomizer instanceof ContextAwareRandomizer) {
((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context);
}
if (!context.hasExceededRandomizationDepth()) {
Object value;
if (randomizer != null) {
value = randomizer.getRandomValue();
} else {
try {
value = generateRandomValue(field, context);
} catch (ObjectCreationException e) {
String exceptionMessage = String.format(
"Unable to create type: %s for field: %s of class: %s",
field.getType().getName(),
field.getName(),
enclosingType.getName()
);
// FIXME catch ObjectCreationException and throw ObjectCreationException ?
throw new ObjectCreationException(exceptionMessage, e);
}
}
return value;
}
//context.popStackItem();
return null;
}

private Randomizer<?> getRandomizer(Field field, RandomizationContext context, Class<?> fieldTargetType) {
// issue 241: if there is no custom randomizer by field, then check by type
Randomizer<?> randomizer = randomizerProvider.getRandomizerByField(field, context);
if (randomizer == null) {
Type genericType = field.getGenericType();
if (isTypeVariable(genericType)) {
// if generic type, retrieve actual type from declaring class
Class<?> type = getParametrizedType(field, fieldTargetType);
randomizer = randomizerProvider.getRandomizerByType(type, context);
} else {
randomizer = randomizerProvider.getRandomizerByType(field.getType(), context);
}
}
return randomizer;
}

private Object generateRandomValue(final Field field, final RandomizationContext context) {
Class<?> fieldType = field.getType();
Type fieldGenericType = field.getGenericType();

if (isArrayType(fieldType)) {
return arrayPopulator.getRandomArray(fieldType, context);
} else if (isCollectionType(fieldType)) {
return collectionPopulator.getRandomCollection(field, context);
} else if (isMapType(fieldType)) {
return mapPopulator.getRandomMap(field, context);
} else if (isOptionalType(fieldType)) {
return optionalPopulator.getRandomOptional(field, context);
} else {
if (
context.getParameters().isScanClasspathForConcreteTypes() &&
isAbstract(fieldType) &&
!isEnumType(fieldType)
/*enums can be abstract, but cannot inherit*/
) {
List<Class<?>> parameterizedTypes = filterSameParameterizedTypes(
getPublicConcreteSubTypesOf(fieldType),
fieldGenericType
);
if (parameterizedTypes.isEmpty()) {
throw new ObjectCreationException(
"Unable to find a matching concrete subtype of type: " + fieldType
);
} else {
Class<?> randomConcreteSubType = parameterizedTypes.get(
easyRandom.nextInt(parameterizedTypes.size())
);
return easyRandom.doPopulateBean(randomConcreteSubType, context);
}
} else {
Type genericType = field.getGenericType();
if (isTypeVariable(genericType)) {
// if generic type, try to retrieve actual type from hierarchy
Class<?> type = getParametrizedType(field, context.getTargetType());
return easyRandom.doPopulateBean(type, context);
}
return easyRandom.doPopulateBean(fieldType, context);
}
}
}

private Class<?> getParametrizedType(Field field, Class<?> fieldTargetType) {
Class<?> declaringClass = field.getDeclaringClass();
TypeVariable<? extends Class<?>>[] typeParameters = declaringClass.getTypeParameters();
Type genericSuperclass = getGenericSuperClass(fieldTargetType);
ParameterizedType parameterizedGenericSuperType = (ParameterizedType) genericSuperclass;
Type[] actualTypeArguments = parameterizedGenericSuperType.getActualTypeArguments();
Type actualTypeArgument = null;
for (int i = 0; i < typeParameters.length; i++) {
if (field.getGenericType().equals(typeParameters[i])) {
actualTypeArgument = actualTypeArguments[i];
}
}
if (actualTypeArgument == null) {
return field.getType();
}
Class<?> aClass;
String typeName = null;
try {
typeName = actualTypeArgument.getTypeName();
aClass = Class.forName(typeName);
} catch (ClassNotFoundException e) {
String message = String.format(
"Unable to load class %s of generic field %s in class %s. " +
"Please refer to the documentation as this generic type may not be supported for randomization.",
typeName,
field.getName(),
field.getDeclaringClass().getName()
);
throw new ObjectCreationException(message, e);
}
return aClass;
}

// find the generic base class in the hierarchy (which might not be the first super type)
private Type getGenericSuperClass(Class<?> targetType) {
Type genericSuperclass = targetType.getGenericSuperclass();
while (targetType != null && !(genericSuperclass instanceof ParameterizedType)) {
targetType = targetType.getSuperclass();
if (targetType != null) {
genericSuperclass = targetType.getGenericSuperclass();
}
}
return genericSuperclass;
}
}
Loading