Search in sources :

Example 6 with PrimitiveStatement

use of org.evosuite.testcase.statements.PrimitiveStatement in project evosuite by EvoSuite.

the class AbstractMOSA method removeUnusedVariables.

/**
 * When a test case is changed via crossover and/or mutation, it can contains some
 * primitive variables that are not used as input (or to store the output) of method calls.
 * Thus, this method removes all these "trash" statements.
 * @param chromosome
 * @return true or false depending on whether "unused variables" are removed
 */
public boolean removeUnusedVariables(T chromosome) {
    int sizeBefore = chromosome.size();
    TestCase t = ((TestChromosome) chromosome).getTestCase();
    List<Integer> to_delete = new ArrayList<Integer>(chromosome.size());
    boolean has_deleted = false;
    int num = 0;
    for (Statement s : t) {
        VariableReference var = s.getReturnValue();
        boolean delete = false;
        delete = delete || s instanceof PrimitiveStatement;
        delete = delete || s instanceof ArrayStatement;
        delete = delete || s instanceof StringPrimitiveStatement;
        if (!t.hasReferences(var) && delete) {
            to_delete.add(num);
            has_deleted = true;
        }
        num++;
    }
    Collections.sort(to_delete, Collections.reverseOrder());
    for (Integer position : to_delete) {
        t.remove(position);
    }
    int sizeAfter = chromosome.size();
    if (has_deleted)
        logger.debug("Removed {} unused statements", (sizeBefore - sizeAfter));
    return has_deleted;
}
Also used : StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) TestCase(org.evosuite.testcase.TestCase) ArrayStatement(org.evosuite.testcase.statements.ArrayStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) ConstructorStatement(org.evosuite.testcase.statements.ConstructorStatement) Statement(org.evosuite.testcase.statements.Statement) MethodStatement(org.evosuite.testcase.statements.MethodStatement) StringPrimitiveStatement(org.evosuite.testcase.statements.StringPrimitiveStatement) ArrayList(java.util.ArrayList) ArrayStatement(org.evosuite.testcase.statements.ArrayStatement) TestChromosome(org.evosuite.testcase.TestChromosome)

Example 7 with PrimitiveStatement

use of org.evosuite.testcase.statements.PrimitiveStatement in project evosuite by EvoSuite.

the class DeprecatedTestSuiteDSE method negateCondition.

/**
 * Generate new constraint and ask solver for solution
 *
 * @param condition
 * @param test
 * @return
 */
// @SuppressWarnings("rawtypes")
// @SuppressWarnings("rawtypes")
@SuppressWarnings({ "unchecked", "rawtypes" })
private TestCase negateCondition(Set<Constraint<?>> reachingConstraints, Constraint<?> localConstraint, TestCase test) {
    List<Constraint<?>> constraints = new LinkedList<Constraint<?>>();
    constraints.addAll(reachingConstraints);
    Constraint<?> targetConstraint = localConstraint.negate();
    constraints.add(targetConstraint);
    if (!targetConstraint.isSolveable()) {
        logger.info("Found unsolvable constraint: " + targetConstraint);
        // Could we treat this as a special case?
        return null;
    }
    int size = constraints.size();
    /*
		 * int counter = 0; for (Constraint cnstr : constraints) { logger.debug(
		 * "Cnstr " + (counter++) + " : " + cnstr + " dist: " +
		 * DistanceEstimator.getDistance(constraints)); }
		 */
    if (size > 0) {
        logger.debug("Calculating cone of influence for " + size + " constraints");
        constraints = reduce(constraints);
        logger.info("Reduced constraints from " + size + " to " + constraints.size());
    // for (Constraint<?> c : constraints) {
    // logger.info(c.toString());
    // }
    }
    nrCurrConstraints = constraints.size();
    nrConstraints += nrCurrConstraints;
    logger.info("Applying local search");
    Solver solver = SolverFactory.getInstance().buildNewSolver();
    DSEStats.getInstance().reportNewConstraints(constraints);
    long startSolvingTime = System.currentTimeMillis();
    SolverCache solverCache = SolverCache.getInstance();
    SolverResult solverResult = solverCache.solve(solver, constraints);
    long estimatedSolvingTime = System.currentTimeMillis() - startSolvingTime;
    DSEStats.getInstance().reportNewSolvingTime(estimatedSolvingTime);
    if (solverResult == null) {
        logger.info("Found no solution");
        /* Timeout, parseException, error, trivialSolution, etc. */
        return null;
    } else if (solverResult.isUNSAT()) {
        logger.info("Found UNSAT solution");
        DSEStats.getInstance().reportNewUNSAT();
        return null;
    } else {
        Map<String, Object> model = solverResult.getModel();
        DSEStats.getInstance().reportNewSAT();
        TestCase newTest = test.clone();
        for (Object key : model.keySet()) {
            Object val = model.get(key);
            if (val != null) {
                logger.info("New value: " + key + ": " + val);
                if (val instanceof Long) {
                    Long value = (Long) val;
                    String name = ((String) key).replace("__SYM", "");
                    // logger.warn("New long value for " + name + " is " +
                    // value);
                    PrimitiveStatement p = getStatement(newTest, name);
                    if (p.getValue().getClass().equals(Character.class))
                        p.setValue((char) value.intValue());
                    else if (p.getValue().getClass().equals(Long.class))
                        p.setValue(value);
                    else if (p.getValue().getClass().equals(Integer.class))
                        p.setValue(value.intValue());
                    else if (p.getValue().getClass().equals(Short.class))
                        p.setValue(value.shortValue());
                    else if (p.getValue().getClass().equals(Boolean.class))
                        p.setValue(value.intValue() > 0);
                    else if (p.getValue().getClass().equals(Byte.class))
                        p.setValue(value.byteValue() > 0);
                    else
                        logger.warn("New value is of an unsupported type: " + p.getValue().getClass() + val);
                } else if (val instanceof String) {
                    String name = ((String) key).replace("__SYM", "");
                    PrimitiveStatement p = getStatement(newTest, name);
                    // val);
                    assert (p != null) : "Could not find variable " + name + " in test: " + newTest.toCode() + " / Orig test: " + test.toCode() + ", seed: " + Randomness.getSeed();
                    if (p.getValue().getClass().equals(Character.class))
                        p.setValue((char) Integer.parseInt(val.toString()));
                    else
                        p.setValue(val.toString());
                } else if (val instanceof Double) {
                    Double value = (Double) val;
                    String name = ((String) key).replace("__SYM", "");
                    PrimitiveStatement p = getStatement(newTest, name);
                    // value);
                    assert (p != null) : "Could not find variable " + name + " in test: " + newTest.toCode() + " / Orig test: " + test.toCode() + ", seed: " + Randomness.getSeed();
                    if (p.getValue().getClass().equals(Double.class))
                        p.setValue(value);
                    else if (p.getValue().getClass().equals(Float.class))
                        p.setValue(value.floatValue());
                    else
                        logger.warn("New value is of an unsupported type: " + val);
                } else {
                    logger.debug("New value is of an unsupported type: " + val);
                }
            } else {
                logger.debug("New value is null");
            }
        }
        return newTest;
    }
}
Also used : Solver(org.evosuite.symbolic.solver.Solver) Constraint(org.evosuite.symbolic.expr.Constraint) SolverResult(org.evosuite.symbolic.solver.SolverResult) SolverCache(org.evosuite.symbolic.solver.SolverCache) LinkedList(java.util.LinkedList) Constraint(org.evosuite.symbolic.expr.Constraint) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) TestCase(org.evosuite.testcase.TestCase) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with PrimitiveStatement

use of org.evosuite.testcase.statements.PrimitiveStatement 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 9 with PrimitiveStatement

use of org.evosuite.testcase.statements.PrimitiveStatement in project evosuite by EvoSuite.

the class DSETestGenerator method updateTest.

@SuppressWarnings({ "rawtypes", "unchecked" })
private TestCase updateTest(TestCase test, Map<String, Object> values) {
    TestCase newTest = test.clone();
    for (Object key : values.keySet()) {
        Object val = values.get(key);
        if (val != null) {
            logger.info("New value: " + key + ": " + val);
            if (val instanceof Long) {
                Long value = (Long) val;
                String name = ((String) key).replace("__SYM", "");
                // logger.warn("New long value for " + name + " is " +
                // value);
                PrimitiveStatement p = getStatement(newTest, name);
                if (p.getValue().getClass().equals(Character.class))
                    p.setValue((char) value.intValue());
                else if (p.getValue().getClass().equals(Long.class))
                    p.setValue(value);
                else if (p.getValue().getClass().equals(Integer.class))
                    p.setValue(value.intValue());
                else if (p.getValue().getClass().equals(Short.class))
                    p.setValue(value.shortValue());
                else if (p.getValue().getClass().equals(Boolean.class))
                    p.setValue(value.intValue() > 0);
                else if (p.getValue().getClass().equals(Byte.class))
                    p.setValue(value.byteValue() > 0);
                else
                    logger.warn("New value is of an unsupported type: " + p.getValue().getClass() + val);
            } else if (val instanceof String) {
                String name = ((String) key).replace("__SYM", "");
                PrimitiveStatement p = getStatement(newTest, name);
                // val);
                assert (p != null) : "Could not find variable " + name + " in test: " + newTest.toCode() + " / Orig test: " + test.toCode() + ", seed: " + Randomness.getSeed();
                if (p.getValue().getClass().equals(Character.class))
                    p.setValue((char) Integer.parseInt(val.toString()));
                else
                    p.setValue(val.toString());
            } else if (val instanceof Double) {
                Double value = (Double) val;
                String name = ((String) key).replace("__SYM", "");
                PrimitiveStatement p = getStatement(newTest, name);
                // value);
                assert (p != null) : "Could not find variable " + name + " in test: " + newTest.toCode() + " / Orig test: " + test.toCode() + ", seed: " + Randomness.getSeed();
                if (p.getValue().getClass().equals(Double.class))
                    p.setValue(value);
                else if (p.getValue().getClass().equals(Float.class))
                    p.setValue(value.floatValue());
                else
                    logger.warn("New value is of an unsupported type: " + val);
            } else {
                logger.debug("New value is of an unsupported type: " + val);
            }
        } else {
            logger.debug("New value is null");
        }
    }
    return newTest;
}
Also used : PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) TestCase(org.evosuite.testcase.TestCase) DefaultTestCase(org.evosuite.testcase.DefaultTestCase)

Example 10 with PrimitiveStatement

use of org.evosuite.testcase.statements.PrimitiveStatement in project evosuite by EvoSuite.

the class EvoTestCaseCodeGenerator method createUnobservedInitStmt.

@SuppressWarnings({ "rawtypes" })
@Override
public void createUnobservedInitStmt(CaptureLog log, int logRecNo) {
    // NOTE: PLAIN INIT: has always one non-null param
    // TODO: use primitives
    final int oid = log.objectIds.get(logRecNo);
    try {
        final Object value = log.params.get(logRecNo)[0];
        final PrimitiveStatement stringRep = new ImmutableStringPrimitiveStatement(testCase, (String) value);
        final VariableReference stringRepRef = testCase.addStatement(stringRep);
        final MethodStatement m = new MethodStatement(testCase, new GenericMethod(EvoSuiteXStream.class.getMethod("fromString", new Class<?>[] { String.class }), EvoSuiteXStream.class), null, Arrays.asList(stringRepRef));
        this.oidToVarRefMap.put(oid, testCase.addStatement(m));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : MethodStatement(org.evosuite.testcase.statements.MethodStatement) ClassPrimitiveStatement(org.evosuite.testcase.statements.ClassPrimitiveStatement) PrimitiveStatement(org.evosuite.testcase.statements.PrimitiveStatement) ImmutableStringPrimitiveStatement(org.evosuite.testcase.statements.ImmutableStringPrimitiveStatement) VariableReference(org.evosuite.testcase.variable.VariableReference) ImmutableStringPrimitiveStatement(org.evosuite.testcase.statements.ImmutableStringPrimitiveStatement) GenericMethod(org.evosuite.utils.generic.GenericMethod)

Aggregations

PrimitiveStatement (org.evosuite.testcase.statements.PrimitiveStatement)16 VariableReference (org.evosuite.testcase.variable.VariableReference)11 Statement (org.evosuite.testcase.statements.Statement)6 MethodStatement (org.evosuite.testcase.statements.MethodStatement)5 CodeUnderTestException (org.evosuite.testcase.execution.CodeUnderTestException)4 TestCase (org.evosuite.testcase.TestCase)3 ArrayStatement (org.evosuite.testcase.statements.ArrayStatement)3 AssignmentStatement (org.evosuite.testcase.statements.AssignmentStatement)3 ConstructorStatement (org.evosuite.testcase.statements.ConstructorStatement)3 NullReference (org.evosuite.testcase.variable.NullReference)3 ArrayList (java.util.ArrayList)2 LinkedHashSet (java.util.LinkedHashSet)2 ClassPrimitiveStatement (org.evosuite.testcase.statements.ClassPrimitiveStatement)2 ImmutableStringPrimitiveStatement (org.evosuite.testcase.statements.ImmutableStringPrimitiveStatement)2 URL (java.net.URL)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 TimeoutException (java.util.concurrent.TimeoutException)1