Search in sources :

Example 31 with CodeUnderTestException

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

the class TestSuiteWriter method getImports.

// -----------------------------------------------------------
// --------------   code generation methods ------------------
// -----------------------------------------------------------
/**
 * Determine packages that need to be imported in the JUnit file
 *
 * @param results a {@link java.util.List} object.
 * @return a {@link java.lang.String} object.
 */
protected String getImports(List<ExecutionResult> results) {
    StringBuilder builder = new StringBuilder();
    Set<Class<?>> imports = new HashSet<Class<?>>();
    Set<Class<?>> accessedClasses = new HashSet<Class<?>>();
    boolean wasSecurityException = TestSuiteWriterUtils.hasAnySecurityException(results);
    boolean hasException = false;
    for (ExecutionResult result : results) {
        visitor.clearExceptions();
        visitor.setExceptions(result.exposeExceptionMapping());
        result.test.accept(visitor);
        imports.addAll(visitor.getImports());
        accessedClasses.addAll(result.test.getAccessedClasses());
        if (!hasException)
            hasException = !result.noThrownExceptions();
    }
    visitor.clearExceptions();
    if (doesUseMocks(results)) {
        String mockito = Mockito.class.getCanonicalName();
        builder.append("import static " + mockito + ".*;" + NEWLINE);
        // MockitoExtension is now deprecated
        // String extension = MockitoExtension.class.getCanonicalName();
        // builder.append("import static "+extension+".*;"+NEWLINE);
        imports.add(ViolatedAssumptionAnswer.class);
    }
    if (hasException && !Properties.NO_RUNTIME_DEPENDENCY) {
        builder.append("import static " + EvoAssertions.class.getCanonicalName() + ".*;" + NEWLINE);
    }
    if (Properties.RESET_STANDARD_STREAMS) {
        imports.add(PrintStream.class);
        imports.add(DebugGraphics.class);
    }
    if (TestSuiteWriterUtils.needToUseAgent() && !Properties.NO_RUNTIME_DEPENDENCY) {
        imports.add(EvoRunner.class);
        imports.add(EvoRunnerParameters.class);
        imports.add(RunWith.class);
    }
    Set<String> importNames = new HashSet<>();
    for (Class<?> imp : imports) {
        while (imp.isArray()) imp = imp.getComponentType();
        if (imp.isPrimitive())
            continue;
        if (imp.getName().startsWith("java.lang")) {
            String name = imp.getName().replace("java.lang.", "");
            if (!name.contains("."))
                continue;
        }
        if (!imp.getName().contains("."))
            continue;
        // TODO: Check for anonymous type?
        if (imp.getName().contains("$"))
            importNames.add(imp.getName().replace("$", "."));
        else
            importNames.add(imp.getName());
    }
    for (Class<?> klass : EnvironmentDataList.getListOfClasses()) {
        // TODO: not paramount, but best if could check if actually used in the test suite
        if (accessedClasses.contains(klass))
            importNames.add(klass.getCanonicalName());
    }
    if (wasSecurityException) {
        // Add import info for EvoSuite classes used in the generated test suite
        importNames.add(java.util.concurrent.ExecutorService.class.getCanonicalName());
        importNames.add(java.util.concurrent.Executors.class.getCanonicalName());
        importNames.add(java.util.concurrent.Future.class.getCanonicalName());
        importNames.add(java.util.concurrent.TimeUnit.class.getCanonicalName());
    }
    if (!Properties.TEST_SCAFFOLDING && !Properties.NO_RUNTIME_DEPENDENCY) {
        importNames.addAll(Scaffolding.getScaffoldingImports(wasSecurityException, results));
    }
    // If a CodeUnderTestException happens, the test will be chopped before that exception
    // but it would still be in the imports
    importNames.remove(CodeUnderTestException.class.getCanonicalName());
    List<String> importsSorted = new ArrayList<>(importNames);
    Collections.sort(importsSorted);
    for (String imp : importsSorted) {
        builder.append("import ");
        builder.append(imp);
        builder.append(";");
        builder.append(NEWLINE);
    }
    builder.append(NEWLINE);
    return builder.toString();
}
Also used : ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException) java.util(java.util)

Example 32 with CodeUnderTestException

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

the class SameTraceObserver 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) {
    // TODO: Only MethodStatement?
    if (statement.isAssignmentStatement())
        return;
    if (statement instanceof PrimitiveStatement<?>)
        return;
    if (statement instanceof ArrayStatement)
        return;
    if (statement instanceof ConstructorStatement)
        return;
    try {
        Object object = var.getObject(scope);
        if (object == null)
            return;
        if (var.isPrimitive())
            return;
        if (var.isString() && Properties.INLINE)
            // After inlining the value of assertions would be different
            return;
        SameTraceEntry entry = new SameTraceEntry(var);
        for (VariableReference other : scope.getElements(var.getType())) {
            if (other == var)
                continue;
            if (other.isPrimitive())
                continue;
            if (other.isWrapperType())
                // Issues with inlining resulting in unstable assertions
                continue;
            Object otherObject = other.getObject(scope);
            if (otherObject == null)
                continue;
            if (otherObject.getClass() != object.getClass())
                continue;
            try {
                logger.debug("Comparison of {} with {}", var, other);
                entry.addEntry(other, object == otherObject);
            } catch (Throwable t) {
                logger.debug("Exception during equals: " + t);
            // ignore?
            }
        }
        trace.addEntry(statement.getPosition(), var, entry);
    } catch (CodeUnderTestException e) {
        logger.debug("", e);
    }
}
Also used : ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) ArrayStatement(org.evosuite.testcase.statements.ArrayStatement) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException)

Example 33 with CodeUnderTestException

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

the class ConcreteValueObserver method afterStatement.

/* (non-Javadoc)
	 * @see org.evosuite.testcase.ExecutionObserver#afterStatement(org.evosuite.testcase.StatementInterface, org.evosuite.testcase.Scope, java.lang.Throwable)
	 */
@Override
public void afterStatement(Statement statement, Scope scope, Throwable exception) {
    int numStatement = statement.getPosition();
    VariableReference returnValue = statement.getReturnValue();
    if (!returnValue.isPrimitive()) {
        // Only interested in primitive values
        return;
    }
    TestCase test = super.getCurrentTest();
    if (test.getStatement(returnValue.getStPosition()) instanceof PrimitiveStatement<?>) {
        // Don't need to collect primitive statement values
        return;
    }
    try {
        Object object = statement.getReturnValue().getObject(scope);
        concreteValues.put(numStatement, object);
    } catch (CodeUnderTestException e) {
    // Ignore
    }
}
Also used : VariableReference(org.evosuite.testcase.variable.VariableReference) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) CodeUnderTestException(org.evosuite.testcase.execution.CodeUnderTestException)

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