Search in sources :

Example 1 with Constraint

use of org.evosuite.symbolic.expr.Constraint in project evosuite by EvoSuite.

the class ConcolicExecution method logNrOfConstraints.

private static void logNrOfConstraints(List<BranchCondition> branches) {
    int nrOfConstraints = 0;
    ExpressionExecutor exprExecutor = new ExpressionExecutor();
    for (BranchCondition branchCondition : branches) {
        for (Constraint<?> supporting_constraint : branchCondition.getSupportingConstraints()) {
            supporting_constraint.getLeftOperand().accept(exprExecutor, null);
            supporting_constraint.getRightOperand().accept(exprExecutor, null);
            nrOfConstraints++;
        }
        Constraint<?> constraint = branchCondition.getConstraint();
        constraint.getLeftOperand().accept(exprExecutor, null);
        constraint.getRightOperand().accept(exprExecutor, null);
        nrOfConstraints++;
    }
    logger.debug("nrOfConstraints=" + nrOfConstraints);
}
Also used : ExpressionExecutor(org.evosuite.symbolic.expr.ExpressionExecutor) Constraint(org.evosuite.symbolic.expr.Constraint)

Example 2 with Constraint

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

use of org.evosuite.symbolic.expr.Constraint in project evosuite by EvoSuite.

the class ConstraintVerifier method canBeInsertedRegardlessOfPosition.

private static boolean canBeInsertedRegardlessOfPosition(GenericAccessibleObject<?> obj, TestCase tc) {
    Constraints constraints = obj.getAccessibleObject().getAnnotation(Constraints.class);
    if (constraints == null) {
        return true;
    }
    if (constraints.noDirectInsertion()) {
        return false;
    }
    Class<?> declaringClass = obj.getDeclaringClass();
    String declaringClassName = declaringClass.getCanonicalName();
    String name = obj.getName();
    // check atMostOnce
    if (constraints.atMostOnce()) {
        int counter = ConstraintHelper.countNumberOfMethodCalls(tc, declaringClass, name);
        if (counter == 1) {
            // cannot insert it again
            return false;
        } else if (counter > 1) {
            throw new RuntimeException("Violated 'atMostOnce' constraint for " + obj.getName());
        }
    }
    // excludeOthers
    List<String[]> othersExcluded = ConstraintHelper.getExcludedMethods(tc);
    if (othersExcluded != null && othersExcluded.size() > 0) {
        for (String[] pair : othersExcluded) {
            if (pair[0].equals(declaringClassName) && pair[1].equals(name)) {
                // this method/constructor cannot be added
                return false;
            }
        }
    }
    // dependOnProperties
    String[] properties = constraints.dependOnProperties();
    if (properties != null && properties.length > 0) {
        for (String property : properties) {
            if (!tc.getAccessedEnvironment().hasProperty(property)) {
                return false;
            }
        }
    }
    return true;
}
Also used : Constraint(org.evosuite.symbolic.expr.Constraint)

Example 4 with Constraint

use of org.evosuite.symbolic.expr.Constraint in project evosuite by EvoSuite.

the class TestZ3Str2HardConstraints method test0.

@Test
public void test0() throws SecurityException, NoSuchMethodException, SolverTimeoutException {
    Z3Str2Solver solver = new Z3Str2Solver();
    DefaultTestCase tc = buildTestCase0();
    Collection<Constraint<?>> constraints = DefaultTestCaseConcolicExecutor.execute(tc);
    assertTrue(!constraints.isEmpty());
    Map<String, Object> solution = solve(solver, constraints);
    assertNotNull(solution);
    Long int0 = (Long) solution.get("var0");
    assertEquals(13075, int0.intValue());
}
Also used : Constraint(org.evosuite.symbolic.expr.Constraint) DefaultTestCase(org.evosuite.testcase.DefaultTestCase) Test(org.junit.Test)

Example 5 with Constraint

use of org.evosuite.symbolic.expr.Constraint in project evosuite by EvoSuite.

the class Z3Str2Solver method solve.

@Override
public SolverResult solve(Collection<Constraint<?>> constraints) throws SolverTimeoutException, IOException, SolverParseException, SolverEmptyQueryException, SolverErrorException {
    SmtCheckSatQuery smtCheckSatQuery = buildSmtQuerty(constraints);
    if (smtCheckSatQuery.getConstantDeclarations().isEmpty()) {
        logger.debug("Z3-str2 input has no variables");
        throw new SolverEmptyQueryException("Z3-str2 input has no variables");
    }
    if (smtCheckSatQuery.getAssertions().isEmpty()) {
        Map<String, Object> emptySolution = new HashMap<String, Object>();
        SolverResult emptySAT = SolverResult.newSAT(emptySolution);
        return emptySAT;
    }
    Z3Str2QueryPrinter printer = new Z3Str2QueryPrinter();
    String smtQueryStr = printer.print(smtCheckSatQuery);
    logger.debug("Z3-str2 input:");
    logger.debug(smtQueryStr);
    int timeout = (int) Properties.DSE_CONSTRAINT_SOLVER_TIMEOUT_MILLIS;
    File tempDir = createNewTmpDir();
    String z3TempFileName = tempDir.getAbsolutePath() + File.separatorChar + EVOSUITE_Z3_STR_FILENAME;
    if (Properties.Z3_STR2_PATH == null) {
        String errMsg = "Property Z3_STR_PATH should be setted in order to use the Z3StrSolver!";
        logger.error(errMsg);
        throw new IllegalStateException(errMsg);
    }
    try {
        FileIOUtils.writeFile(smtQueryStr, z3TempFileName);
        String z3Cmd = Properties.Z3_STR2_PATH + " -f " + z3TempFileName;
        ByteArrayOutputStream stdout = new ByteArrayOutputStream();
        launchNewProcess(z3Cmd, smtQueryStr, timeout, stdout);
        String z3str2ResultStr = stdout.toString("UTF-8");
        Z3Str2ResultParser parser = new Z3Str2ResultParser();
        Set<Variable<?>> variables = getVariables(constraints);
        Map<String, Object> initialValues = getConcreteValues(variables);
        SolverResult solverResult;
        if (addMissingVariables()) {
            solverResult = parser.parse(z3str2ResultStr, initialValues);
        } else {
            solverResult = parser.parse(z3str2ResultStr);
        }
        if (solverResult.isSAT()) {
            // check if solution is correct, otherwise return UNSAT
            boolean check = checkSAT(constraints, solverResult);
            if (!check) {
                logger.debug("Z3-str2 solution does not solve the constraint system!");
                SolverResult unsatResult = SolverResult.newUNSAT();
                return unsatResult;
            }
        }
        return solverResult;
    } catch (UnsupportedEncodingException e) {
        throw new EvosuiteError("UTF-8 should not cause this exception!");
    } finally {
        File tempFile = new File(z3TempFileName);
        if (tempFile.exists()) {
            tempFile.delete();
        }
    }
}
Also used : Variable(org.evosuite.symbolic.expr.Variable) SmtIntVariable(org.evosuite.symbolic.solver.smt.SmtIntVariable) SmtRealVariable(org.evosuite.symbolic.solver.smt.SmtRealVariable) SmtVariable(org.evosuite.symbolic.solver.smt.SmtVariable) SmtStringVariable(org.evosuite.symbolic.solver.smt.SmtStringVariable) EvosuiteError(org.evosuite.testcase.execution.EvosuiteError) HashMap(java.util.HashMap) SolverResult(org.evosuite.symbolic.solver.SolverResult) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Constraint(org.evosuite.symbolic.expr.Constraint) SolverEmptyQueryException(org.evosuite.symbolic.solver.SolverEmptyQueryException) SmtCheckSatQuery(org.evosuite.symbolic.solver.smt.SmtCheckSatQuery) File(java.io.File)

Aggregations

Constraint (org.evosuite.symbolic.expr.Constraint)210 DefaultTestCase (org.evosuite.testcase.DefaultTestCase)101 IntegerConstraint (org.evosuite.symbolic.expr.IntegerConstraint)83 Test (org.junit.Test)81 EvoSuiteSolver (org.evosuite.symbolic.solver.avm.EvoSuiteSolver)76 SolverTimeoutException (org.evosuite.symbolic.solver.SolverTimeoutException)75 ArrayList (java.util.ArrayList)68 IntegerConstant (org.evosuite.symbolic.expr.bv.IntegerConstant)42 SolverResult (org.evosuite.symbolic.solver.SolverResult)36 StringVariable (org.evosuite.symbolic.expr.str.StringVariable)34 StringConstraint (org.evosuite.symbolic.expr.StringConstraint)33 TestCaseStringAppendString (com.examples.with.different.packagename.solver.TestCaseStringAppendString)28 TestCaseStringIndexOfString (com.examples.with.different.packagename.solver.TestCaseStringIndexOfString)28 TestCaseStringLastIndexOfString (com.examples.with.different.packagename.solver.TestCaseStringLastIndexOfString)28 RealConstraint (org.evosuite.symbolic.expr.RealConstraint)26 IntegerVariable (org.evosuite.symbolic.expr.bv.IntegerVariable)26 RealVariable (org.evosuite.symbolic.expr.fp.RealVariable)23 StringConstant (org.evosuite.symbolic.expr.str.StringConstant)22 StringBinaryComparison (org.evosuite.symbolic.expr.bv.StringBinaryComparison)17 RealConstant (org.evosuite.symbolic.expr.fp.RealConstant)16