Search in sources :

Example 31 with ConstructionFailedException

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;
}
Also used : ConstantInliner(org.evosuite.testcase.ConstantInliner) VariableReference(org.evosuite.testcase.variable.VariableReference) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) TestCase(org.evosuite.testcase.TestCase) TestFactory(org.evosuite.testcase.TestFactory) ArrayList(java.util.ArrayList) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 32 with ConstructionFailedException

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));
}
Also used : GenericArrayType(java.lang.reflect.GenericArrayType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) CaptureType(com.googlecode.gentyref.CaptureType) TypeVariable(java.lang.reflect.TypeVariable) ParameterizedTypeImpl(org.evosuite.utils.ParameterizedTypeImpl) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 33 with ConstructionFailedException

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;
}
Also used : CaptureType(com.googlecode.gentyref.CaptureType) CaptureType(com.googlecode.gentyref.CaptureType) GenericClass(org.evosuite.utils.generic.GenericClass) ArrayList(java.util.ArrayList) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 34 with ConstructionFailedException

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");
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) GenericClass(org.evosuite.utils.generic.GenericClass) Arrays(java.util.Arrays) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) org.evosuite.testcase.statements(org.evosuite.testcase.statements) TimeController(org.evosuite.TimeController) EnvironmentStatements(org.evosuite.testcase.statements.environment.EnvironmentStatements) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) InstanceOnlyOnce(org.evosuite.testcase.jee.InstanceOnlyOnce) LoggerFactory(org.slf4j.LoggerFactory) MockList(org.evosuite.runtime.mock.MockList) ArrayList(java.util.ArrayList) EvoServletState(org.evosuite.runtime.javaee.javax.servlet.EvoServletState) ClassUtils(org.apache.commons.lang3.ClassUtils) GenericMethod(org.evosuite.utils.generic.GenericMethod) org.evosuite.testcase.variable(org.evosuite.testcase.variable) Constraints(org.evosuite.runtime.annotation.Constraints) org.evosuite.setup(org.evosuite.setup) LinkedHashSet(java.util.LinkedHashSet) InjectionSupport(org.evosuite.testcase.jee.InjectionSupport) java.lang.reflect(java.lang.reflect) AtMostOnceLogger(org.evosuite.runtime.util.AtMostOnceLogger) Properties(org.evosuite.Properties) Logger(org.slf4j.Logger) GenericTypeReflector(com.googlecode.gentyref.GenericTypeReflector) Iterator(java.util.Iterator) HttpServlet(javax.servlet.http.HttpServlet) Collection(java.util.Collection) Inputs(org.evosuite.runtime.util.Inputs) ObjectPoolManager(org.evosuite.seeding.ObjectPoolManager) GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) Set(java.util.Set) CastClassManager(org.evosuite.seeding.CastClassManager) RandomInsertion(org.evosuite.testcase.mutation.RandomInsertion) GenericField(org.evosuite.utils.generic.GenericField) ReflectionFactory(org.evosuite.testcase.statements.reflection.ReflectionFactory) Collectors(java.util.stream.Collectors) Randomness(org.evosuite.utils.Randomness) TestGenerationContext(org.evosuite.TestGenerationContext) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) List(java.util.List) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) Injector(org.evosuite.runtime.javaee.injection.Injector) GenericUtils(org.evosuite.utils.generic.GenericUtils) CaptureType(com.googlecode.gentyref.CaptureType) Collections(java.util.Collections) ServletSupport(org.evosuite.testcase.jee.ServletSupport) GenericClass(org.evosuite.utils.generic.GenericClass) GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) GenericConstructor(org.evosuite.utils.generic.GenericConstructor) GenericField(org.evosuite.utils.generic.GenericField) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 35 with ConstructionFailedException

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;
    }
}
Also used : GenericMethod(org.evosuite.utils.generic.GenericMethod) GenericField(org.evosuite.utils.generic.GenericField) 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