Search in sources :

Example 96 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class ParameterLocalSearch method doSearch.

/**
 * Go through parameters of constructor call and apply local search
 *
 * @param test
 * @param statement
 * @param objective
 */
private boolean doSearch(TestChromosome test, ConstructorStatement statement, LocalSearchObjective<TestChromosome> objective) {
    int numParameter = 0;
    boolean hasImproved = false;
    for (VariableReference parameter : statement.getParameterReferences()) {
        // First try null
        statement.replaceParameterReference(new NullReference(test.getTestCase(), parameter.getType()), numParameter);
        // Else try all other values available in the test
        if (!objective.hasImproved(test)) {
            statement.replaceParameterReference(parameter, numParameter);
            boolean done = false;
            List<VariableReference> objects = test.getTestCase().getObjects(parameter.getType(), statement.getPosition());
            objects.remove(parameter);
            for (VariableReference replacement : objects) {
                statement.replaceParameterReference(replacement, numParameter);
                if (objective.hasImproved(test)) {
                    done = true;
                    hasImproved = true;
                    break;
                }
            }
            if (!done)
                statement.replaceParameterReference(parameter, numParameter);
        } else {
            hasImproved = true;
        }
        numParameter++;
    }
    return hasImproved;
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) NullReference(org.evosuite.testcase.variable.NullReference)

Example 97 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class MethodStatement method execute.

/**
 * {@inheritDoc}
 */
@Override
public Throwable execute(final Scope scope, PrintStream out) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException {
    logger.trace("Executing method " + method.getName());
    final Object[] inputs = new Object[parameters.size()];
    Throwable exceptionThrown = null;
    try {
        return super.exceptionHandler(new Executer() {

            @Override
            public void execute() throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, CodeUnderTestException {
                Object callee_object;
                try {
                    java.lang.reflect.Type[] parameterTypes = method.getParameterTypes();
                    for (int i = 0; i < parameters.size(); i++) {
                        VariableReference parameterVar = parameters.get(i);
                        inputs[i] = parameterVar.getObject(scope);
                        if (inputs[i] == null && method.getMethod().getParameterTypes()[i].isPrimitive()) {
                            throw new CodeUnderTestException(new NullPointerException());
                        }
                        if (inputs[i] != null && !TypeUtils.isAssignable(inputs[i].getClass(), parameterTypes[i])) {
                            // !parameterVar.isAssignableTo(parameterTypes[i])) {
                            throw new CodeUnderTestException(new UncompilableCodeException("Cannot assign " + parameterVar.getVariableClass().getName() + " to " + parameterTypes[i]));
                        }
                    }
                    callee_object = method.isStatic() ? null : callee.getObject(scope);
                    if (!method.isStatic() && callee_object == null) {
                        throw new CodeUnderTestException(new NullPointerException());
                    }
                } catch (CodeUnderTestException e) {
                    throw e;
                // throw CodeUnderTestException.throwException(e.getCause());
                } catch (Throwable e) {
                    e.printStackTrace();
                    throw new EvosuiteError(e);
                }
                Object ret = method.getMethod().invoke(callee_object, inputs);
                /*
					 * TODO: Sometimes we do want to cast an Object to String etc...
					 */
                if (method.getReturnType() instanceof Class<?>) {
                    Class<?> returnClass = (Class<?>) method.getReturnType();
                    if (!returnClass.isPrimitive() && ret != null && !returnClass.isAssignableFrom(ret.getClass())) {
                        throw new CodeUnderTestException(new ClassCastException("Cannot assign " + method.getReturnType() + " to variable of type " + retval.getType()));
                    }
                }
                try {
                    retval.setObject(scope, ret);
                } catch (CodeUnderTestException e) {
                    throw e;
                // throw CodeUnderTestException.throwException(e);
                } catch (Throwable e) {
                    throw new EvosuiteError(e);
                }
            }

            @Override
            public Set<Class<? extends Throwable>> throwableExceptions() {
                Set<Class<? extends Throwable>> t = new LinkedHashSet<Class<? extends Throwable>>();
                t.add(InvocationTargetException.class);
                return t;
            }
        });
    } catch (InvocationTargetException e) {
        exceptionThrown = e.getCause();
        logger.debug("Exception thrown in method {}: {}", method.getName(), exceptionThrown);
    }
    return exceptionThrown;
}
Also used : Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) VariableReference(org.evosuite.testcase.variable.VariableReference) EvosuiteError(org.evosuite.testcase.execution.EvosuiteError) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UncompilableCodeException(org.evosuite.testcase.execution.UncompilableCodeException)

Example 98 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class MethodStatement method mutate.

/**
 * Go through parameters of method call and apply local search
 *
 * @param test
 * @param factory
 */
@Override
public boolean mutate(TestCase test, TestFactory factory) {
    if (Randomness.nextDouble() >= Properties.P_CHANGE_PARAMETER)
        return false;
    Constraints constraint = method.getMethod().getAnnotation(Constraints.class);
    if (constraint != null && constraint.notMutable()) {
        return false;
    }
    List<VariableReference> parameters = getParameterReferences();
    boolean changed = false;
    int max = parameters.size();
    if (!isStatic()) {
        max++;
    }
    if (max == 0)
        // Static method with no parameters...
        return false;
    double pParam = 1.0 / max;
    if (!isStatic() && Randomness.nextDouble() < pParam) {
        // replace callee
        VariableReference callee = getCallee();
        List<VariableReference> objects = test.getObjects(callee.getType(), getPosition());
        objects.remove(callee);
        objects = objects.stream().filter(var -> !(test.getStatement(var.getStPosition()) instanceof FunctionalMockStatement)).collect(Collectors.toList());
        if (!objects.isEmpty()) {
            VariableReference replacement = Randomness.choice(objects);
            setCallee(replacement);
            changed = true;
        }
    }
    for (int numParameter = 0; numParameter < parameters.size(); numParameter++) {
        if (Randomness.nextDouble() < pParam) {
            if (mutateParameter(test, numParameter))
                changed = true;
        }
    }
    return changed;
}
Also used : Constraints(org.evosuite.runtime.annotation.Constraints) VariableReference(org.evosuite.testcase.variable.VariableReference)

Example 99 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class PrimitiveExpression method copy.

/**
 * {@inheritDoc}
 */
@Override
public Statement copy(TestCase newTestCase, int offset) {
    VariableReference newRetVal = new VariableReferenceImpl(newTestCase, retval.getType());
    VariableReference newLeftOperand = newTestCase.getStatement(leftOperand.getStPosition()).getReturnValue();
    VariableReference newRightOperand = newTestCase.getStatement(rightOperand.getStPosition()).getReturnValue();
    return new PrimitiveExpression(newTestCase, newRetVal, newLeftOperand, operator, newRightOperand);
// return new PrimitiveExpression(newTestCase, retval, leftOperand, operator, rightOperand);
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) VariableReferenceImpl(org.evosuite.testcase.variable.VariableReferenceImpl)

Example 100 with VariableReference

use of org.evosuite.testcase.variable.VariableReference in project evosuite by EvoSuite.

the class LocalAddressPrimitiveStatement method getTestCode.

@Override
public String getTestCode(String varName) {
    String testCode = "";
    VariableReference retval = getReturnValue();
    Object value = getValue();
    if (value != null) {
        String escapedAddress = StringUtil.getEscapedString(((EvoSuiteAddress) value).getHost());
        int port = ((EvoSuiteAddress) value).getPort();
        testCode += ((Class<?>) retval.getType()).getSimpleName() + " " + varName + " = new " + ((Class<?>) retval.getType()).getSimpleName() + "(\"" + escapedAddress + "\", " + port + ");\n";
    } else {
        testCode += ((Class<?>) retval.getType()).getSimpleName() + " " + varName + " = null;\n";
    }
    return testCode;
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) EvoSuiteAddress(org.evosuite.runtime.testdata.EvoSuiteAddress)

Aggregations

VariableReference (org.evosuite.testcase.variable.VariableReference)472 Method (java.lang.reflect.Method)289 TestCaseBuilder (org.evosuite.symbolic.TestCaseBuilder)143 Test (org.junit.Test)73 GenericMethod (org.evosuite.utils.generic.GenericMethod)68 GenericConstructor (org.evosuite.utils.generic.GenericConstructor)55 MethodStatement (org.evosuite.testcase.statements.MethodStatement)44 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)38 ArrayList (java.util.ArrayList)31 GenericClass (org.evosuite.utils.generic.GenericClass)27 TestCase (org.evosuite.testcase.TestCase)26 CodeUnderTestException (org.evosuite.testcase.execution.CodeUnderTestException)26 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)25 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)19 Type (java.lang.reflect.Type)17 Statement (org.evosuite.testcase.statements.Statement)17 EvosuiteError (org.evosuite.testcase.execution.EvosuiteError)15 ArrayReference (org.evosuite.testcase.variable.ArrayReference)15 VariableReferenceImpl (org.evosuite.testcase.variable.VariableReferenceImpl)15 ReferenceConstant (org.evosuite.symbolic.expr.ref.ReferenceConstant)14