Search in sources :

Example 1 with Solver

use of org.evosuite.symbolic.solver.Solver in project evosuite by EvoSuite.

the class ConcolicMutation method negateCondition.

/**
 * Generate new constraint and ask solver for solution
 *
 * @param pathCondition
 *
 * @param targetCondition
 *            a {@link org.evosuite.symbolic.BranchCondition} object.
 * @param test
 *            a {@link org.evosuite.testcase.TestCase} object.
 * @return a {@link org.evosuite.testcase.TestCase} object.
 */
// @SuppressWarnings({ "rawtypes", "unchecked" })
public static TestCase negateCondition(List<BranchCondition> pathCondition, BranchCondition targetCondition, TestCase test) {
    List<Constraint<?>> constraints = new LinkedList<Constraint<?>>();
    for (BranchCondition b : pathCondition) {
        constraints.addAll(b.getSupportingConstraints());
        if (b == targetCondition) {
            break;
        } else {
            constraints.add(b.getConstraint());
        }
    }
    final Constraint<?> targetConstraint = targetCondition.getConstraint().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();
    if (size > 0) {
        constraints = reduce(constraints);
    // logger.info("Reduced constraints from " + size + " to " +
    // constraints.size());
    // logger.info("Now solving: " + constraints);
    }
    Solver solver = SolverFactory.getInstance().buildNewSolver();
    SolverCache solverCache = SolverCache.getInstance();
    SolverResult solverResult = solverCache.solve(solver, constraints);
    if (solverResult != null) {
        // logger.info(values.toString());
        TestCase newTest = test.clone();
        Map<String, Object> model = solverResult.getModel();
        for (Object key : model.keySet()) {
            Object val = model.get(key);
            if (val != null) {
                if (val instanceof Long) {
                    Long value = (Long) val;
                    String name = ((String) key).replace("__SYM", "");
                    logger.debug("New value for " + name + " is " + value);
                    PrimitiveStatement<?> p = getStatement(newTest, name);
                    assert (p != null);
                    if (p instanceof BooleanPrimitiveStatement) {
                        BooleanPrimitiveStatement bp = (BooleanPrimitiveStatement) p;
                        bp.setValue(value.intValue() > 0);
                    } else if (p instanceof CharPrimitiveStatement) {
                        CharPrimitiveStatement cp = (CharPrimitiveStatement) p;
                        cp.setValue((char) value.intValue());
                    } else if (p instanceof BytePrimitiveStatement) {
                        BytePrimitiveStatement bp = (BytePrimitiveStatement) p;
                        bp.setValue((byte) value.intValue());
                    } else if (p instanceof ShortPrimitiveStatement) {
                        ShortPrimitiveStatement sp = (ShortPrimitiveStatement) p;
                        sp.setValue((short) value.intValue());
                    } else if (p instanceof LongPrimitiveStatement) {
                        LongPrimitiveStatement lp = (LongPrimitiveStatement) p;
                        lp.setValue(value);
                    } else {
                        assert (p instanceof IntPrimitiveStatement);
                        IntPrimitiveStatement ip = (IntPrimitiveStatement) p;
                        ip.setValue(value.intValue());
                    }
                } else {
                    logger.debug("New value is not long " + val);
                }
            } else {
                logger.debug("New value is null");
            }
        }
        return newTest;
    } else {
        logger.debug("Got null :-(");
        return null;
    }
}
Also used : BytePrimitiveStatement(org.evosuite.testcase.statements.numeric.BytePrimitiveStatement) 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) CharPrimitiveStatement(org.evosuite.testcase.statements.numeric.CharPrimitiveStatement) IntPrimitiveStatement(org.evosuite.testcase.statements.numeric.IntPrimitiveStatement) TestCase(org.evosuite.testcase.TestCase) ShortPrimitiveStatement(org.evosuite.testcase.statements.numeric.ShortPrimitiveStatement) BooleanPrimitiveStatement(org.evosuite.testcase.statements.numeric.BooleanPrimitiveStatement) LongPrimitiveStatement(org.evosuite.testcase.statements.numeric.LongPrimitiveStatement)

Example 2 with Solver

use of org.evosuite.symbolic.solver.Solver 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 3 with Solver

use of org.evosuite.symbolic.solver.Solver in project evosuite by EvoSuite.

the class DSETestGenerator method generateNewTest.

/**
 * Applies DSE to the passed test using as symbolic variables only those
 * that are declared in the set of statement indexes. The objective is used
 * to detect if the DSE has improved the fitness.
 *
 * @param test
 *            the test case to be used as parameterised unit test
 *
 * @param statementIndexes
 *            a set with statement indexes with primitive value declarations
 *            that can be used as symbolic variables. This set must be
 *            non-empty.
 *
 * @param objective
 *            the local search objective to measure fitness improvement.
 */
public TestChromosome generateNewTest(final TestChromosome test, Set<Integer> statementIndexes, LocalSearchObjective<TestChromosome> objective) {
    logger.info("APPLYING DSE EEEEEEEEEEEEEEEEEEEEEEE");
    logger.info(test.getTestCase().toCode());
    logger.info("Starting concolic execution");
    // Backup copy
    // test.getMutationHistory().clear();
    // I am not sure what is the purpose of this
    test.clone();
    DefaultTestCase clone_test_case = (DefaultTestCase) test.getTestCase().clone();
    List<BranchCondition> branchConditions = ConcolicExecution.executeConcolic(clone_test_case);
    final PathCondition collectedPathCondition = new PathCondition(branchConditions);
    logger.info("Done concolic execution");
    if (collectedPathCondition.isEmpty()) {
        return null;
    }
    for (BranchCondition c : collectedPathCondition.getBranchConditions()) {
        logger.info(" -> " + c.getConstraint());
    }
    Set<VariableReference> symbolicVariables = new HashSet<VariableReference>();
    for (Integer position : statementIndexes) {
        final VariableReference variableReference = test.getTestCase().getStatement(position).getReturnValue();
        symbolicVariables.add(variableReference);
    }
    logger.info("Checking {} conditions", collectedPathCondition.size());
    List<Integer> conditionIndexesNotCoveredTwoWays = computeConditionIndexesNotCoveredTwoWays(test, collectedPathCondition);
    // 
    for (int conditionIndex = 0; conditionIndex < collectedPathCondition.size(); conditionIndex++) {
        BranchCondition condition = collectedPathCondition.get(conditionIndex);
        if (LocalSearchBudget.getInstance().isFinished()) {
            logger.debug("Local search budget used up: " + Properties.LOCAL_SEARCH_BUDGET_TYPE);
            break;
        }
        logger.debug("Local search budget not yet used up");
        if (!conditionIndexesNotCoveredTwoWays.contains(conditionIndex)) {
            // skip branches covered two ways
            continue;
        }
        logger.info("Current condition: " + conditionIndex + "/" + collectedPathCondition.size() + ": " + condition.getConstraint());
        // Determine if this a branch condition depending on the target
        // statement
        Constraint<?> currentConstraint = condition.getConstraint();
        if (!isRelevant(currentConstraint, symbolicVariables)) {
            // if(!isRelevant(currentConstraint, test.getTestCase(),
            // statement)) {
            logger.info("Is not relevant for " + symbolicVariables);
            continue;
        }
        logger.info("Is relevant for " + symbolicVariables);
        List<Constraint<?>> query = buildQuery(collectedPathCondition, conditionIndex);
        logger.info("Trying to solve: ");
        for (Constraint<?> c : query) {
            logger.info("  " + c);
        }
        DSEStats.getInstance().reportNewConstraints(query);
        // Get solution
        Solver solver = SolverFactory.getInstance().buildNewSolver();
        long startSolvingTime = System.currentTimeMillis();
        SolverCache solverCache = SolverCache.getInstance();
        SolverResult solverResult = solverCache.solve(solver, query);
        long estimatedSolvingTime = System.currentTimeMillis() - startSolvingTime;
        DSEStats.getInstance().reportNewSolvingTime(estimatedSolvingTime);
        if (solverResult == null) {
            logger.info("Found no result");
        } else if (solverResult.isUNSAT()) {
            logger.info("Found UNSAT result");
            DSEStats.getInstance().reportNewUNSAT();
        } else {
            logger.info("Found SAT result");
            DSEStats.getInstance().reportNewSAT();
            Map<String, Object> model = solverResult.getModel();
            TestCase oldTest = test.getTestCase();
            ExecutionResult oldResult = test.getLastExecutionResult().clone();
            TestCase newTest = updateTest(oldTest, model);
            logger.info("New test: " + newTest.toCode());
            test.setTestCase(newTest);
            // test.clearCachedMutationResults(); // TODO Mutation
            test.clearCachedResults();
            if (objective.hasImproved(test)) {
                DSEStats.getInstance().reportNewTestUseful();
                logger.info("Solution improves fitness, finishing DSE");
                /* new test was created */
                return test;
            } else {
                DSEStats.getInstance().reportNewTestUnuseful();
                test.setTestCase(oldTest);
                // FIXXME: How can this be null?
                if (oldResult != null)
                    test.setLastExecutionResult(oldResult);
            // TODO Mutation
            }
        }
    }
    /* no new test was created */
    return null;
}
Also used : PathCondition(org.evosuite.symbolic.PathCondition) Solver(org.evosuite.symbolic.solver.Solver) VariableReference(org.evosuite.testcase.variable.VariableReference) Constraint(org.evosuite.symbolic.expr.Constraint) SolverResult(org.evosuite.symbolic.solver.SolverResult) ExecutionResult(org.evosuite.testcase.execution.ExecutionResult) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) BranchCondition(org.evosuite.symbolic.BranchCondition) SolverCache(org.evosuite.symbolic.solver.SolverCache) Constraint(org.evosuite.symbolic.expr.Constraint) TestCase(org.evosuite.testcase.TestCase) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

Constraint (org.evosuite.symbolic.expr.Constraint)3 Solver (org.evosuite.symbolic.solver.Solver)3 SolverCache (org.evosuite.symbolic.solver.SolverCache)3 SolverResult (org.evosuite.symbolic.solver.SolverResult)3 TestCase (org.evosuite.testcase.TestCase)3 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 BranchCondition (org.evosuite.symbolic.BranchCondition)1 PathCondition (org.evosuite.symbolic.PathCondition)1 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)1 ExecutionResult (org.evosuite.testcase.execution.ExecutionResult)1 PrimitiveStatement (org.evosuite.testcase.statements.PrimitiveStatement)1 BooleanPrimitiveStatement (org.evosuite.testcase.statements.numeric.BooleanPrimitiveStatement)1 BytePrimitiveStatement (org.evosuite.testcase.statements.numeric.BytePrimitiveStatement)1 CharPrimitiveStatement (org.evosuite.testcase.statements.numeric.CharPrimitiveStatement)1 IntPrimitiveStatement (org.evosuite.testcase.statements.numeric.IntPrimitiveStatement)1 LongPrimitiveStatement (org.evosuite.testcase.statements.numeric.LongPrimitiveStatement)1 ShortPrimitiveStatement (org.evosuite.testcase.statements.numeric.ShortPrimitiveStatement)1