Search in sources :

Example 16 with ConstructionFailedException

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

the class TestFactory method createPrimitive.

/**
 * Create and return a new primitive variable
 *
 * @param test
 * @param position
 * @param recursionDepth
 * @return
 * @throws ConstructionFailedException
 */
private VariableReference createPrimitive(TestCase test, GenericClass clazz, int position, int recursionDepth) throws ConstructionFailedException {
    // Special case: we cannot instantiate Class<Class<?>>
    if (clazz.isClass()) {
        if (clazz.hasWildcardOrTypeVariables()) {
            logger.debug("Getting generic instantiation of class");
            clazz = clazz.getGenericInstantiation();
            logger.debug("Chosen: " + clazz);
        }
        Type parameterType = clazz.getParameterTypes().get(0);
        if (!(parameterType instanceof WildcardType) && GenericTypeReflector.erase(parameterType).equals(Class.class)) {
            throw new ConstructionFailedException("Cannot instantiate a class with a class");
        }
    }
    Statement st = PrimitiveStatement.getRandomStatement(test, clazz, position);
    VariableReference ret = test.addStatement(st, position);
    ret.setDistance(recursionDepth);
    return ret;
}
Also used : CaptureType(com.googlecode.gentyref.CaptureType) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) GenericClass(org.evosuite.utils.generic.GenericClass) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 17 with ConstructionFailedException

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

the class TestFactory method createObject.

/**
 * Create a new non-null, non-primitive object and return reference
 *
 * @param test
 * @param type
 * @param position
 * @param recursionDepth
 * @return
 * @throws ConstructionFailedException
 */
public VariableReference createObject(TestCase test, Type type, int position, int recursionDepth, VariableReference generatorRefToExclude, boolean allowNull, boolean canUseFunctionalMocks, boolean canReuseVariables) throws ConstructionFailedException {
    GenericClass clazz = new GenericClass(type);
    logger.debug("Going to create object for type {}", type);
    VariableReference ret = null;
    if (canUseFunctionalMocks && TimeController.getInstance().getPhasePercentage() >= Properties.FUNCTIONAL_MOCKING_PERCENT && Randomness.nextDouble() < Properties.P_FUNCTIONAL_MOCKING && FunctionalMockStatement.canBeFunctionalMocked(type)) {
        // mock creation
        logger.debug("Creating functional mock for {}", type);
        ret = addFunctionalMock(test, type, position, recursionDepth + 1);
    } else {
        // regular creation
        GenericAccessibleObject<?> o = TestCluster.getInstance().getRandomGenerator(clazz, currentRecursion, test, position, generatorRefToExclude, recursionDepth);
        currentRecursion.add(o);
        if (o == null) {
            if (canReuseVariables) {
                /*
					It could happen that there is no current valid generator for 'position', but valid
					generators were usable before. This is for example the case when the only generator
					has an "atMostOnce" constraint, and so can only be used once.
					In such case, we should just re-use an existing variable if it exists, as long as
					it is not a functional mock (which can be used only once)
				 */
                for (int i = position - 1; i >= 0; i--) {
                    Statement statement = test.getStatement(i);
                    VariableReference var = statement.getReturnValue();
                    if (!allowNull && ConstraintHelper.isNull(var, test)) {
                        continue;
                    }
                    if (var.isAssignableTo(type) && !(statement instanceof FunctionalMockStatement)) {
                        logger.debug("Reusing variable at position {}", var.getStPosition());
                        return var;
                    }
                }
            }
            if (canUseFunctionalMocks && (Properties.MOCK_IF_NO_GENERATOR || Properties.P_FUNCTIONAL_MOCKING > 0)) {
                /*
						Even if mocking is not active yet in this phase, if we have
						no generator for a type, we use mocking directly
				 	*/
                if (FunctionalMockStatement.canBeFunctionalMocked(type)) {
                    logger.debug("Using mock for type {}", type);
                    ret = addFunctionalMock(test, type, position, recursionDepth + 1);
                } else if (clazz.isAbstract() && FunctionalMockStatement.canBeFunctionalMockedIncludingSUT(type)) {
                    {
                        logger.debug("Using mock for abstract type {}", type);
                        ret = addFunctionalMockForAbstractClass(test, type, position, recursionDepth + 1);
                    }
                }
            }
            if (ret == null) {
                logger.debug("No mock solution found: {}, {}, {}, {}", canUseFunctionalMocks, Properties.MOCK_IF_NO_GENERATOR, FunctionalMockStatement.canBeFunctionalMocked(type), FunctionalMockStatement.canBeFunctionalMockedIncludingSUT(type));
                if (!TestCluster.getInstance().hasGenerator(type)) {
                    logger.debug("No generators found for {}, attempting to resolve dependencies", type);
                    TestClusterGenerator clusterGenerator = TestGenerationContext.getInstance().getTestClusterGenerator();
                    Class<?> mock = MockList.getMockClass(clazz.getRawClass().getCanonicalName());
                    if (mock != null) {
                        clusterGenerator.addNewDependencies(Arrays.asList(mock));
                    } else {
                        clusterGenerator.addNewDependencies(Arrays.asList(clazz.getRawClass()));
                    }
                    if (TestCluster.getInstance().hasGenerator(type)) {
                        logger.debug("Found new generators for {}", type);
                        return createObject(test, type, position, recursionDepth + 1, generatorRefToExclude, allowNull, canUseFunctionalMocks, canReuseVariables);
                    } else {
                        logger.debug("Found no new generators for {}", type);
                    }
                }
                throw new ConstructionFailedException("Have no generator for " + type + " canUseFunctionalMocks=" + canUseFunctionalMocks + ", canBeMocked: " + FunctionalMockStatement.canBeFunctionalMocked(type));
            }
        } else if (o.isField()) {
            logger.debug("Attempting generating of {} via field of type {}", type, type);
            ret = addField(test, (GenericField) o, position, recursionDepth + 1);
        } else if (o.isMethod()) {
            logger.debug("Attempting generating of " + type + " via method " + (o) + " of type " + type);
            ret = addMethod(test, (GenericMethod) o, position, recursionDepth + 1);
            // TODO: Why are we doing this??
            // if (o.isStatic()) {
            // ret.setType(type);
            // }
            logger.debug("Success in generating type {} using method \"{}\"", type, o);
        } else if (o.isConstructor()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Attempting generating of " + type + " via constructor " + (o) + " of type " + type + ", with constructor type " + o.getOwnerType() + ", at position " + position);
            }
            ret = addConstructor(test, (GenericConstructor) o, type, position, recursionDepth + 1);
        } else {
            logger.debug("No generators found for type {}", type);
            throw new ConstructionFailedException("No generator found for type " + type);
        }
    }
    ret.setDistance(recursionDepth + 1);
    logger.debug("Success in generation of type {} at position {}", type, position);
    return ret;
}
Also used : GenericClass(org.evosuite.utils.generic.GenericClass) PrivateMethodStatement(org.evosuite.testcase.statements.reflection.PrivateMethodStatement) PrivateFieldStatement(org.evosuite.testcase.statements.reflection.PrivateFieldStatement) GenericMethod(org.evosuite.utils.generic.GenericMethod) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 18 with ConstructionFailedException

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

the class LIPS method evolve.

@SuppressWarnings("unchecked")
@Override
protected void evolve() {
    List<T> newGeneration = new ArrayList<T>();
    // Elitism. It is not specified in original paper [1].
    // However, we assume that LIPS uses elitism given the fact the
    // elitism has been shown to positively affect the convergence
    // speed of GAs in various optimisation problems
    Collections.sort(population, new SortByFitness(this.currentTarget, false));
    newGeneration.add((T) population.get(0).clone());
    newGeneration.add((T) population.get(1).clone());
    // new_generation.size() < population_size
    while (newGeneration.size() < Properties.POPULATION) {
        T parent1 = selectionFunction.select(population);
        T parent2 = selectionFunction.select(population);
        T offspring1 = (T) parent1.clone();
        T offspring2 = (T) parent2.clone();
        try {
            if (Randomness.nextDouble() <= Properties.CROSSOVER_RATE) {
                crossoverFunction.crossOver(offspring1, offspring2);
            }
            notifyMutation(offspring1);
            offspring1.mutate();
            newGeneration.add(offspring1);
            notifyMutation(offspring2);
            offspring2.mutate();
            newGeneration.add(offspring2);
            if (offspring1.isChanged()) {
                offspring1.updateAge(currentIteration);
            }
            if (offspring2.isChanged()) {
                offspring2.updateAge(currentIteration);
            }
        } catch (ConstructionFailedException e) {
            logger.info("CrossOver/Mutation failed.");
            continue;
        }
    }
    population.clear();
    population = newGeneration;
    // calculate fitness for all test cases in the current (new) population
    calculateFitness();
}
Also used : ArrayList(java.util.ArrayList) SortByFitness(org.evosuite.ga.comparators.SortByFitness) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 19 with ConstructionFailedException

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

the class ArrayLocalSearch method stripAssignments.

private int stripAssignments(ArrayStatement statement, TestChromosome test, LocalSearchObjective<TestChromosome> objective) {
    int difference = 0;
    ArrayReference arrRef = (ArrayReference) statement.getReturnValue();
    TestFactory factory = TestFactory.getInstance();
    for (int position = test.size() - 1; position > statement.getPosition(); position--) {
        logger.debug("Current delete position: " + position);
        if (test.getTestCase().getStatement(position) instanceof AssignmentStatement) {
            logger.debug("Is assignment statement");
            AssignmentStatement assignment = (AssignmentStatement) test.getTestCase().getStatement(position);
            Statement valueStatement = test.getTestCase().getStatement(assignment.getValue().getStPosition());
            if (assignment.getReturnValue().getAdditionalVariableReference() == arrRef) {
                int currentDelta = 0;
                int differenceDelta = 0;
                logger.debug("Assigns to target array. Checking if we can remove it without worsening fitness");
                backup(test);
                try {
                    factory.deleteStatement(test.getTestCase(), position);
                    if (valueStatement instanceof PrimitiveStatement || valueStatement instanceof NullStatement) {
                        if (!test.getTestCase().hasReferences(valueStatement.getReturnValue())) {
                            if (valueStatement.getPosition() < statement.getPosition())
                                differenceDelta = 1;
                            currentDelta = 1;
                            logger.debug("Deleting primitive statement assigned to this array at " + valueStatement.getPosition());
                            factory.deleteStatement(test.getTestCase(), valueStatement.getPosition());
                        }
                    }
                    if (!objective.hasNotWorsened(test)) {
                        logger.debug("Fitness has decreased, so restoring test");
                        restore(test);
                        currentDelta = 0;
                        differenceDelta = 0;
                    }
                } catch (ConstructionFailedException e) {
                    currentDelta = 0;
                    differenceDelta = 0;
                    restore(test);
                }
                position -= currentDelta;
                difference += differenceDelta;
            }
        }
    }
    return difference;
}
Also used : ArrayReference(org.evosuite.testcase.variable.ArrayReference) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) NullStatement(org.evosuite.testcase.statements.NullStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) TestFactory(org.evosuite.testcase.TestFactory) Statement(org.evosuite.testcase.statements.Statement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) NullStatement(org.evosuite.testcase.statements.NullStatement) ArrayStatement(org.evosuite.testcase.statements.ArrayStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) ConstructionFailedException(org.evosuite.ga.ConstructionFailedException)

Example 20 with ConstructionFailedException

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

the class ReferenceLocalSearch method replace.

/**
 * Replace the call with a completely different call
 *
 * @param test
 * @param statement
 * @return
 */
private boolean replace(TestChromosome test, int statement) {
    logger.debug("Replacing call");
    TestFactory factory = TestFactory.getInstance();
    Statement theStatement = test.getTestCase().getStatement(statement);
    VariableReference var = theStatement.getReturnValue();
    int oldLength = test.size();
    try {
        VariableReference replacement = null;
        if (Randomness.nextDouble() < Properties.NULL_PROBABILITY) {
            NullStatement nullStatement = new NullStatement(test.getTestCase(), var.getType());
            replacement = test.getTestCase().addStatement(nullStatement, statement);
        } else if (!var.isPrimitive()) {
            // Test cluster does not keep track of generators for primitives
            replacement = factory.createObject(test.getTestCase(), var.getType(), statement, 0, null);
        }
        if (replacement != null) {
            int oldStatement = statement + (test.size() - oldLength);
            for (int i = oldStatement + 1; i < test.size(); i++) {
                test.getTestCase().getStatement(i).replace(var, replacement);
            }
            factory.deleteStatement(test.getTestCase(), oldStatement);
            test.setChanged(true);
        }
    } catch (ConstructionFailedException e) {
        if (test.size() < oldLength) {
            restore(test);
        }
        test.setChanged(test.size() != oldLength);
    }
    return false;
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) NullStatement(org.evosuite.testcase.statements.NullStatement) TestFactory(org.evosuite.testcase.TestFactory) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) NullStatement(org.evosuite.testcase.statements.NullStatement) FieldStatement(org.evosuite.testcase.statements.FieldStatement) ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) 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