Search in sources :

Example 16 with CodeUnderTestException

use of org.evosuite.testcase.execution.CodeUnderTestException in project evosuite by EvoSuite.

the class FixedNumRandomTestStrategy method generateTests.

@Override
public TestSuiteChromosome generateTests() {
    LoggingUtils.getEvoLogger().info("* Generating fixed number of random tests");
    RandomLengthTestFactory factory = new org.evosuite.testcase.factories.RandomLengthTestFactory();
    TestSuiteChromosome suite = new TestSuiteChromosome();
    if (!canGenerateTestsForSUT()) {
        LoggingUtils.getEvoLogger().info("* Found no testable methods in the target class " + Properties.TARGET_CLASS);
        ClientServices.getInstance().getClientNode().trackOutputVariable(RuntimeVariable.Total_Goals, 0);
        return suite;
    }
    for (int i = 0; i < Properties.NUM_RANDOM_TESTS; i++) {
        logger.info("Current test: " + i + "/" + Properties.NUM_RANDOM_TESTS);
        TestChromosome test = factory.getChromosome();
        ExecutionResult result = TestCaseExecutor.runTest(test.getTestCase());
        Integer pos = result.getFirstPositionOfThrownException();
        if (pos != null) {
            if (result.getExceptionThrownAtPosition(pos) instanceof CodeUnderTestException || result.getExceptionThrownAtPosition(pos) instanceof UncompilableCodeException || result.getExceptionThrownAtPosition(pos) instanceof TestCaseExecutor.TimeoutExceeded) {
                // Filter invalid tests
                continue;
            } else {
                // Remove anything that follows an exception
                test.getTestCase().chop(pos + 1);
            }
            test.setChanged(true);
        } else {
            test.setLastExecutionResult(result);
        }
        suite.addTest(test);
    }
    // Search is finished, send statistics
    sendExecutionStatistics();
    return suite;
}
Also used : TestCaseExecutor(org.evosuite.testcase.execution.TestCaseExecutor) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) RandomLengthTestFactory(org.evosuite.testcase.factories.RandomLengthTestFactory) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) TestChromosome(org.evosuite.testcase.TestChromosome) UncompilableCodeException(org.evosuite.testcase.execution.UncompilableCodeException)

Example 17 with CodeUnderTestException

use of org.evosuite.testcase.execution.CodeUnderTestException in project evosuite by EvoSuite.

the class ConstantInliner method afterStatement.

/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.evosuite.testcase.ExecutionObserver#statement(org.evosuite.testcase.
	 * StatementInterface, org.evosuite.testcase.Scope, java.lang.Throwable)
	 */
/**
 * {@inheritDoc}
 */
@Override
public void afterStatement(Statement statement, Scope scope, Throwable exception) {
    try {
        for (VariableReference var : statement.getVariableReferences()) {
            if (var.equals(statement.getReturnValue()) || var.equals(statement.getReturnValue().getAdditionalVariableReference()))
                continue;
            Object object = var.getObject(scope);
            if (var.isPrimitive()) {
                ConstantValue value = new ConstantValue(test, var.getGenericClass());
                value.setValue(object);
                // logger.info("Statement before inlining: " +
                // statement.getCode());
                statement.replace(var, value);
            // logger.info("Statement after inlining: " +
            // statement.getCode());
            } else if (var.isString() && object != null) {
                ConstantValue value = new ConstantValue(test, var.getGenericClass());
                try {
                    String val = StringEscapeUtils.unescapeJava(new String(object.toString()));
                    if (val.length() < Properties.MAX_STRING) {
                        value.setValue(val);
                        statement.replace(var, value);
                    }
                } catch (IllegalArgumentException e) {
                    // Exceptions may happen if strings are not valid
                    // unicode
                    logger.info("Cannot escape invalid string: " + object);
                }
            // logger.info("Statement after inlining: " +
            // statement.getCode());
            } else if (var.isArrayIndex()) {
                // then replace the array index with that object
                for (VariableReference otherVar : scope.getElements(var.getType())) {
                    Object otherObject = otherVar.getObject(scope);
                    if (otherObject == object && !otherVar.isArrayIndex() && otherVar.getStPosition() < statement.getPosition()) {
                        statement.replace(var, otherVar);
                        break;
                    }
                }
            } else {
                // the assertion for now
                if (object == null) {
                    if (statement instanceof MethodStatement) {
                        MethodStatement ms = (MethodStatement) statement;
                        if (var.equals(ms.getCallee())) {
                            // Don't put null in callee's, the compiler will not accept it
                            continue;
                        }
                    } else if (statement instanceof FieldStatement) {
                        FieldStatement fs = (FieldStatement) statement;
                        if (var.equals(fs.getSource())) {
                            // Don't put null in source, the compiler will not accept it
                            continue;
                        }
                    }
                    ConstantValue value = new ConstantValue(test, var.getGenericClass());
                    value.setValue(null);
                    // logger.info("Statement before inlining: " +
                    // statement.getCode());
                    statement.replace(var, value);
                // logger.info("Statement after inlining: " +
                // statement.getCode());
                }
            }
        }
    } catch (CodeUnderTestException e) {
        logger.warn("Not inlining test: " + e.getCause());
    // throw new AssertionError("This case isn't handled yet: " +
    // e.getCause()
    // + ", " + Arrays.asList(e.getStackTrace()));
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) FieldStatement(org.evosuite.testcase.statements.FieldStatement) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) ConstantValue(org.evosuite.testcase.variable.ConstantValue)

Example 18 with CodeUnderTestException

use of org.evosuite.testcase.execution.CodeUnderTestException 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 19 with CodeUnderTestException

use of org.evosuite.testcase.execution.CodeUnderTestException in project evosuite by EvoSuite.

the class PrimitiveExpression method execute.

/**
 * {@inheritDoc}
 */
@Override
public Throwable execute(Scope scope, PrintStream out) throws IllegalArgumentException {
    try {
        Object o1 = leftOperand.getObject(scope);
        Object o2 = rightOperand.getObject(scope);
        switch(operator) {
            case EQUALS:
                if (Objects.equals(o1, o2)) {
                    scope.setObject(retval, true);
                } else {
                    scope.setObject(retval, false);
                }
                break;
            default:
                throw new UnsupportedOperationException("Method execute not implemented!");
        }
    } catch (CodeUnderTestException e) {
        return e;
    }
    return null;
}
Also used : GenericAccessibleObject(org.evosuite.utils.generic.GenericAccessibleObject) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException)

Example 20 with CodeUnderTestException

use of org.evosuite.testcase.execution.CodeUnderTestException in project evosuite by EvoSuite.

the class ComparisonTraceObserver method visit.

/* (non-Javadoc)
	 * @see org.evosuite.assertion.AssertionTraceObserver#visit(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope, org.evosuite.testcase.VariableReference)
	 */
/**
 * {@inheritDoc}
 */
@Override
protected void visit(Statement statement, Scope scope, VariableReference var) {
    try {
        Object object = var.getObject(scope);
        if (object == null)
            return;
        if (statement instanceof AssignmentStatement)
            return;
        if (statement instanceof PrimitiveStatement<?>)
            return;
        ComparisonTraceEntry entry = new ComparisonTraceEntry(var);
        int position = statement.getPosition();
        for (VariableReference other : scope.getElements(var.getType())) {
            Object otherObject = other.getObject(scope);
            // TODO: Create a matrix of object comparisons?
            if (otherObject == null)
                // TODO: Don't do this?
                continue;
            if (object == otherObject)
                // Don't compare with self?
                continue;
            int otherPos = other.getStPosition();
            if (otherPos >= position)
                // Don't compare with variables that are not defined - may happen with primitives?
                continue;
            Statement otherStatement = currentTest.getStatement(otherPos);
            if (statement instanceof PrimitiveStatement && otherStatement instanceof PrimitiveStatement)
                // Don't compare two primitives
                continue;
            if (otherStatement instanceof MethodStatement) {
                if (((MethodStatement) otherStatement).getMethodName().equals("hashCode"))
                    // No comparison against hashCode, as the hashCode return value will not be in the test
                    continue;
            }
            if (Properties.PURE_EQUALS) {
                String className = object.getClass().getCanonicalName();
                String methodName = "equals";
                String descriptor = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class));
                CheapPurityAnalyzer cheapPurityAnalyzer = CheapPurityAnalyzer.getInstance();
                if (!cheapPurityAnalyzer.isPure(className, methodName, descriptor))
                    // Don't compare using impure equals(Object) methods
                    continue;
            }
            try {
                logger.debug("Comparison of " + var + " with " + other + " is: " + object.equals(otherObject));
                entry.addEntry(other, ComparisonTraceEntry.equals(object, otherObject));
            } catch (Throwable t) {
                logger.debug("Exception during equals: " + t);
            // ignore?
            }
            if (object instanceof Comparable<?>) {
            // TODO
            }
        }
        trace.addEntry(statement.getPosition(), var, entry);
    } catch (CodeUnderTestException e) {
        logger.debug("", e);
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) AssignmentStatement(org.evosuite.testcase.statements.AssignmentStatement)

Aggregations

CodeUnderTestException (org.evosuite.testcase.execution.CodeUnderTestException)33 VariableReference (org.evosuite.testcase.variable.VariableReference)25 ReferenceConstant (org.evosuite.symbolic.expr.ref.ReferenceConstant)16 EvosuiteError (org.evosuite.testcase.execution.EvosuiteError)14 IntegerVariable (org.evosuite.symbolic.expr.bv.IntegerVariable)6 ReferenceExpression (org.evosuite.symbolic.expr.ref.ReferenceExpression)6 MethodStatement (org.evosuite.testcase.statements.MethodStatement)5 Type (org.objectweb.asm.Type)5 StringValue (org.evosuite.symbolic.expr.str.StringValue)4 UncompilableCodeException (org.evosuite.testcase.execution.UncompilableCodeException)4 PrimitiveStatement (org.evosuite.testcase.statements.PrimitiveStatement)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 LinkedHashSet (java.util.LinkedHashSet)3 Expression (org.evosuite.symbolic.expr.Expression)3 IntegerValue (org.evosuite.symbolic.expr.bv.IntegerValue)3 RealValue (org.evosuite.symbolic.expr.fp.RealValue)3 PrimitiveExpression (org.evosuite.testcase.statements.PrimitiveExpression)3 ArrayReference (org.evosuite.testcase.variable.ArrayReference)3 ConstantValue (org.evosuite.testcase.variable.ConstantValue)3 Field (java.lang.reflect.Field)2