use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.
the class ContractViolation method minimizeTest.
/**
* Remove all statements that do not contribute to the contract violation
*/
public void minimizeTest() {
if (isMinimized)
return;
/**
* Factory method that handles statement deletion
*/
TestFactory testFactory = TestFactory.getInstance();
if (Properties.INLINE) {
ConstantInliner inliner = new ConstantInliner();
inliner.inline(test);
}
TestCase origTest = test.clone();
List<Integer> positions = new ArrayList<Integer>();
for (VariableReference var : variables) positions.add(var.getStPosition());
int oldLength = test.size();
boolean changed = true;
while (changed) {
changed = false;
for (int i = test.size() - 1; i >= 0; i--) {
// TODO - why??
if (i >= test.size())
continue;
if (positions.contains(i))
continue;
try {
boolean deleted = testFactory.deleteStatement(test, i);
if (!deleted) {
continue;
}
if (!contract.fails(test)) {
test = origTest.clone();
} else {
changed = true;
for (int j = 0; j < positions.size(); j++) {
if (positions.get(j) > i) {
positions.set(j, positions.get(j) - (oldLength - test.size()));
}
}
origTest = test.clone();
oldLength = test.size();
}
} catch (ConstructionFailedException e) {
test = origTest.clone();
}
}
}
statement = test.getStatement(test.size() - 1);
for (int i = 0; i < variables.size(); i++) {
variables.set(i, test.getStatement(positions.get(i)).getReturnValue());
}
contract.addAssertionAndComments(statement, variables, exception);
isMinimized = true;
}
use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.
the class GenericClass method getGenericParameterizedTypeInstantiation.
/**
* Instantiate all type parameters of a parameterized type
*
* @param typeMap
* @param recursionLevel
* @return
* @throws ConstructionFailedException
*/
private GenericClass getGenericParameterizedTypeInstantiation(Map<TypeVariable<?>, Type> typeMap, int recursionLevel) throws ConstructionFailedException {
// FIXME: This negatively affects coverage. Why was it added?
//
// if(isClass() && !hasTypeVariables()) {
// return this;
// }
List<TypeVariable<?>> typeParameters = getTypeVariables();
Type[] parameterTypes = new Type[typeParameters.size()];
Type ownerType = null;
int numParam = 0;
for (GenericClass parameterClass : getParameterClasses()) {
logger.debug("Current parameter to instantiate", parameterClass);
/*
* If the parameter is a parameterized type variable such as T extends Map<String, K extends Number>
* then the boundaries of the parameters of the type variable need to be respected
*/
if (!parameterClass.hasWildcardOrTypeVariables()) {
logger.debug("Parameter has no wildcard or type variable");
parameterTypes[numParam++] = parameterClass.getType();
} else {
logger.debug("Current parameter has type variables: " + parameterClass);
Map<TypeVariable<?>, Type> extendedMap = new HashMap<TypeVariable<?>, Type>(typeMap);
extendedMap.putAll(parameterClass.getTypeVariableMap());
if (!extendedMap.containsKey(typeParameters.get(numParam)) && !parameterClass.isTypeVariable())
extendedMap.put(typeParameters.get(numParam), parameterClass.getType());
logger.debug("New type map: " + extendedMap);
if (parameterClass.isWildcardType()) {
logger.debug("Is wildcard type, here we should value the wildcard boundaries");
logger.debug("Wildcard boundaries: " + parameterClass.getGenericBounds());
logger.debug("Boundaries of underlying var: " + Arrays.asList(typeParameters.get(numParam).getBounds()));
GenericClass parameterInstance = parameterClass.getGenericWildcardInstantiation(extendedMap, recursionLevel + 1);
// if(!parameterTypeClass.isAssignableFrom(parameterInstance)) {
if (!parameterInstance.satisfiesBoundaries(typeParameters.get(numParam))) {
throw new ConstructionFailedException("Invalid generic instance");
}
// GenericClass parameterInstance = new GenericClass(
// typeParameters.get(numParam)).getGenericInstantiation(extendedMap,
// recursionLevel + 1);
parameterTypes[numParam++] = parameterInstance.getType();
} else {
logger.debug("Is not wildcard but type variable? " + parameterClass.isTypeVariable());
GenericClass parameterInstance = parameterClass.getGenericInstantiation(extendedMap, recursionLevel + 1);
parameterTypes[numParam++] = parameterInstance.getType();
}
}
}
if (hasOwnerType()) {
GenericClass ownerClass = getOwnerType().getGenericInstantiation(typeMap, recursionLevel);
ownerType = ownerClass.getType();
}
return new GenericClass(new ParameterizedTypeImpl(rawClass, parameterTypes, ownerType));
}
use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.
the class TestFactory method satisfyParameters.
/**
* Satisfy a list of parameters by reusing or creating variables
*
* @param test
* @param parameterTypes
* @param parameterList
* @param position
* @param recursionDepth
* @return
* @throws ConstructionFailedException
*/
public List<VariableReference> satisfyParameters(TestCase test, VariableReference callee, List<Type> parameterTypes, List<Parameter> parameterList, int position, int recursionDepth, boolean allowNull, boolean excludeCalleeGenerators, boolean canReuseExistingVariables) throws ConstructionFailedException {
if (callee == null && excludeCalleeGenerators) {
throw new IllegalArgumentException("Exclude generators on null callee");
}
List<VariableReference> parameters = new ArrayList<>();
logger.debug("Trying to satisfy {} parameters at position {}", parameterTypes.size(), position);
for (int i = 0; i < parameterTypes.size(); i++) {
Type parameterType = parameterTypes.get(i);
Parameter parameter = null;
boolean allowNullForParameter = allowNull;
if (parameterList != null)
parameter = parameterList.get(i);
logger.debug("Current parameter type: {}", parameterType);
if (parameterType instanceof CaptureType) {
// TODO: This should not really happen in the first place
throw new ConstructionFailedException("Cannot satisfy capture type");
}
GenericClass parameterClass = new GenericClass(parameterType);
if (parameterClass.hasTypeVariables()) {
logger.debug("Parameter has type variables, replacing with wildcard");
parameterType = parameterClass.getWithWildcardTypes().getType();
}
int previousLength = test.size();
VariableReference var = null;
if (Properties.HONOUR_DATA_ANNOTATIONS && (parameterList != null)) {
if (GenericUtils.isAnnotationTypePresent(parameter.getAnnotations(), GenericUtils.NONNULL)) {
allowNullForParameter = false;
}
}
if (canReuseExistingVariables) {
logger.debug("Can re-use variables");
var = createOrReuseVariable(test, parameterType, position, recursionDepth, callee, allowNullForParameter, excludeCalleeGenerators, true);
} else {
logger.debug("Cannot re-use variables: attempt at creating new one");
var = createVariable(test, parameterType, position, recursionDepth, callee, allowNullForParameter, excludeCalleeGenerators, true, false);
if (var == null) {
throw new ConstructionFailedException("Failed to create variable for type " + parameterType + " at position " + position);
}
}
assert !(!allowNullForParameter && ConstraintHelper.isNull(var, test));
if (var.getStPosition() < position && ConstraintHelper.getLastPositionOfBounded(var, test) >= position) {
String msg = "Bounded variable issue when calling satisfyParameters()";
AtMostOnceLogger.warn(logger, msg);
throw new ConstructionFailedException(msg);
}
// double check
if (!var.isAssignableTo(parameterType)) {
throw new ConstructionFailedException("Error: " + var + " is not assignable to " + parameterType);
}
parameters.add(var);
int currentLength = test.size();
position += currentLength - previousLength;
}
logger.debug("Satisfied {} parameters", parameterTypes.size());
return parameters;
}
use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.
the class TestFactory method attemptObjectGeneration.
/**
* Try to generate an object suitable for Object.class
*
* @param test
* @param position
* @param recursionDepth
* @param allowNull
* @return
* @throws ConstructionFailedException
*/
protected VariableReference attemptObjectGeneration(TestCase test, int position, int recursionDepth, boolean allowNull) throws ConstructionFailedException {
if (allowNull && Randomness.nextDouble() <= Properties.NULL_PROBABILITY) {
logger.debug("Using a null reference to satisfy the type: {}", Object.class);
return createNull(test, Object.class, position, recursionDepth);
}
Set<GenericClass> castClasses = new LinkedHashSet<>(CastClassManager.getInstance().getCastClasses());
// needed a copy because hasGenerator(c) does modify that set...
List<GenericClass> classes = castClasses.stream().filter(c -> TestCluster.getInstance().hasGenerator(c) || c.isString()).collect(Collectors.toList());
classes.add(new GenericClass(Object.class));
// TODO if classes is empty, should we use FM here?
GenericClass choice = Randomness.choice(classes);
logger.debug("Chosen class for Object: {}", choice);
if (choice.isString()) {
return createOrReuseVariable(test, String.class, position, recursionDepth, null, allowNull, false, false);
}
GenericAccessibleObject<?> o = TestCluster.getInstance().getRandomGenerator(choice);
currentRecursion.add(o);
if (o == null) {
if (!TestCluster.getInstance().hasGenerator(Object.class)) {
logger.debug("We have no generator for Object.class ");
}
throw new ConstructionFailedException("Generator is null");
} else if (o.isField()) {
logger.debug("Attempting generating of Object.class via field of type Object.class");
VariableReference ret = addField(test, (GenericField) o, position, recursionDepth + 1);
ret.setDistance(recursionDepth + 1);
logger.debug("Success in generating type Object.class");
return ret;
} else if (o.isMethod()) {
logger.debug("Attempting generating of Object.class via method {} of type Object.class", o);
VariableReference ret = addMethod(test, (GenericMethod) o, position, recursionDepth + 1);
logger.debug("Success in generating type Object.class");
ret.setDistance(recursionDepth + 1);
return ret;
} else if (o.isConstructor()) {
logger.debug("Attempting generating of Object.class via constructor {} of type Object.class", o);
VariableReference ret = addConstructor(test, (GenericConstructor) o, position, recursionDepth + 1);
logger.debug("Success in generating Object.class");
ret.setDistance(recursionDepth + 1);
return ret;
} else {
logger.debug("No generators found for Object.class");
throw new ConstructionFailedException("No generator found for Object.class");
}
}
use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.
the class TestFactory method addCallFor.
/**
* Append given call to the test case at given position
*
* @param test
* @param call
* @param position
*/
private boolean addCallFor(TestCase test, VariableReference callee, GenericAccessibleObject<?> call, int position) {
logger.trace("addCallFor {}", callee.getName());
int previousLength = test.size();
currentRecursion.clear();
try {
if (call.isMethod()) {
GenericMethod method = (GenericMethod) call;
if (call.isStatic() || !method.getDeclaringClass().isAssignableFrom(callee.getVariableClass())) {
// Static methods / methods in other classes can be modifiers of the SUT if the SUT depends on static fields
addMethod(test, method, position, 0);
} else {
addMethodFor(test, callee, (GenericMethod) call.copyWithNewOwner(callee.getGenericClass()), position);
}
} else if (call.isField()) {
// A modifier for the SUT could also be a static field in another class
if (call.isStatic()) {
addFieldAssignment(test, (GenericField) call, position, 0);
} else {
addFieldFor(test, callee, (GenericField) call.copyWithNewOwner(callee.getGenericClass()), position);
}
}
return true;
} catch (ConstructionFailedException e) {
// TODO: Check this!
logger.debug("Inserting call {} has failed: {} Removing statements", call, e);
// TODO: Doesn't work if position != test.size()
int lengthDifference = test.size() - previousLength;
for (int i = lengthDifference - 1; i >= 0; i--) {
// we need to remove them in order, so that the testcase is at all time consistent
if (logger.isDebugEnabled()) {
logger.debug(" Removing statement: " + test.getStatement(position + i).getCode());
}
test.remove(position + i);
}
if (logger.isDebugEnabled()) {
logger.debug("Test after removal: " + test.toCode());
}
return false;
}
}
Aggregations