Search in sources :

Example 36 with ConstructionFailedException

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

the class TestFactory method createNull.

/**
 * Create and return a new null variable
 *
 * @param test
 * @param type
 * @param position
 * @param recursionDepth
 * @return
 * @throws ConstructionFailedException
 */
private VariableReference createNull(TestCase test, Type type, int position, int recursionDepth) throws ConstructionFailedException {
    GenericClass genericType = new GenericClass(type);
    // in a public method. This would lead to compile errors
    if (!TestUsageChecker.canUse(genericType.getRawClass())) {
        throw new ConstructionFailedException("Cannot use class " + type);
    }
    if (genericType.hasWildcardOrTypeVariables()) {
        type = genericType.getGenericInstantiation().getType();
    }
    Statement st = new NullStatement(test, type);
    test.addStatement(st, position);
    VariableReference ret = test.getStatement(position).getReturnValue();
    ret.setDistance(recursionDepth);
    return ret;
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 37 with ConstructionFailedException

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

the class TestFactory method createOrReuseVariable.

/**
 * Create a new variable or reuse and existing one
 *
 * @param test
 * @param parameterType
 * @param position
 * @param recursionDepth
 * @param exclude
 * @return
 * @throws ConstructionFailedException
 */
private VariableReference createOrReuseVariable(TestCase test, Type parameterType, int position, int recursionDepth, VariableReference exclude, boolean allowNull, boolean excludeCalleeGenerators, boolean canUseMocks) throws ConstructionFailedException {
    if (Properties.SEED_TYPES && parameterType.equals(Object.class)) {
        return createOrReuseObjectVariable(test, position, recursionDepth, exclude, allowNull, canUseMocks);
    }
    double reuse = Randomness.nextDouble();
    List<VariableReference> objects = getCandidatesForReuse(test, parameterType, position, exclude, allowNull, canUseMocks);
    GenericClass clazz = new GenericClass(parameterType);
    boolean isPrimitiveOrSimilar = clazz.isPrimitive() || clazz.isWrapperType() || clazz.isEnum() || clazz.isClass() || clazz.isString();
    if (isPrimitiveOrSimilar && !objects.isEmpty() && reuse <= Properties.PRIMITIVE_REUSE_PROBABILITY) {
        logger.debug(" Looking for existing object of type {}", parameterType);
        VariableReference reference = Randomness.choice(objects);
        return reference;
    } else if (!isPrimitiveOrSimilar && !objects.isEmpty() && (reuse <= Properties.OBJECT_REUSE_PROBABILITY)) {
        if (logger.isDebugEnabled()) {
            logger.debug(" Choosing from {} existing objects: {}", objects.size(), Arrays.toString(objects.toArray()));
        }
        VariableReference reference = Randomness.choice(objects);
        // logger.debug(" Using existing object of type {}: {}", parameterType, reference);
        return reference;
    }
    // if chosen to not re-use existing variable, try create a new one
    VariableReference created = createVariable(test, parameterType, position, recursionDepth, exclude, allowNull, excludeCalleeGenerators, canUseMocks, true);
    if (created != null) {
        return created;
    }
    // could not create, so go back in trying to re-use an existing variable
    if (objects.isEmpty()) {
        if (allowNull) {
            return createNull(test, parameterType, position, recursionDepth);
        } else {
            throw new ConstructionFailedException("No objects and generators for type " + parameterType);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug(" Choosing from {} existing objects: {}", objects.size(), Arrays.toString(objects.toArray()));
    }
    VariableReference reference = Randomness.choice(objects);
    assert canUseMocks || !(test.getStatement(reference.getStPosition()) instanceof FunctionalMockStatement);
    logger.debug(" Using existing object of type {}: {}", parameterType, reference);
    return reference;
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 38 with ConstructionFailedException

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

the class TestFactory method getPossibleCalls.

/**
 * Retrieve all the replacement calls that can be inserted at this position
 * without changing the length
 *
 * @param returnType
 * @param objects
 * @return
 */
private List<GenericAccessibleObject<?>> getPossibleCalls(Type returnType, List<VariableReference> objects) {
    List<GenericAccessibleObject<?>> calls = new ArrayList<GenericAccessibleObject<?>>();
    Set<GenericAccessibleObject<?>> allCalls;
    try {
        allCalls = TestCluster.getInstance().getGenerators(new GenericClass(returnType), true);
    } catch (ConstructionFailedException e) {
        return calls;
    }
    for (GenericAccessibleObject<?> call : allCalls) {
        Set<Type> dependencies = null;
        if (call.isMethod()) {
            GenericMethod method = (GenericMethod) call;
            if (method.hasTypeParameters()) {
                try {
                    call = method.getGenericInstantiation(new GenericClass(returnType));
                } catch (ConstructionFailedException e) {
                    continue;
                }
            }
            if (!((GenericMethod) call).getReturnType().equals(returnType))
                continue;
            dependencies = getDependencies((GenericMethod) call);
        } else if (call.isConstructor()) {
            dependencies = getDependencies((GenericConstructor) call);
        } else if (call.isField()) {
            if (!((GenericField) call).getFieldType().equals(returnType))
                continue;
            dependencies = getDependencies((GenericField) call);
        } else {
            assert (false);
        }
        if (dependenciesSatisfied(dependencies, objects)) {
            calls.add(call);
        }
    }
    return calls;
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) CaptureType(com.googlecode.gentyref.CaptureType) GenericClass(org.evosuite.utils.generic.GenericClass) ArrayList(java.util.ArrayList) GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericField(org.evosuite.utils.generic.GenericField) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 39 with ConstructionFailedException

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

the class TestFactory method addMethodFor.

/**
 * Add a call on the method for the given callee at position
 *
 * @param test
 * @param callee
 * @param method
 * @param position
 * @return
 * @throws ConstructionFailedException
 */
public VariableReference addMethodFor(TestCase test, VariableReference callee, GenericMethod method, int position) throws ConstructionFailedException {
    logger.debug("Adding method {} for {} (Generating {})", method, callee, method.getGeneratedClass());
    if (position <= callee.getStPosition()) {
        throw new ConstructionFailedException("Cannot insert call on object before the object is defined");
    }
    currentRecursion.clear();
    int length = test.size();
    boolean allowNull = true;
    Constraints constraints = method.getMethod().getAnnotation(Constraints.class);
    if (constraints != null && constraints.noNullInputs()) {
        allowNull = false;
    }
    // Added 'null' as additional parameter - fix for @NotNull annotations issue on evo mailing list
    List<VariableReference> parameters = satisfyParameters(test, callee, Arrays.asList(method.getParameterTypes()), Arrays.asList(method.getMethod().getParameters()), position, 1, allowNull, false, true);
    int newLength = test.size();
    position += (newLength - length);
    Statement st = new MethodStatement(test, method, callee, parameters);
    VariableReference ret = test.addStatement(st, position);
    ret.setDistance(callee.getDistance() + 1);
    logger.debug("Success: Adding method {}", method);
    return ret;
}
Also used : PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) Constraints(org.evosuite.runtime.annotation.Constraints) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 40 with ConstructionFailedException

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

the class TestFactory method insertRandomReflectionCallOnObject.

private boolean insertRandomReflectionCallOnObject(TestCase test, VariableReference callee, int position, int recursionDepth) throws ConstructionFailedException {
    logger.debug("Recursion depth: " + recursionDepth);
    if (recursionDepth > Properties.MAX_RECURSION) {
        logger.debug("Max recursion depth reached");
        throw new ConstructionFailedException("Max recursion depth reached");
    }
    if (!reflectionFactory.getReflectedClass().isAssignableFrom(callee.getVariableClass())) {
        logger.debug("Reflection not performed on class {}", callee.getVariableClass());
        return false;
    }
    int length = test.size();
    List<VariableReference> parameters = null;
    Statement st = null;
    if (reflectionFactory.nextUseField()) {
        Field field = reflectionFactory.nextField();
        /*
				In theory, there might be cases in which using null in PA might help increasing
				coverage. However, likely most of the time we ll end up in useless tests throwing
				NPE on the private fields. As we maximize the number of methods throwing exceptions,
				we could end up with a lot of useless tests
			 */
        boolean allowNull = false;
        // Added 'null' as additional parameter - fix for @NotNull annotations issue on evo mailing list
        parameters = satisfyParameters(test, callee, // we need a reference to the SUT, and one to a variable of same type of chosen field
        Arrays.asList((Type) field.getType()), null, position, recursionDepth + 1, allowNull, false, true);
        try {
            st = new PrivateFieldStatement(test, reflectionFactory.getReflectedClass(), field.getName(), callee, parameters.get(0));
        } catch (NoSuchFieldException e) {
            logger.error("Reflection problem: " + e, e);
            throw new ConstructionFailedException("Reflection problem");
        }
    } else {
        // method
        Method method = reflectionFactory.nextMethod();
        List<Type> list = new ArrayList<>();
        list.addAll(Arrays.asList(method.getParameterTypes()));
        // Added 'null' as additional parameter - fix for @NotNull annotations issue on evo mailing list
        parameters = satisfyParameters(test, callee, list, null, position, recursionDepth + 1, true, false, true);
        st = new PrivateMethodStatement(test, reflectionFactory.getReflectedClass(), method, callee, parameters, Modifier.isStatic(method.getModifiers()));
    }
    int newLength = test.size();
    position += (newLength - length);
    test.addStatement(st, position);
    return true;
}
Also used : PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) ArrayList(java.util.ArrayList) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) GenericField(org.evosuite.utils.generic.GenericField) CaptureType(com.googlecode.gentyref.CaptureType)

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