Search in sources :

Example 76 with CtMethod

use of spoon.reflect.declaration.CtMethod in project spoon by INRIA.

the class SetParentTest method testContract.

@Test
public void testContract() throws Throwable {
    Object o = factory.Core().create((Class<? extends CtElement>) toTest.getActualClass());
    CtMethod<?> setter = factory.Type().get(CtElement.class).getMethodsByName("setParent").get(0);
    Object argument = createCompatibleObject(setter.getParameters().get(0).getType());
    if (!(argument instanceof CtElement)) {
        // is a primitive type or a list
        throw new AssertionError("impossible, setParent always takes an element");
    }
    // we create a fresh object
    CtElement receiver = ((CtElement) o).clone();
    if ("CtClass".equals(toTest.getSimpleName()) || "CtInterface".equals(toTest.getSimpleName()) || "CtEnum".equals(toTest.getSimpleName()) || "CtAnnotationType".equals(toTest.getSimpleName()) || "CtPackage".equals(toTest.getSimpleName())) {
        // contract: root package is the parent for those classes
        assertTrue(receiver.getParent() instanceof CtModelImpl.CtRootPackage);
    } else if ("CtModule".equals(toTest.getSimpleName())) {
        // contract: module parent is necessarily the unnamedmodule
        assertTrue(receiver.getParent() instanceof ModuleFactory.CtUnnamedModule);
    } else {
        // contract: there is no parent before
        try {
            receiver.getParent().hashCode();
            fail(receiver.getParent().getClass().getSimpleName());
        } catch (ParentNotInitializedException normal) {
        }
    }
    Method actualMethod = setter.getReference().getActualMethod();
    CtElement argumentClone = ((CtElement) argument).clone();
    actualMethod.invoke(receiver, new Object[] { argument });
    // contract: the parent has not been changed by a call to setParent on an elemnt
    assertTrue(argument.equals(argumentClone));
    assertFalse(argument == argumentClone);
}
Also used : ParentNotInitializedException(spoon.reflect.declaration.ParentNotInitializedException) CtElement(spoon.reflect.declaration.CtElement) ParentContractTest.createCompatibleObject(spoon.test.parent.ParentContractTest.createCompatibleObject) Method(java.lang.reflect.Method) CtMethod(spoon.reflect.declaration.CtMethod) CtModelImpl(spoon.reflect.CtModelImpl) Test(org.junit.Test)

Example 77 with CtMethod

use of spoon.reflect.declaration.CtMethod in project spoon by INRIA.

the class CtRenameLocalVariableRefactoringTest method getParentMethodName.

private String getParentMethodName(CtElement ele) {
    CtMethod parentMethod = ele.getParent(CtMethod.class);
    CtMethod m;
    while (parentMethod != null && (m = parentMethod.getParent(CtMethod.class)) != null) {
        parentMethod = m;
    }
    if (parentMethod != null) {
        return parentMethod.getParent(CtType.class).getSimpleName() + "#" + parentMethod.getSimpleName();
    } else {
        return ele.getParent(CtType.class).getSimpleName() + "#annonymous block";
    }
}
Also used : CtType(spoon.reflect.declaration.CtType) CtMethod(spoon.reflect.declaration.CtMethod)

Example 78 with CtMethod

use of spoon.reflect.declaration.CtMethod in project spoon by INRIA.

the class PositionTest method testPositionMethod.

@Test
public void testPositionMethod() throws Exception {
    final Factory build = build(FooMethod.class);
    final CtClass<FooMethod> foo = build.Class().get(FooMethod.class);
    String classContent = getClassContent(foo);
    CtMethod<?> method1 = foo.getMethodsByName("m").get(0);
    BodyHolderSourcePosition position1 = (BodyHolderSourcePosition) method1.getPosition();
    assertEquals(5, position1.getLine());
    assertEquals(7, position1.getEndLine());
    assertEquals(69, position1.getSourceStart());
    assertEquals(114, position1.getSourceEnd());
    assertEquals("public static void m(int parm1) {\n" + "\t\treturn;\n" + "\t}", contentAtPosition(classContent, position1));
    assertEquals("m", contentAtPosition(classContent, position1.getNameStart(), position1.getNameEnd()));
    assertEquals("public static", contentAtPosition(classContent, position1.getModifierSourceStart(), position1.getModifierSourceEnd()));
    // contract: body contains starting and ending brackets {}
    assertEquals("{\n" + "\t\treturn;\n" + "\t}", contentAtPosition(classContent, position1.getBodyStart(), position1.getBodyEnd()));
    DeclarationSourcePosition positionParam1 = (DeclarationSourcePosition) method1.getParameters().get(0).getPosition();
    assertEquals(5, positionParam1.getLine());
    assertEquals(5, positionParam1.getEndLine());
    assertEquals(90, positionParam1.getSourceStart());
    assertEquals(98, positionParam1.getSourceEnd());
    assertEquals("int parm1", contentAtPosition(classContent, positionParam1));
    assertEquals("parm1", contentAtPosition(classContent, positionParam1.getNameStart(), positionParam1.getNameEnd()));
    assertEquals("", contentAtPosition(classContent, positionParam1.getModifierSourceStart(), positionParam1.getModifierSourceEnd()));
    CtMethod method2 = foo.getMethodsByName("mWithDoc").get(0);
    BodyHolderSourcePosition position2 = (BodyHolderSourcePosition) method2.getPosition();
    assertEquals(13, position2.getLine());
    assertEquals(15, position2.getEndLine());
    assertEquals("/**\n" + "\t * Mathod with javadoc\n" + "\t * @param parm1 the parameter\n" + "\t */\n" + "\tint mWithDoc(int parm1) {\n" + "\t\treturn parm1;\n" + "\t}", contentAtPosition(classContent, position2));
    assertEquals("mWithDoc", contentAtPosition(classContent, position2.getNameStart(), position2.getNameEnd()));
    assertEquals("", contentAtPosition(classContent, position2.getModifierSourceStart(), position2.getModifierSourceEnd()));
    CtConstructor<FooMethod> constructor = foo.getConstructor(build.Type().integerPrimitiveType());
    SourcePosition position3 = constructor.getPosition();
    contentAtPosition(classContent, position3);
    CtMethod mWithLine = foo.getMethod("mWithLine", build.Type().integerPrimitiveType());
    SourcePosition position4 = mWithLine.getPosition();
    contentAtPosition(classContent, position4);
}
Also used : FooMethod(spoon.test.position.testclasses.FooMethod) BodyHolderSourcePosition(spoon.reflect.cu.position.BodyHolderSourcePosition) DeclarationSourcePosition(spoon.reflect.cu.position.DeclarationSourcePosition) BodyHolderSourcePosition(spoon.reflect.cu.position.BodyHolderSourcePosition) SourcePosition(spoon.reflect.cu.SourcePosition) Factory(spoon.reflect.factory.Factory) CtMethod(spoon.reflect.declaration.CtMethod) DeclarationSourcePosition(spoon.reflect.cu.position.DeclarationSourcePosition) Test(org.junit.Test)

Example 79 with CtMethod

use of spoon.reflect.declaration.CtMethod in project dspot by STAMP-project.

the class MethodsAssertGenerator method buildTestWithAssert.

/**
 * Adds new assertions to a test from observation points.
 *
 * @param test Test method
 * @param observations Observation points of the test suite
 * @return Test with new assertions
 */
@SuppressWarnings("unchecked")
private CtMethod<?> buildTestWithAssert(CtMethod test, Map<String, Observation> observations) {
    CtMethod testWithAssert = AmplificationHelper.cloneTestMethodForAmp(test, "");
    int numberOfAddedAssertion = 0;
    List<CtStatement> statements = Query.getElements(testWithAssert, new TypeFilter(CtStatement.class));
    for (String id : observations.keySet()) {
        if (!id.split("__")[0].equals(testWithAssert.getSimpleName())) {
            continue;
        }
        final List<CtStatement> assertStatements = AssertBuilder.buildAssert(factory, observations.get(id).getNotDeterministValues(), observations.get(id).getObservationValues(), Double.parseDouble(configuration.getProperties().getProperty("delta", "0.1")));
        if (assertStatements.stream().map(Object::toString).map("// AssertGenerator add assertion\n"::concat).anyMatch(testWithAssert.getBody().getLastStatement().toString()::equals)) {
            continue;
        }
        int line = Integer.parseInt(id.split("__")[1]);
        CtStatement lastStmt = null;
        for (CtStatement statement : assertStatements) {
            DSpotUtils.addComment(statement, "AssertGenerator add assertion", CtComment.CommentType.INLINE);
            try {
                CtStatement stmt = statements.get(line);
                if (lastStmt == null) {
                    lastStmt = stmt;
                }
                if (stmt instanceof CtBlock) {
                    break;
                }
                if (stmt instanceof CtInvocation && !AssertGeneratorHelper.isVoidReturn((CtInvocation) stmt) && stmt.getParent() instanceof CtBlock) {
                    CtInvocation invocationToBeReplaced = (CtInvocation) stmt.clone();
                    final CtLocalVariable localVariable = factory.createLocalVariable(invocationToBeReplaced.getType(), "o_" + id.split("___")[0], invocationToBeReplaced);
                    stmt.replace(localVariable);
                    DSpotUtils.addComment(localVariable, "AssertGenerator create local variable with return value of invocation", CtComment.CommentType.INLINE);
                    localVariable.setParent(stmt.getParent());
                    if (id.endsWith("end")) {
                        testWithAssert.getBody().insertEnd(statement);
                    } else {
                        localVariable.insertAfter(statement);
                    }
                    statements.remove(line);
                    statements.add(line, localVariable);
                } else {
                    if (id.endsWith("end")) {
                        stmt.getParent(CtBlock.class).insertEnd(statement);
                    } else {
                        lastStmt.insertAfter(statement);
                    }
                }
                lastStmt = statement;
                numberOfAddedAssertion++;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    Counter.updateAssertionOf(testWithAssert, numberOfAddedAssertion);
    if (!testWithAssert.equals(test)) {
        return testWithAssert;
    } else {
        AmplificationHelper.removeAmpTestParent(testWithAssert);
        return null;
    }
}
Also used : TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtMethod(spoon.reflect.declaration.CtMethod) TestTimedOutException(org.junit.runners.model.TestTimedOutException) IOException(java.io.IOException)

Example 80 with CtMethod

use of spoon.reflect.declaration.CtMethod in project dspot by STAMP-project.

the class MethodsAssertGenerator method makeFailureTest.

/**
 * Adds surrounding try/catch/fail in a failing test.
 *
 * @param test Failing test method to amplify
 * @param failure Test's failure description
 * @return New amplified test
 */
protected CtMethod<?> makeFailureTest(CtMethod<?> test, Failure failure) {
    CtMethod cloneMethodTest = AmplificationHelper.cloneTestMethodForAmp(test, "");
    cloneMethodTest.setSimpleName(test.getSimpleName());
    Factory factory = cloneMethodTest.getFactory();
    Throwable exception = failure.getException();
    if (// TestTimedOutException means infinite loop
    exception instanceof TestTimedOutException || exception instanceof AssertionError) {
        // AssertionError means that some assertion remained in the test: TODO
        return null;
    }
    Class exceptionClass;
    if (exception == null) {
        exceptionClass = Exception.class;
    } else {
        exceptionClass = exception.getClass();
    }
    CtTry tryBlock = factory.Core().createTry();
    tryBlock.setBody(cloneMethodTest.getBody());
    String snippet = "org.junit.Assert.fail(\"" + test.getSimpleName() + " should have thrown " + exceptionClass.getSimpleName() + "\")";
    tryBlock.getBody().addStatement(factory.Code().createCodeSnippetStatement(snippet));
    DSpotUtils.addComment(tryBlock, "AssertGenerator generate try/catch block with fail statement", CtComment.CommentType.INLINE);
    CtCatch ctCatch = factory.Core().createCatch();
    CtTypeReference exceptionType = factory.Type().createReference(exceptionClass);
    ctCatch.setParameter(factory.Code().createCatchVariable(exceptionType, "eee"));
    ctCatch.setBody(factory.Core().createBlock());
    List<CtCatch> catchers = new ArrayList<>(1);
    catchers.add(ctCatch);
    tryBlock.setCatchers(catchers);
    CtBlock body = factory.Core().createBlock();
    body.addStatement(tryBlock);
    cloneMethodTest.setBody(body);
    cloneMethodTest.setSimpleName(cloneMethodTest.getSimpleName() + "_failAssert" + (numberOfFail++));
    Counter.updateAssertionOf(cloneMethodTest, 1);
    return cloneMethodTest;
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) Factory(spoon.reflect.factory.Factory) CtTypeReference(spoon.reflect.reference.CtTypeReference) TestTimedOutException(org.junit.runners.model.TestTimedOutException) CtMethod(spoon.reflect.declaration.CtMethod)

Aggregations

CtMethod (spoon.reflect.declaration.CtMethod)240 Test (org.junit.Test)163 Factory (spoon.reflect.factory.Factory)77 Launcher (spoon.Launcher)73 CtClass (spoon.reflect.declaration.CtClass)47 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)47 CtType (spoon.reflect.declaration.CtType)45 AbstractTest (fr.inria.AbstractTest)36 ArrayList (java.util.ArrayList)35 List (java.util.List)33 CtTypeReference (spoon.reflect.reference.CtTypeReference)31 CtInvocation (spoon.reflect.code.CtInvocation)26 CtStatement (spoon.reflect.code.CtStatement)26 AmplificationHelper (fr.inria.diversify.utils.AmplificationHelper)19 Collectors (java.util.stream.Collectors)19 CtLiteral (spoon.reflect.code.CtLiteral)18 CtElement (spoon.reflect.declaration.CtElement)18 CtIf (spoon.reflect.code.CtIf)16 CtAnnotation (spoon.reflect.declaration.CtAnnotation)16 CtField (spoon.reflect.declaration.CtField)16