Search in sources :

Example 11 with CheapPurityAnalyzer

use of org.evosuite.assertion.CheapPurityAnalyzer in project evosuite by EvoSuite.

the class SpecialInspectorSystemTest method test.

@Test
public void test() {
    EvoSuite evosuite = new EvoSuite();
    String targetClass = SpecialInspector.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;
    Properties.OUTPUT_VARIABLES = "" + RuntimeVariable.HadUnstableTests;
    String[] command = new String[] { "-generateSuite", "-class", targetClass };
    Object result = evosuite.parseCommandLine(command);
    GeneticAlgorithm<?> ga = getGAFromResult(result);
    TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual();
    System.out.println("EvolvedTestSuite:\n" + best);
    double best_fitness = best.getFitness();
    Assert.assertTrue("Optimal coverage was not achieved ", best_fitness == 0.0);
    CheapPurityAnalyzer purityAnalyzer = CheapPurityAnalyzer.getInstance();
    String descriptor = Type.getMethodDescriptor(Type.BOOLEAN_TYPE);
    boolean greaterthanZeroIsPure = purityAnalyzer.isPure(targetClass, "greaterThanZero", descriptor);
    assertTrue(greaterthanZeroIsPure);
    boolean notPureGreaterthanZeroIsPure = purityAnalyzer.isPure(targetClass, "notPureGreaterThanZero", descriptor);
    assertFalse(notPureGreaterthanZeroIsPure);
    boolean notPureCreationOfObjectIsPure = purityAnalyzer.isPure(targetClass, "notPureCreationOfObject", descriptor);
    assertFalse(notPureCreationOfObjectIsPure);
    boolean pureCreationOfObjectIsPure = purityAnalyzer.isPure(targetClass, "pureCreationOfObject", descriptor);
    assertFalse(pureCreationOfObjectIsPure);
    boolean superPureCall = purityAnalyzer.isPure(targetClass, "superPureCall", descriptor);
    assertTrue(superPureCall);
    boolean notPureGreaterThanZero = purityAnalyzer.isPure(AbstractInspector.class.getCanonicalName(), "notPureGreaterThanZero", descriptor);
    assertFalse(notPureGreaterThanZero);
    boolean superNotPureCall = purityAnalyzer.isPure(targetClass, "superNotPureCall", descriptor);
    assertFalse(superNotPureCall);
    Map<String, OutputVariable<?>> map = DebugStatisticsBackend.getLatestWritten();
    Assert.assertNotNull(map);
    OutputVariable unstable = map.get(RuntimeVariable.HadUnstableTests.toString());
    Assert.assertNotNull(unstable);
    Assert.assertEquals(Boolean.FALSE, unstable.getValue());
}
Also used : CheapPurityAnalyzer(org.evosuite.assertion.CheapPurityAnalyzer) AbstractInspector(com.examples.with.different.packagename.purity.AbstractInspector) EvoSuite(org.evosuite.EvoSuite) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) OutputVariable(org.evosuite.statistics.OutputVariable) Test(org.junit.Test)

Example 12 with CheapPurityAnalyzer

use of org.evosuite.assertion.CheapPurityAnalyzer in project evosuite by EvoSuite.

the class ImpureRandomnessSystemTest method test.

@Test
public void test() {
    EvoSuite evosuite = new EvoSuite();
    String targetClass = ImpureRandomness.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;
    Properties.OUTPUT_VARIABLES = "" + RuntimeVariable.HadUnstableTests;
    String[] command = new String[] { "-generateSuite", "-class", targetClass };
    Object result = evosuite.parseCommandLine(command);
    GeneticAlgorithm<?> ga = getGAFromResult(result);
    TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual();
    System.out.println("EvolvedTestSuite:\n" + best);
    double best_fitness = best.getFitness();
    Assert.assertTrue("Optimal coverage was not achieved ", best_fitness == 0.0);
    CheapPurityAnalyzer purityAnalyzer = CheapPurityAnalyzer.getInstance();
    String intTypeDescriptor = Type.getMethodDescriptor(Type.INT_TYPE);
    boolean randomNextInt = purityAnalyzer.isPure(targetClass, "randomNextInt", intTypeDescriptor);
    assertFalse(randomNextInt);
    boolean secureRandomNextInt = purityAnalyzer.isPure(targetClass, "secureRandomNextInt", intTypeDescriptor);
    assertFalse(secureRandomNextInt);
    String stringTypeDescriptor = Type.getMethodDescriptor(Type.getType(String.class));
    boolean randomUUIDToString = purityAnalyzer.isPure(targetClass, "randomUUIDToString", stringTypeDescriptor);
    assertFalse(randomUUIDToString);
    String doubleTypeDescriptor = Type.getMethodDescriptor(Type.DOUBLE_TYPE);
    boolean randomMath = purityAnalyzer.isPure(targetClass, "randomMath", doubleTypeDescriptor);
    assertFalse(randomMath);
    Map<String, OutputVariable<?>> map = DebugStatisticsBackend.getLatestWritten();
    Assert.assertNotNull(map);
    OutputVariable unstable = map.get(RuntimeVariable.HadUnstableTests.toString());
    Assert.assertNotNull(unstable);
    Assert.assertEquals(Boolean.FALSE, unstable.getValue());
}
Also used : CheapPurityAnalyzer(org.evosuite.assertion.CheapPurityAnalyzer) EvoSuite(org.evosuite.EvoSuite) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) OutputVariable(org.evosuite.statistics.OutputVariable) Test(org.junit.Test)

Example 13 with CheapPurityAnalyzer

use of org.evosuite.assertion.CheapPurityAnalyzer in project evosuite by EvoSuite.

the class PureEqualsSystemTest method test.

@Test
public void test() {
    EvoSuite evosuite = new EvoSuite();
    String targetClass = PureEquals.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;
    Properties.OUTPUT_VARIABLES = "" + RuntimeVariable.HadUnstableTests;
    String[] command = new String[] { "-generateSuite", "-class", targetClass };
    Object result = evosuite.parseCommandLine(command);
    GeneticAlgorithm<?> ga = getGAFromResult(result);
    TestSuiteChromosome best = (TestSuiteChromosome) ga.getBestIndividual();
    System.out.println("EvolvedTestSuite:\n" + best);
    double best_fitness = best.getFitness();
    Assert.assertTrue("Optimal coverage was not achieved ", best_fitness == 0.0);
    CheapPurityAnalyzer purityAnalyzer = CheapPurityAnalyzer.getInstance();
    String descriptor = Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class));
    boolean equals = purityAnalyzer.isPure(targetClass, "equals", descriptor);
    assertTrue(equals);
    Map<String, OutputVariable<?>> map = DebugStatisticsBackend.getLatestWritten();
    Assert.assertNotNull(map);
    OutputVariable unstable = map.get(RuntimeVariable.HadUnstableTests.toString());
    Assert.assertNotNull(unstable);
    Assert.assertEquals(Boolean.FALSE, unstable.getValue());
}
Also used : CheapPurityAnalyzer(org.evosuite.assertion.CheapPurityAnalyzer) EvoSuite(org.evosuite.EvoSuite) TestSuiteChromosome(org.evosuite.testsuite.TestSuiteChromosome) OutputVariable(org.evosuite.statistics.OutputVariable) Test(org.junit.Test)

Example 14 with CheapPurityAnalyzer

use of org.evosuite.assertion.CheapPurityAnalyzer in project evosuite by EvoSuite.

the class BytecodeInstrumentation method transformBytes.

/**
 * <p>
 * transformBytes
 * </p>
 *
 * @param className
 *            a {@link java.lang.String} object.
 * @param reader
 *            a {@link org.objectweb.asm.ClassReader} object.
 * @return an array of byte.
 */
public byte[] transformBytes(ClassLoader classLoader, String className, ClassReader reader) {
    int readFlags = ClassReader.SKIP_FRAMES;
    if (Properties.INSTRUMENTATION_SKIP_DEBUG)
        readFlags |= ClassReader.SKIP_DEBUG;
    String classNameWithDots = ResourceList.getClassNameFromResourcePath(className);
    if (!checkIfCanInstrument(classNameWithDots)) {
        throw new RuntimeException("Should not transform a shared class (" + classNameWithDots + ")! Load by parent (JVM) classloader.");
    }
    TransformationStatistics.reset();
    /*
		 * To use COMPUTE_FRAMES we need to remove JSR commands. Therefore, we
		 * have a JSRInlinerAdapter in NonTargetClassAdapter as well as
		 * CFGAdapter.
		 */
    int asmFlags = ClassWriter.COMPUTE_FRAMES;
    ClassWriter writer = new ComputeClassWriter(asmFlags);
    ClassVisitor cv = writer;
    if (logger.isDebugEnabled()) {
        cv = new TraceClassVisitor(cv, new PrintWriter(System.err));
    }
    if (Properties.RESET_STATIC_FIELDS) {
        cv = new StaticAccessClassAdapter(cv, className);
    }
    if (Properties.PURE_INSPECTORS) {
        CheapPurityAnalyzer purityAnalyzer = CheapPurityAnalyzer.getInstance();
        cv = new PurityAnalysisClassVisitor(cv, className, purityAnalyzer);
    }
    if (Properties.MAX_LOOP_ITERATIONS >= 0) {
        cv = new LoopCounterClassAdapter(cv);
    }
    // Apply transformations to class under test and its owned classes
    if (DependencyAnalysis.shouldAnalyze(classNameWithDots)) {
        logger.debug("Applying target transformation to class " + classNameWithDots);
        if (!Properties.TEST_CARVING && Properties.MAKE_ACCESSIBLE) {
            cv = new AccessibleClassAdapter(cv, className);
        }
        cv = new RemoveFinalClassAdapter(cv);
        cv = new ExecutionPathClassAdapter(cv, className);
        cv = new CFGClassAdapter(classLoader, cv, className);
        if (Properties.EXCEPTION_BRANCHES) {
            cv = new ExceptionTransformationClassAdapter(cv, className);
        }
        if (Properties.ERROR_BRANCHES) {
            cv = new ErrorConditionClassAdapter(cv, className);
        }
    } else {
        logger.debug("Not applying target transformation");
        cv = new NonTargetClassAdapter(cv, className);
        if (Properties.MAKE_ACCESSIBLE) {
            cv = new AccessibleClassAdapter(cv, className);
        }
        // to create the CFG first
        if (Properties.TT && classNameWithDots.startsWith(Properties.CLASS_PREFIX)) {
            cv = new CFGClassAdapter(classLoader, cv, className);
        }
    }
    // Collect constant values for the value pool
    cv = new PrimitiveClassAdapter(cv, className);
    if (Properties.RESET_STATIC_FIELDS) {
        cv = handleStaticReset(className, cv);
    }
    // Mock instrumentation (eg File and TCP).
    if (TestSuiteWriterUtils.needToUseAgent()) {
        cv = new MethodCallReplacementClassAdapter(cv, className);
        /*
			 * If the class is serializable, then doing any change (adding hashCode, static reset, etc)
			 * will change the serialVersionUID if it is not defined in the class.
			 * Hence, if it is not defined, we have to define it to
			 * avoid problems in serialising the class, as reading Master will not do instrumentation.
			 * The serialVersionUID HAS to be the same as the un-instrumented class
			 */
        if (RuntimeSettings.applyUIDTransformation)
            cv = new SerialVersionUIDAdder(cv);
    }
    // Testability Transformations
    if (classNameWithDots.startsWith(Properties.PROJECT_PREFIX) || (!Properties.TARGET_CLASS_PREFIX.isEmpty() && classNameWithDots.startsWith(Properties.TARGET_CLASS_PREFIX)) || shouldTransform(classNameWithDots)) {
        ClassNode cn = new AnnotatedClassNode();
        reader.accept(cn, readFlags);
        logger.info("Starting transformation of " + className);
        if (Properties.STRING_REPLACEMENT) {
            StringTransformation st = new StringTransformation(cn);
            if (isTargetClassName(classNameWithDots) || shouldTransform(classNameWithDots))
                cn = st.transform();
        }
        ComparisonTransformation cmp = new ComparisonTransformation(cn);
        if (isTargetClassName(classNameWithDots) || shouldTransform(classNameWithDots)) {
            cn = cmp.transform();
            ContainerTransformation ct = new ContainerTransformation(cn);
            cn = ct.transform();
        }
        if (shouldTransform(classNameWithDots)) {
            logger.info("Testability Transforming " + className);
            BooleanTestabilityTransformation tt = new BooleanTestabilityTransformation(cn, classLoader);
            try {
                cn = tt.transform();
            } catch (Throwable t) {
                throw new Error(t);
            }
            logger.info("Testability Transformation done: " + className);
        }
        // -----
        cn.accept(cv);
        if (Properties.TEST_CARVING && TransformerUtil.isClassConsideredForInstrumentation(className)) {
            return handleCarving(className, writer);
        }
    } else {
        reader.accept(cv, readFlags);
    }
    return writer.toByteArray();
}
Also used : ClassVisitor(org.objectweb.asm.ClassVisitor) TraceClassVisitor(org.objectweb.asm.util.TraceClassVisitor) SerialVersionUIDAdder(org.objectweb.asm.commons.SerialVersionUIDAdder) BooleanTestabilityTransformation(org.evosuite.instrumentation.testability.BooleanTestabilityTransformation) TraceClassVisitor(org.objectweb.asm.util.TraceClassVisitor) CFGClassAdapter(org.evosuite.graphs.cfg.CFGClassAdapter) ComparisonTransformation(org.evosuite.instrumentation.testability.ComparisonTransformation) PrintWriter(java.io.PrintWriter) ContainerTransformation(org.evosuite.instrumentation.testability.ContainerTransformation) ClassNode(org.objectweb.asm.tree.ClassNode) ErrorConditionClassAdapter(org.evosuite.instrumentation.error.ErrorConditionClassAdapter) StringTransformation(org.evosuite.instrumentation.testability.StringTransformation) ClassWriter(org.objectweb.asm.ClassWriter) ComputeClassWriter(org.evosuite.runtime.util.ComputeClassWriter) CheapPurityAnalyzer(org.evosuite.assertion.CheapPurityAnalyzer) ComputeClassWriter(org.evosuite.runtime.util.ComputeClassWriter) PrimitiveClassAdapter(org.evosuite.seeding.PrimitiveClassAdapter)

Aggregations

CheapPurityAnalyzer (org.evosuite.assertion.CheapPurityAnalyzer)14 EvoSuite (org.evosuite.EvoSuite)13 OutputVariable (org.evosuite.statistics.OutputVariable)13 TestSuiteChromosome (org.evosuite.testsuite.TestSuiteChromosome)13 Test (org.junit.Test)13 AbstractInspector (com.examples.with.different.packagename.purity.AbstractInspector)1 AbstractToStringInspector (com.examples.with.different.packagename.purity.AbstractToStringInspector)1 PrintWriter (java.io.PrintWriter)1 CFGClassAdapter (org.evosuite.graphs.cfg.CFGClassAdapter)1 ErrorConditionClassAdapter (org.evosuite.instrumentation.error.ErrorConditionClassAdapter)1 BooleanTestabilityTransformation (org.evosuite.instrumentation.testability.BooleanTestabilityTransformation)1 ComparisonTransformation (org.evosuite.instrumentation.testability.ComparisonTransformation)1 ContainerTransformation (org.evosuite.instrumentation.testability.ContainerTransformation)1 StringTransformation (org.evosuite.instrumentation.testability.StringTransformation)1 ComputeClassWriter (org.evosuite.runtime.util.ComputeClassWriter)1 PrimitiveClassAdapter (org.evosuite.seeding.PrimitiveClassAdapter)1 ClassVisitor (org.objectweb.asm.ClassVisitor)1 ClassWriter (org.objectweb.asm.ClassWriter)1 SerialVersionUIDAdder (org.objectweb.asm.commons.SerialVersionUIDAdder)1 ClassNode (org.objectweb.asm.tree.ClassNode)1