Search in sources :

Example 21 with ConstructionFailedException

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

the class GenericClass method getGenericTypeVariableInstantiation.

/**
 * Instantiate type variable
 *
 * @param typeMap
 * @param recursionLevel
 * @return
 * @throws ConstructionFailedException
 */
private GenericClass getGenericTypeVariableInstantiation(Map<TypeVariable<?>, Type> typeMap, int recursionLevel) throws ConstructionFailedException {
    if (typeMap.containsKey(type)) {
        logger.debug("Type contains {}: {}", toString(), typeMap);
        if (typeMap.get(type) == type) {
            // FIXXME: How does this happen?
            throw new ConstructionFailedException("Type points to itself");
        }
        // TODO: If typeMap.get(type) is a wildcard we need to keep the bounds of the
        // type variable in mind anyway, so this needs to be rewritten/fixed.
        GenericClass selectedClass = new GenericClass(typeMap.get(type)).getGenericInstantiation(typeMap, recursionLevel + 1);
        if (!selectedClass.satisfiesBoundaries((TypeVariable<?>) type)) {
            logger.debug("Cannot be instantiated to: {}", selectedClass);
        } else {
            logger.debug("Can be instantiated to: {}", selectedClass);
            return selectedClass;
        }
    }
    logger.debug("Type map does not contain {}: {}", toString(), typeMap);
    GenericClass selectedClass = CastClassManager.getInstance().selectCastClass((TypeVariable<?>) type, recursionLevel < Properties.MAX_GENERIC_DEPTH, typeMap);
    if (selectedClass == null) {
        throw new ConstructionFailedException("Unable to instantiate " + toString());
    }
    logger.debug("Getting instantiation of type variable {}: {}", toString(), selectedClass);
    Map<TypeVariable<?>, Type> extendedMap = new HashMap<TypeVariable<?>, Type>(typeMap);
    extendedMap.putAll(getTypeVariableMap());
    for (Type bound : ((TypeVariable<?>) type).getBounds()) {
        logger.debug("Current bound of variable {}: {}", type, bound);
        GenericClass boundClass = new GenericClass(bound);
        extendedMap.putAll(boundClass.getTypeVariableMap());
        if (boundClass.isParameterizedType()) {
            Class<?> boundRawClass = boundClass.getRawClass();
            if (boundRawClass.isAssignableFrom(selectedClass.getRawClass())) {
                Map<TypeVariable<?>, Type> xmap = TypeUtils.determineTypeArguments(selectedClass.getRawClass(), (ParameterizedType) boundClass.getType());
                extendedMap.putAll(xmap);
            }
        }
    }
    logger.debug("Updated type variable map to {}", extendedMap);
    GenericClass instantiation = selectedClass.getGenericInstantiation(extendedMap, recursionLevel + 1);
    typeMap.put((TypeVariable<?>) type, instantiation.getType());
    return instantiation;
}
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) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 22 with ConstructionFailedException

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

the class TestSuiteMinimizer method minimizeSuite.

/**
 * Minimize test suite with respect to the isCovered Method of the goals
 * defined by the supplied TestFitnessFactory
 *
 * @param suite a {@link org.evosuite.testsuite.TestSuiteChromosome} object.
 */
private void minimizeSuite(TestSuiteChromosome suite) {
    // in the case of whole suite generation
    for (ExecutableChromosome test : suite.getTestChromosomes()) {
        test.setChanged(true);
        test.clearCachedResults();
    }
    SecondaryObjective strategy = Properties.SECONDARY_OBJECTIVE[0];
    boolean size = false;
    if (strategy.equals("size")) {
        size = true;
        // If we want to remove tests, start with shortest
        Collections.sort(suite.tests, new Comparator<TestChromosome>() {

            @Override
            public int compare(TestChromosome chromosome1, TestChromosome chromosome2) {
                return chromosome1.size() - chromosome2.size();
            }
        });
    } else if (strategy.equals("maxlength")) {
        // If we want to remove the longest test, start with longest
        Collections.sort(suite.tests, new Comparator<TestChromosome>() {

            @Override
            public int compare(TestChromosome chromosome1, TestChromosome chromosome2) {
                return chromosome2.size() - chromosome1.size();
            }
        });
    }
    List<TestFitnessFunction> goals = new ArrayList<TestFitnessFunction>();
    List<Double> fitness = new ArrayList<Double>();
    for (TestFitnessFactory<?> ff : testFitnessFactories) {
        goals.addAll(ff.getCoverageGoals());
        fitness.add(ff.getFitness(suite));
    }
    boolean changed = true;
    while (changed && !isTimeoutReached()) {
        changed = false;
        removeEmptyTestCases(suite);
        for (TestChromosome testChromosome : suite.tests) {
            if (isTimeoutReached())
                break;
            for (int i = testChromosome.size() - 1; i >= 0; i--) {
                if (isTimeoutReached())
                    break;
                logger.debug("Current size: " + suite.size() + "/" + suite.totalLengthOfTestCases());
                logger.debug("Deleting statement " + testChromosome.getTestCase().getStatement(i).getCode() + " from test");
                TestChromosome originalTestChromosome = (TestChromosome) testChromosome.clone();
                boolean modified = false;
                try {
                    TestFactory testFactory = TestFactory.getInstance();
                    modified = testFactory.deleteStatementGracefully(testChromosome.getTestCase(), i);
                } catch (ConstructionFailedException e) {
                    modified = false;
                }
                if (!modified) {
                    testChromosome.setChanged(false);
                    testChromosome.setTestCase(originalTestChromosome.getTestCase());
                    logger.debug("Deleting failed");
                    continue;
                }
                testChromosome.setChanged(true);
                testChromosome.getTestCase().clearCoveredGoals();
                List<Double> modifiedVerFitness = new ArrayList<Double>();
                for (TestFitnessFactory<?> ff : testFitnessFactories) modifiedVerFitness.add(ff.getFitness(suite));
                int compare_ff = 0;
                for (int i_fit = 0; i_fit < modifiedVerFitness.size(); i_fit++) {
                    if (Double.compare(modifiedVerFitness.get(i_fit), fitness.get(i_fit)) < 0) {
                        // new value is lower than previous one
                        compare_ff = -1;
                        break;
                    } else if (Double.compare(modifiedVerFitness.get(i_fit), fitness.get(i_fit)) > 0) {
                        // new value is greater than previous one
                        compare_ff = 1;
                        break;
                    }
                }
                // the value 0 if d1 (previous fitness) is numerically equal to d2 (new fitness)
                if (compare_ff == 0) {
                    // if we can guarantee that we have the same fitness value with less statements, better
                    continue;
                } else if (// a value less than 0 if d1 is numerically less than d2
                compare_ff < -1) {
                    fitness = modifiedVerFitness;
                    changed = true;
                    /**
                     * This means, that we try to delete statements equally
                     * from each test case (If size is 'false'.) The hope is
                     * that the median length of the test cases is shorter,
                     * as opposed to the average length.
                     */
                    if (!size)
                        break;
                } else // and a value greater than 0 if d1 is numerically greater than d2
                if (compare_ff == 1) {
                    // Restore previous state
                    logger.debug("Can't remove statement " + originalTestChromosome.getTestCase().getStatement(i).getCode());
                    logger.debug("Restoring fitness from " + modifiedVerFitness + " to " + fitness);
                    testChromosome.setTestCase(originalTestChromosome.getTestCase());
                    testChromosome.setLastExecutionResult(originalTestChromosome.getLastExecutionResult());
                    testChromosome.setChanged(false);
                }
            }
        }
    }
    this.removeEmptyTestCases(suite);
    this.removeRedundantTestCases(suite, goals);
}
Also used : ConstructionFailedException(org.evosuite.ga.ConstructionFailedException) SecondaryObjective(org.evosuite.Properties.SecondaryObjective)

Example 23 with ConstructionFailedException

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

the class PrivateFieldStatement method copy.

@Override
public Statement copy(TestCase newTestCase, int offset) {
    try {
        PrivateFieldStatement pf;
        VariableReference owner = parameters.get(1).copy(newTestCase, offset);
        VariableReference value = parameters.get(3).copy(newTestCase, offset);
        pf = new PrivateFieldStatement(newTestCase, ownerClass, fieldName, owner, value);
        return pf;
    } catch (NoSuchFieldException | ConstructionFailedException e) {
        throw new RuntimeException("EvoSuite bug", e);
    }
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 24 with ConstructionFailedException

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

the class TestCluster method cacheGenerators.

/**
 * Calculate and cache all generators for a particular type. All generic
 * types on the generator are instantiated according to the produced type
 *
 * @param clazz
 * @throws ConstructionFailedException
 */
private void cacheGenerators(GenericClass clazz) throws ConstructionFailedException {
    if (generatorCache.containsKey(clazz)) {
        return;
    }
    logger.debug("1. Caching generators for {}", clazz);
    Set<GenericAccessibleObject<?>> targetGenerators = new LinkedHashSet<>();
    if (clazz.isObject()) {
        logger.debug("2. Target class is object: {}", clazz);
        for (GenericClass generatorClazz : generators.keySet()) {
            if (generatorClazz.isObject()) {
                targetGenerators.addAll(generators.get(generatorClazz));
            }
        }
    } else {
        logger.debug("2. Target class is not object: {}", clazz);
        for (GenericClass generatorClazz : generators.keySet()) {
            if (generatorClazz.canBeInstantiatedTo(clazz)) {
                // logger.debug("4. generator " + generatorClazz + " can be instantiated to " + clazz);
                GenericClass instantiatedGeneratorClazz = generatorClazz.getWithParametersFromSuperclass(clazz);
                logger.debug("Instantiated type: {} for {} and superclass {}", instantiatedGeneratorClazz, generatorClazz, clazz);
                for (GenericAccessibleObject<?> generator : generators.get(generatorClazz)) {
                    logger.debug("5. current instantiated generator: {}", generator);
                    try {
                        if ((generator.isMethod() || generator.isField()) && clazz.isParameterizedType() && GenericClass.isMissingTypeParameters(generator.getGenericGeneratedType())) {
                            logger.debug("No type parameters present in generator for {}: {}", clazz, generator);
                            continue;
                        }
                        // Set owner type parameters from new return type
                        GenericAccessibleObject<?> newGenerator = generator.copyWithOwnerFromReturnType(instantiatedGeneratorClazz);
                        boolean hadTypeParameters = false;
                        // Instantiate potential further type variables based on type variables of return type
                        if (newGenerator.getOwnerClass().hasWildcardOrTypeVariables()) {
                            logger.debug("Instantiating type parameters of owner type: {}", newGenerator.getOwnerClass());
                            GenericClass concreteClass = newGenerator.getOwnerClass().getGenericInstantiation(clazz.getTypeVariableMap());
                            newGenerator = newGenerator.copyWithNewOwner(concreteClass);
                            hadTypeParameters = true;
                        }
                        // If it is a generic method, instantiate generic type variables for the produced class
                        if (newGenerator.hasTypeParameters()) {
                            logger.debug("Instantiating type parameters");
                            /*
								 * TODO:
								 * public class Foo<X> {
								 *   public <X> Foo<X> getFoo() {
								 *     // ...
								 *   }
								 * }
								 *
								 * Here X and X are two different type variables, and these need to be matched here!
								 *
								 */
                            newGenerator = newGenerator.getGenericInstantiationFromReturnValue(clazz);
                            hadTypeParameters = true;
                        // newGenerator = newGenerator.getGenericInstantiation(clazz);
                        }
                        logger.debug("Current generator: {}", newGenerator);
                        if ((!hadTypeParameters && generatorClazz.equals(clazz)) || clazz.isAssignableFrom(newGenerator.getGeneratedType())) {
                            logger.debug("Got new generator: {} which generated: {}", newGenerator, newGenerator.getGeneratedClass());
                            logger.debug("{} vs {}", (!hadTypeParameters && generatorClazz.equals(clazz)), clazz.isAssignableFrom(newGenerator.getGeneratedType()));
                            targetGenerators.add(newGenerator);
                        } else if (logger.isDebugEnabled()) {
                            logger.debug("New generator not assignable: {}", newGenerator);
                            logger.debug("Had type parameters: {}", hadTypeParameters);
                            logger.debug("generatorClazz.equals(clazz): {}", generatorClazz.equals(clazz));
                            try {
                                logger.debug("clazz.isAssignableFrom({}): ", newGenerator.getGeneratedType());
                                logger.debug("                        {}", clazz.isAssignableFrom(newGenerator.getGeneratedType()));
                            } catch (Throwable t) {
                                logger.debug("Error", t);
                            }
                        }
                    } catch (ConstructionFailedException e) {
                        logger.debug("5. ERROR", e);
                    }
                }
            // FIXME:
            // There are cases where this might lead to relevant cast classes not being included
            // but in manycases it will pull in large numbers of useless dependencies.
            // Commented out for now, until we find a case where the problem can be properly studied.
            // } else {
            // logger.debug("4. generator {} CANNOT be instantiated to {}", generatorClazz, clazz);
            // for(GenericClass boundClass : generatorClazz.getGenericBounds()) {
            // CastClassManager.getInstance().addCastClass(boundClass, 0);
            // }
            }
        }
        logger.debug("Found generators for {}: {}", clazz, targetGenerators.size());
    }
    logger.debug("]");
    generatorCache.put(clazz, targetGenerators);
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) GenericClass(org.evosuite.utils.generic.GenericClass) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 25 with ConstructionFailedException

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

the class TestCluster method getRandomizedCallsToEnvironment.

public List<GenericAccessibleObject<?>> getRandomizedCallsToEnvironment() {
    if (environmentMethods.isEmpty()) {
        return null;
    }
    List<GenericAccessibleObject<?>> list = new ArrayList<>();
    for (GenericAccessibleObject<?> obj : environmentMethods) {
        try {
            if (obj.getOwnerClass().hasWildcardOrTypeVariables()) {
                GenericClass concreteClass = obj.getOwnerClass().getGenericInstantiation();
                obj = obj.copyWithNewOwner(concreteClass);
            }
            if (obj.hasTypeParameters()) {
                obj = obj.getGenericInstantiation();
            }
        } catch (ConstructionFailedException e) {
            logger.error("Failed generic instantiation in " + obj);
            continue;
        }
        list.add(obj);
    }
    Collections.shuffle(list);
    return list;
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) GenericClass(org.evosuite.utils.generic.GenericClass) 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