Search in sources :

Example 11 with ConstructionFailedException

use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.

the class TestFactory method insertRandomCall.

/**
 * Insert a random call for the UUT at the given position
 *
 * @param test
 * @param position
 */
public boolean insertRandomCall(TestCase test, int position) {
    int previousLength = test.size();
    String name = "";
    currentRecursion.clear();
    logger.debug("Inserting random call at position {}", position);
    try {
        if (reflectionFactory == null) {
            final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();
            reflectionFactory = new ReflectionFactory(targetClass);
        }
        if (reflectionFactory.hasPrivateFieldsOrMethods() && TimeController.getInstance().getPhasePercentage() >= Properties.REFLECTION_START_PERCENT && (Randomness.nextDouble() < Properties.P_REFLECTION_ON_PRIVATE || TestCluster.getInstance().getNumTestCalls() == 0)) {
            logger.debug("Going to insert random reflection call");
            return insertRandomReflectionCall(test, position, 0);
        }
        GenericAccessibleObject<?> o = TestCluster.getInstance().getRandomTestCall(test);
        if (o == null) {
            logger.warn("Have no target methods to test");
            return false;
        } else if (o.isConstructor()) {
            if (InstanceOnlyOnce.canInstantiateOnlyOnce(o.getDeclaringClass()) && ConstraintHelper.countNumberOfNewInstances(test, o.getDeclaringClass()) != 0) {
                return false;
            }
            GenericConstructor c = (GenericConstructor) o;
            logger.debug("Adding constructor call {}", c.getName());
            name = c.getName();
            addConstructor(test, c, position, 0);
        } else if (o.isMethod()) {
            GenericMethod m = (GenericMethod) o;
            logger.debug("Adding method call {}", m.getName());
            name = m.getName();
            if (!m.isStatic()) {
                logger.debug("Getting callee of type {}", m.getOwnerClass().getTypeName());
                VariableReference callee = null;
                Type target = m.getOwnerType();
                if (!test.hasObject(target, position)) {
                    // no FM for SUT
                    callee = createObject(test, target, position, 0, null, false, false, true);
                    position += test.size() - previousLength;
                    previousLength = test.size();
                } else {
                    callee = test.getRandomNonNullObject(target, position);
                // This may also be an inner class, in this case we can't use a SUT instance
                // if (!callee.isAssignableTo(m.getDeclaringClass())) {
                // callee = test.getRandomNonNullObject(m.getDeclaringClass(), position);
                // }
                }
                logger.debug("Got callee of type {}", callee.getGenericClass().getTypeName());
                if (!TestUsageChecker.canUse(m.getMethod(), callee.getVariableClass())) {
                    logger.debug("Cannot call method {} with callee of type {}", m, callee.getClassName());
                    throw new ConstructionFailedException("Cannot apply method to this callee");
                }
                addMethodFor(test, callee, m.copyWithNewOwner(callee.getGenericClass()), position);
            } else {
                // We only use this for static methods to avoid using wrong constructors (?)
                addMethod(test, m, position, 0);
            }
        } else if (o.isField()) {
            GenericField f = (GenericField) o;
            name = f.getName();
            logger.debug("Adding field {}", f.getName());
            if (Randomness.nextBoolean()) {
                addFieldAssignment(test, f, position, 0);
            } else {
                addField(test, f, position, 0);
            }
        } else {
            logger.error("Got type other than method or constructor!");
            return false;
        }
        return true;
    } catch (ConstructionFailedException e) {
        // TODO: Check this! - TestCluster replaced
        // TestCluster.getInstance().checkDependencies(o);
        logger.debug("Inserting statement {} has failed. Removing statements: {}", name, 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);
        }
        return false;
    }
}
Also used : CaptureType(com.googlecode.gentyref.CaptureType) ReflectionFactory(org.evosuite.testcase.statements.reflection.ReflectionFactory) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericField(org.evosuite.utils.generic.GenericField) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 12 with ConstructionFailedException

use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.

the class TestFactory method changeCall.

/**
 * Replace the statement with a new statement using given call
 *
 * @param test
 * @param statement
 * @param call
 * @throws ConstructionFailedException
 */
public void changeCall(TestCase test, Statement statement, GenericAccessibleObject<?> call) throws ConstructionFailedException {
    int position = statement.getReturnValue().getStPosition();
    logger.debug("Changing call {} with {}", test.getStatement(position), call);
    if (call.isMethod()) {
        GenericMethod method = (GenericMethod) call;
        if (method.hasTypeParameters())
            throw new ConstructionFailedException("Cannot handle generic methods properly");
        VariableReference retval = statement.getReturnValue();
        VariableReference callee = null;
        if (!method.isStatic()) {
            callee = getRandomNonNullNonPrimitiveObject(test, method.getOwnerType(), position);
        }
        List<VariableReference> parameters = new ArrayList<>();
        for (Type type : method.getParameterTypes()) {
            parameters.add(test.getRandomObject(type, position));
        }
        MethodStatement m = new MethodStatement(test, method, callee, parameters, retval);
        test.setStatement(m, position);
        logger.debug("Using method {}", m.getCode());
    } else if (call.isConstructor()) {
        GenericConstructor constructor = (GenericConstructor) call;
        VariableReference retval = statement.getReturnValue();
        List<VariableReference> parameters = new ArrayList<>();
        for (Type type : constructor.getParameterTypes()) {
            parameters.add(test.getRandomObject(type, position));
        }
        ConstructorStatement c = new ConstructorStatement(test, constructor, retval, parameters);
        test.setStatement(c, position);
        logger.debug("Using constructor {}", c.getCode());
    } else if (call.isField()) {
        GenericField field = (GenericField) call;
        VariableReference retval = statement.getReturnValue();
        VariableReference source = null;
        if (!field.isStatic())
            source = getRandomNonNullNonPrimitiveObject(test, field.getOwnerType(), position);
        try {
            FieldStatement f = new FieldStatement(test, field, source, retval);
            test.setStatement(f, position);
            logger.debug("Using field {}", f.getCode());
        } catch (Throwable e) {
            logger.error("Error: " + e + " , Field: " + field + " , Test: " + test);
            throw new Error(e);
        }
    }
}
Also used : PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) ArrayList(java.util.ArrayList) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) CaptureType(com.googlecode.gentyref.CaptureType) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) MockList(org.evosuite.runtime.mock.MockList) ArrayList(java.util.ArrayList) List(java.util.List) GenericField(org.evosuite.utils.generic.GenericField)

Example 13 with ConstructionFailedException

use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.

the class TestFactory method assignArray.

/**
 * Assign a value to an array index for a given set of objects
 *
 * @param test
 * @param array
 * @param arrayIndex
 * @param position
 * @param objects
 * @throws ConstructionFailedException
 */
protected void assignArray(TestCase test, VariableReference array, int arrayIndex, int position, List<VariableReference> objects) throws ConstructionFailedException {
    assert (array instanceof ArrayReference);
    ArrayReference arrRef = (ArrayReference) array;
    if (!objects.isEmpty() && Randomness.nextDouble() <= Properties.OBJECT_REUSE_PROBABILITY) {
        // Assign an existing value
        // TODO:
        // Do we need a special "[Array]AssignmentStatement"?
        VariableReference choice = Randomness.choice(objects);
        logger.debug("Reusing value: " + choice);
        ArrayIndex index = new ArrayIndex(test, arrRef, arrayIndex);
        Statement st = new AssignmentStatement(test, index, choice);
        test.addStatement(st, position);
    } else {
        // Assign a new value
        // Need a primitive, method, constructor, or field statement where
        // retval is set to index
        // Need a version of attemptGeneration that takes retval as
        // parameter
        // OR: Create a new variablereference and then assign it to array
        // (better!)
        int oldLength = test.size();
        logger.debug("Attempting generation of object of type " + array.getComponentType());
        VariableReference var = attemptGeneration(test, array.getComponentType(), position);
        // Generics instantiation may lead to invalid types, so better double check
        if (!var.isAssignableTo(arrRef.getComponentType())) {
            throw new ConstructionFailedException("Error");
        }
        position += test.size() - oldLength;
        ArrayIndex index = new ArrayIndex(test, arrRef, arrayIndex);
        Statement st = new AssignmentStatement(test, index, var);
        test.addStatement(st, position);
    }
}
Also used : PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 14 with ConstructionFailedException

use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.

the class DefaultTestCase method getRandomNonNullObject.

/* (non-Javadoc)
	 * @see org.evosuite.testcase.TestCase#getRandomObject(java.lang.reflect.Type, int)
	 */
/**
 * {@inheritDoc}
 */
@Override
public VariableReference getRandomNonNullObject(Type type, int position) throws ConstructionFailedException {
    Inputs.checkNull(type);
    List<VariableReference> variables = getObjects(type, position);
    Iterator<VariableReference> iterator = variables.iterator();
    while (iterator.hasNext()) {
        VariableReference ref = iterator.next();
        if (ref instanceof NullReference || (this.getStatement(ref.getStPosition()) instanceof FunctionalMockStatement)) {
            iterator.remove();
        }
    }
    if (variables.isEmpty())
        throw new ConstructionFailedException("Found no variables of type " + type + " at position " + position);
    return Randomness.choice(variables);
}
Also used : ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 15 with ConstructionFailedException

use of org.evosuite.ga.ConstructionFailedException in project evosuite by EvoSuite.

the class DefaultTestCase method getRandomNonNullNonPrimitiveObject.

/* (non-Javadoc)
	 * @see org.evosuite.testcase.TestCase#getRandomObject(java.lang.reflect.Type, int)
	 */
/**
 * {@inheritDoc}
 */
@Override
public VariableReference getRandomNonNullNonPrimitiveObject(Type type, int position) throws ConstructionFailedException {
    Inputs.checkNull(type);
    List<VariableReference> variables = getObjects(type, position);
    Iterator<VariableReference> iterator = variables.iterator();
    while (iterator.hasNext()) {
        VariableReference var = iterator.next();
        if (var instanceof NullReference)
            iterator.remove();
        else if (getStatement(var.getStPosition()) instanceof PrimitiveStatement)
            iterator.remove();
        else if (var.isPrimitive() || var.isWrapperType())
            iterator.remove();
        else if (this.getStatement(var.getStPosition()) instanceof FunctionalMockStatement && !(this.getStatement(var.getStPosition()) instanceof FunctionalMockForAbstractClassStatement))
            iterator.remove();
    }
    if (variables.isEmpty())
        throw new ConstructionFailedException("Found no variables of type " + type + " at position " + position);
    return Randomness.choice(variables);
}
Also used : ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Aggregations

ConstructionFailedException (org.evosuite.ga.ConstructionFailedException)43 GenericClass (org.evosuite.utils.generic.GenericClass)16 PrivateFieldStatement (org.evosuite.testcase.statements.reflection.PrivateFieldStatement)14 PrivateMethodStatement (org.evosuite.testcase.statements.reflection.PrivateMethodStatement)14 CaptureType (com.googlecode.gentyref.CaptureType)11 GenericAccessibleObject (org.evosuite.utils.generic.GenericAccessibleObject)11 GenericMethod (org.evosuite.utils.generic.GenericMethod)10 ArrayList (java.util.ArrayList)8 GenericField (org.evosuite.utils.generic.GenericField)7 TestFactory (org.evosuite.testcase.TestFactory)6 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)6 TestCase (org.evosuite.testcase.TestCase)4 VariableReference (org.evosuite.testcase.variable.VariableReference)4 Type (java.lang.reflect.Type)3 GenericArrayType (java.lang.reflect.GenericArrayType)2 ParameterizedType (java.lang.reflect.ParameterizedType)2 TypeVariable (java.lang.reflect.TypeVariable)2 WildcardType (java.lang.reflect.WildcardType)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2