spoon.reflect.declaration.CtMethod Java Examples

The following examples show how to use spoon.reflect.declaration.CtMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExtendedRepairGenerator.java    From coming with MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example #2
Source File: VarMappingTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testNotMappedVars() {
	// Testing Not Mapped variables
	// We get a method setup(UnivariateRealFunction f) for testing the
	// insertion of a ingredient out of scope
	CtMethod mSetup = getMethod4Test1(engine);
	assertNotNull(mSetup);
	CtStatement stmSetup = mSetup.getBody().getStatement(0);
	List<CtVariable> varsScopeStmSetup = VariableResolver.searchVariablesInScope(stmSetup);
	assertFalse(varsScopeStmSetup.isEmpty());
	// field: private static final String NULL_FUNCTION_MESSAGE, parameter
	// UnivariateRealFunction f
	assertEquals(2, varsScopeStmSetup.size());
	log.debug("context of Setup method " + varsScopeStmSetup);

	VarMapping vmapping3 = VariableResolver.mapVariablesUsingCluster(varsScopeStmSetup, otherClassElementC8);
	assertTrue(vmapping3.getMappedVariables().isEmpty());
	assertFalse(vmapping3.getNotMappedVariables().isEmpty());
	assertEquals(2, vmapping3.getNotMappedVariables().size());

}
 
Example #3
Source File: NodeCreator.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void visitCtMethod(CtMethod<T> e) {
	// add the return type of the method
	CtTypeReference<T> type = e.getType();
	if (type != null) {
		ITree returnType = builder.createNode("RETURN_TYPE", type.getQualifiedName());
		returnType.setMetadata(SpoonGumTreeBuilder.SPOON_OBJECT, type);
		type.putMetadata(SpoonGumTreeBuilder.GUMTREE_NODE, returnType);
		builder.addSiblingNode(returnType);
	}

	for (CtTypeReference thrown : e.getThrownTypes()) {
		ITree thrownType = builder.createNode("THROWS", thrown.getQualifiedName());
		thrownType.setMetadata(SpoonGumTreeBuilder.SPOON_OBJECT, thrown);
		type.putMetadata(SpoonGumTreeBuilder.GUMTREE_NODE, thrownType);
		builder.addSiblingNode(thrownType);
	}

	super.visitCtMethod(e);
}
 
Example #4
Source File: BoundProcessor.java    From spoon-examples with GNU General Public License v2.0 6 votes vote down vote up
public void process(Bound annotation, CtParameter<?> element) {
	final CtMethod parent = element.getParent(CtMethod.class);

	// Build if check for min.
	CtIf anIf = getFactory().Core().createIf();
	anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min()));
	CtThrow throwStmt = getFactory().Core().createThrow();
	throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")"));
	anIf.setThenStatement(throwStmt);
	parent.getBody().insertBegin(anIf);
	anIf.setParent(parent);

	// Build if check for max.
	anIf = getFactory().Core().createIf();
	anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max()));
	anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")"));
	parent.getBody().insertBegin(anIf);
	anIf.setParent(parent);
}
 
Example #5
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static List<CtExpression> checkOcurrenceOfOtherParameters(CtMethod anotherMethod, CtMethod affectedMethod,
		List realParameters) {

	List newRealParameters = new ArrayList();

	for (Object parameterFromAnotherM : anotherMethod.getParameters()) {
		CtParameter parAnother = (CtParameter) parameterFromAnotherM;

		int indexOfParameter = affectedMethod.getParameters().indexOf(parAnother);
		// The parameter does not exist in the previous version
		if (indexOfParameter < 0) {
			return null;
		} else {
			CtExpression parameterAtI = (CtExpression) realParameters.get(indexOfParameter);
			newRealParameters.add(parameterAtI);
		}

	}
	// all parameters exist
	return newRealParameters;
}
 
Example #6
Source File: AbstractCodeAnalyzer.java    From coming with MIT License 6 votes vote down vote up
/**
 * Check if a method declaration has a parameter compatible and return with the
 * cttype as argument
 * 
 * @param allMethods
 * @param typeToMatch
 * @return
 */
public CtMethod checkMethodDeclarationWithParameterReturnCompatibleType(List allMethods,
		CtTypeReference typeToMatch) {
	for (Object omethod : allMethods) {

		if (!(omethod instanceof CtMethod))
			continue;

		CtMethod anotherMethodInBuggyClass = (CtMethod) omethod;

		// Check the parameters
		for (Object oparameter : anotherMethodInBuggyClass.getParameters()) {
			CtParameter parameter = (CtParameter) oparameter;

			if (compareTypes(typeToMatch, parameter.getType())
					&& compareTypes(typeToMatch, anotherMethodInBuggyClass.getType())) {

				return anotherMethodInBuggyClass;
			}
		}
	}

	return null;
}
 
Example #7
Source File: LogicalExpressionAnalyzer.java    From coming with MIT License 6 votes vote down vote up
/**
 * Check if a method declaration has a parameter compatible with that one from
 * the var affected
 * 
 * @param allMethods
 * @param varAffected
 * @return
 */
public CtMethod checkBooleanMethodDeclarationWithTypeInParameter(List allMethods, CtVariableAccess varAffected) {
	
	for (Object omethod : allMethods) {

		if (!(omethod instanceof CtMethod))
			continue;

		CtMethod anotherMethodInBuggyClass = (CtMethod) omethod;

		for (Object oparameter : anotherMethodInBuggyClass.getParameters()) {
			CtParameter parameter = (CtParameter) oparameter;

			if (compareTypes(varAffected.getType(), parameter.getType())) {
				if (anotherMethodInBuggyClass.getType().unbox().toString().equals("boolean")) {

					return anotherMethodInBuggyClass;
				}
			}
		}
	}
	return null;
}
 
Example #8
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private void fetchLibOverload(CtInvocation call) {
       
	List<String> origTypes = resolveTypes(call.getArguments());
	CtExpression exp = call.getTarget();
	String typename=exp.getType().getQualifiedName();
	if(typename==null||typename.isEmpty())
		return;
	
       CtClass classname = parser.getClassMap().get(typename); 

	if(classname!=null) {
		Set<CtMethod> overloadmethods=classname.getMethods();
           for(CtMethod methodoverloaded : overloadmethods) {
           	if(call.getExecutable().getSimpleName().equals(methodoverloaded.getSimpleName())) {
           	  List<CtParameter> paramlist=methodoverloaded.getParameters();
           	  List<String> target=resolveParams(paramlist);
           	  transformOneMethod(origTypes,target, call);
           	}
           }
	} else {
		List<Class[]> params = parser.fetchMethods(typename, call.getExecutable().getSimpleName());
		for (Class[] p : params)
			transformOneConstructor(origTypes, call, p);
	}
}
 
Example #9
Source File: MetaGenerator.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public static CtInvocation creationInvocationToMega(ModificationPoint modificationPoint,
		List<CtExpression<?>> realParameters, CtMethod<?> megaMethod) {
	CtType target = modificationPoint.getCodeElement().getParent(CtType.class);
	CtExpression invocationTarget = MutationSupporter.getFactory().createThisAccess(target.getReference());

	// Here, we have to consider if the parent method is static.
	CtMethod parentMethod = modificationPoint.getCodeElement().getParent(CtMethod.class);
	if (parentMethod != null) {

		if (parentMethod.getModifiers().contains(ModifierKind.STATIC)) {
			// modifiers.add(ModifierKind.STATIC);
			invocationTarget = MutationSupporter.getFactory().createTypeAccess(target.getReference());

		}
	}

	// Invocation to mega

	CtInvocation newInvocationToMega = MutationSupporter.getFactory().createInvocation(invocationTarget,
			megaMethod.getReference(), realParameters);
	return newInvocationToMega;
}
 
Example #10
Source File: TestSelectionProcessor.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean isToBeProcessed(CtMethod element){

    boolean isTest = false;
    for(CtAnnotation<? extends Annotation> annotation : element.getAnnotations()){
        if (annotation.getType().equals(annotation.getFactory().Annotation().createReference(org.junit.Test.class))) {
            isTest = true;
        }
    }

    if(!isTest){
        return false; //keep this one
    }

    for(CtMethod<?> method : keptMethods){
        if(element.getSignature().equals(method.getSignature())){
            return false; //keep this one
        }
    }

    return super.isToBeProcessed(element);
}
 
Example #11
Source File: EnhancedRepairAnalyzer.java    From coming with MIT License 6 votes vote down vote up
public List<CtInvocation> getCandidateCalleeFunction(CtInvocation CE) {
    List<CtInvocation> ret = new ArrayList<>();

    CtMethod ownedMethod = CE.getParent(new TypeFilter<>(CtMethod.class));
    if (ownedMethod != null) {
        List<CtInvocation> invocations = ownedMethod.getElements(new TypeFilter<>(CtInvocation.class));
        for (CtInvocation invocation : invocations) {
            if (CE == invocation) {
                continue;
            }
            if (CE.getExecutable() != invocation.getExecutable()) {
                continue;
            }
            if (CE.getArguments().size() != invocation.getArguments().size()) {
                continue;
            }
            ret.add(invocation);
        }
    }
    return ret;
}
 
Example #12
Source File: EnhancedRepairGenerator.java    From coming with MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example #13
Source File: OriginalRepairGenerator.java    From coming with MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example #14
Source File: S4RORepairAnalyzer.java    From coming with MIT License 6 votes vote down vote up
public List<CtInvocation> getCandidateCalleeFunction(CtInvocation CE) {
    List<CtInvocation> ret = new ArrayList<>();

    CtMethod ownedMethod = CE.getParent(new TypeFilter<>(CtMethod.class));
    if (ownedMethod != null) {
        List<CtInvocation> invocations = ownedMethod.getElements(new TypeFilter<>(CtInvocation.class));
        for (CtInvocation invocation : invocations) {
            if (CE == invocation) {
                continue;
            }
            if (CE.getExecutable() != invocation.getExecutable()) {
                continue;
            }
            if (CE.getArguments().size() != invocation.getArguments().size()) {
                continue;
            }
            ret.add(invocation);
        }
    }
    return ret;
}
 
Example #15
Source File: ApiModelPropertyProcessor.java    From camunda-bpm-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final CtMethod<?> method) {
  final CtAnnotation<Annotation> annotation = getFactory().Code().createAnnotation(getFactory().Code().createCtTypeReference(ApiModelProperty.class));

  final String fieldName = uncapitalize(removeStart(method.getSimpleName(), "get"));
  final String classFqn = TypeHelper.getClassname(method);

  final Map<String, ParameterDescription> docs = context.getDtoDocumentation().get(classFqn);
  if (docs != null) {
    final ParameterDescription parameterDescription = docs.get(fieldName);
    if (parameterDescription != null) {
      log.debug("Found parameter description for {} {}", classFqn, fieldName);
      annotation.addValue("value", parameterDescription.getDescription());
      if (parameterDescription.getRequired() != null) {
        annotation.addValue("required", parameterDescription.getRequired().booleanValue());
      }
    }
  }

  annotation.addValue("name", fieldName);

  method.addAnnotation(annotation);
}
 
Example #16
Source File: S4RORepairGenerator.java    From coming with MIT License 6 votes vote down vote up
private Set<CtElement> fuzzyLocator(CtElement statement) {
    Set<CtElement> locations = new HashSet<>();
    if (statement instanceof CtMethod || statement instanceof CtClass || statement instanceof CtIf || statement instanceof CtStatementList) {
        locations.add(statement);
    } else {
        // "int a;" is not CtStatement?
        CtElement parent = statement.getParent();
        if (parent != null) {
            List<CtElement> statements = parent.getElements(new TypeFilter<>(CtElement.class));
            if (parent instanceof CtStatement) {
                statements = statements.subList(1, statements.size());
            }
            int idx = statements.indexOf(statement);
            if (idx >= 0) {
                if (idx > 0)
                    locations.add(statements.get(idx - 1));
                locations.add(statements.get(idx));
                if (idx < statements.size() - 1)
                    locations.add(statements.get(idx + 1));
            }
        }
    }
    return locations;
}
 
Example #17
Source File: SpoonSupportTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemove() {
	String c1 = "" + "class X {" + "public void foo0() {" + " int x = 0;return;" + "}" + "};";

	String c2 = "" + "class X {" + "public void foo0() {" + " int x = 0;" + "}" + "};";

	AstComparator diff = new AstComparator();
	Diff editScript = diff.compare(c1, c2);
	assertEquals(1, editScript.getRootOperations().size());

	Operation op = editScript.getRootOperations().get(0);
	assertTrue(op instanceof DeleteOperation);

	assertNotNull(op.getSrcNode());
	assertEquals("return", op.getSrcNode().toString());

	CtMethod methodSrc = op.getSrcNode().getParent(CtMethod.class);
	assertEquals(2, methodSrc.getBody().getStatements().size());
	assertNotNull(methodSrc);

	SpoonSupport support = new SpoonSupport();
	CtMethod methodTgt = (CtMethod) support.getMappedElement(editScript, methodSrc, true);
	assertNotNull(methodTgt);
	assertEquals("foo0", methodTgt.getSimpleName());
	assertEquals(1, methodTgt.getBody().getStatements().size());
	assertEquals("int x = 0", methodTgt.getBody().getStatements().get(0).toString());
}
 
Example #18
Source File: SpoonSupportTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Test
public void testInsert1_SearchInWrong() {
	String c1 = "" + "class X {" + "public int foo0() {" + " int x = 0;return 1;" + "}" + "};";

	String c2 = "" + "class X {" + "public int foo0() {" + " int x = 0;x = 10;return 1;" + "}" + "};";

	AstComparator diff = new AstComparator();
	Diff editScript = diff.compare(c1, c2);
	assertEquals(1, editScript.getRootOperations().size());

	Operation op = editScript.getRootOperations().get(0);
	assertTrue(op instanceof InsertOperation);

	assertNotNull(op.getSrcNode());
	assertEquals("x = 10", op.getSrcNode().toString());

	CtMethod methodRight = op.getSrcNode().getParent(CtMethod.class);
	assertNotNull(methodRight);
	assertEquals("foo0", methodRight.getSimpleName());
	assertEquals(3, methodRight.getBody().getStatements().size());
	assertEquals("x = 10", methodRight.getBody().getStatements().get(1).toString());

	SpoonSupport support = new SpoonSupport();
	// Search one insert in left part
	CtMethod methodLeft = (CtMethod) support.getMappedElement(editScript, methodRight, true);

	assertNull(methodLeft);
}
 
Example #19
Source File: OverloadMethodTransform.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private boolean fetchInClassOverload(CtInvocation call, CtClass classname) {
	
	if(!call.getTarget().getType().getQualifiedName().equals(classname.getQualifiedName())) {
		return false;
	}
	
	String name = call.getExecutable().getSimpleName();
	Set<CtMethod> methods=classname.getMethods();
	List<CtMethod> overloadmethods = new ArrayList<CtMethod>();
	for(CtMethod method: methods) {
		if(method.getSimpleName().equals(name))
			overloadmethods.add(method);
	}
	
	if (overloadmethods.size() == 0)
		return false;
	if (overloadmethods.size()== 1) {
		return true;
	}
	
	List<String> origTypes = resolveTypes(call.getArguments());

	if (origTypes == null)
		return true;
	for (CtMethod mtd : overloadmethods) {
		transformOneMethod(origTypes, resolveParams(mtd.getParameters()), call);
	}
	return true;
}
 
Example #20
Source File: ReplaceReturnOp.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
private CtElement createReturn(CtElement rootElement) {
	CtMethod method = rootElement.getParent(CtMethod.class);

	if (method == null) {
		log.info("Element without method parent");
		return null;
	}
	// We create the "if(true)"{}
	CtIf ifReturn = MutationSupporter.getFactory().Core().createIf();
	CtExpression ifTrueExpression = MutationSupporter.getFactory().Code().createCodeSnippetExpression("true");
	ifReturn.setCondition(ifTrueExpression);

	// Now we create the return statement
	CtReturn<?> returnStatement = null;
	CtTypeReference typeR = method.getType();
	if (typeR == null || "void".equals(typeR.getSimpleName())) {
		returnStatement = MutationSupporter.getFactory().Core().createReturn();
	} else {
		String codeExpression = "";
		if (prim.contains(typeR.getSimpleName())) {
			codeExpression = getZeroValue(typeR.getSimpleName().toLowerCase());
		} else if (typeR.getSimpleName().toLowerCase().equals("boolean")) {
			codeExpression = "false";
		} else {
			codeExpression = "null";
		}
		CtExpression returnExpression = MutationSupporter.getFactory().Code()
				.createCodeSnippetExpression(codeExpression);
		returnStatement = MutationSupporter.getFactory().Core().createReturn();
		returnStatement.setReturnedExpression(returnExpression);
	}
	// Now, we associate if(true){return [...]}
	ifReturn.setThenStatement(returnStatement);
	return ifReturn;

}
 
Example #21
Source File: EnhancedRepairAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public List<CtElement> getCandidateLocalVars(CtElement element, Type type) {
    List<CtElement> ret = new ArrayList<>();
    CtMethod ownedMethod = element.getParent(new TypeFilter<>(CtMethod.class));
    if (ownedMethod != null) {
        for (CtLocalVariable tmp : ownedMethod.getElements(new TypeFilter<>(CtLocalVariable.class))) {
            if (tmp.getClass().getGenericSuperclass() == type) {
                ret.add(tmp);
            }
        }
    }
    return ret;
}
 
Example #22
Source File: S4RORepairAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public List<CtElement> getCondCandidateVars(CtElement element) {
    List<CtElement> ret = new ArrayList<>();
    // Global variables
    CtClass ownedClass = element.getParent(new TypeFilter<>(CtClass.class));
    if (ownedClass != null) {
        ret.addAll(ownedClass.getElements(new TypeFilter<>(CtVariableAccess.class)));
        ret.addAll(ownedClass.getElements(new TypeFilter<>(CtArrayAccess.class)));
    }
    // Local variables
    CtMethod ownedMethod = element.getParent(new TypeFilter<>(CtMethod.class));
    if (ownedMethod != null) {
        ret.addAll(ownedMethod.getElements(new TypeFilter<>(CtLocalVariable.class)));
    }
    return ret;
}
 
Example #23
Source File: S4RORepairAnalyzer.java    From coming with MIT License 5 votes vote down vote up
public List<CtElement> getCandidateLocalVars(CtElement element, Type type) {
    List<CtElement> ret = new ArrayList<>();
    CtMethod ownedMethod = element.getParent(new TypeFilter<>(CtMethod.class));
    if (ownedMethod != null) {
        for (CtLocalVariable tmp : ownedMethod.getElements(new TypeFilter<>(CtLocalVariable.class))) {
            if (tmp.getClass().getGenericSuperclass() == type) {
                ret.add(tmp);
            }
        }
    }
    return ret;
}
 
Example #24
Source File: SpoonSupportTest.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Test
public void testInsert1() {
	String c1 = "" + "class X {" + "public int foo0() {" + " int x = 0;return 1;" + "}" + "};";

	String c2 = "" + "class X {" + "public int foo0() {" + " int x = 0;x = 10;return 1;" + "}" + "};";

	AstComparator diff = new AstComparator();
	Diff editScript = diff.compare(c1, c2);
	assertEquals(1, editScript.getRootOperations().size());

	Operation op = editScript.getRootOperations().get(0);
	assertTrue(op instanceof InsertOperation);

	assertNotNull(op.getSrcNode());
	assertEquals("x = 10", op.getSrcNode().toString());

	CtMethod methodRight = op.getSrcNode().getParent(CtMethod.class);
	assertNotNull(methodRight);
	assertEquals("foo0", methodRight.getSimpleName());
	assertEquals(3, methodRight.getBody().getStatements().size());
	assertEquals("x = 10", methodRight.getBody().getStatements().get(1).toString());

	SpoonSupport support = new SpoonSupport();
	CtMethod methodLeft = (CtMethod) support.getMappedElement(editScript, methodRight, false);

	assertNotNull(methodLeft);
	assertEquals("foo0", methodLeft.getSimpleName());
	assertEquals(2, methodLeft.getBody().getStatements().size());
}
 
Example #25
Source File: Util.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
public static List<CtMethod> getGetters(CtLocalVariable localVariable) {
	return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream()
			.filter(method -> method.getParameters().isEmpty() &&
					method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE &&
					(method.getSimpleName().startsWith("get") ||
							method.getSimpleName().startsWith("is"))
			).collect(Collectors.toList());
}
 
Example #26
Source File: AssertionGenerationTest.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
	Launcher launcher = new Launcher();
	launcher.getEnvironment().setAutoImports(true);
	launcher.getEnvironment().setLevel(Level.ALL.toString());
	launcher.addInputResource("src/test/resources/project/src/main/java/");
	launcher.addInputResource("src/test/resources/project/src/test/java/");
	launcher.addInputResource("src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java");
	launcher.getEnvironment().setSourceClasspath(getPathToJunit());
	launcher.buildModel();

	final Analyzer analyzer = new Analyzer();
	final Collector collector = new Collector(launcher.getFactory());
	final AssertionAdder assertionAdder = new AssertionAdder(launcher.getFactory());

	launcher.getFactory().Class().getAll().forEach(ctClass -> {
		// Analyze
		Map<CtMethod, List<CtLocalVariable>> localVariablesPerTestMethod = analyzer.analyze(ctClass);
		localVariablesPerTestMethod.keySet().stream().forEach(key -> System.out.println("{"+ key.getParent(CtClass.class).getSimpleName() + "#" + key.getSimpleName() + "=["+ localVariablesPerTestMethod.get(key) +"]"));
		if (!localVariablesPerTestMethod.isEmpty()) {
			// Collect
			localVariablesPerTestMethod.keySet().forEach(ctMethod -> collector.collect(launcher, ctMethod, localVariablesPerTestMethod.get(ctMethod)));
			// Generate
			localVariablesPerTestMethod.keySet().forEach(ctMethod -> assertionAdder.addAssertion(ctMethod, localVariablesPerTestMethod.get(ctMethod)));
		}
	});
}
 
Example #27
Source File: AssertionAdder.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) {
	List<CtMethod> getters =
			getGetters(localVariable);
	getters.forEach(getter -> {
		String key = getKey(getter);
		CtInvocation invocationToGetter =
				invok(getter, localVariable);
		CtInvocation invocationToAssert = createAssert("assertEquals",
				factory.createLiteral(Logger.observations.get(key)), // expected
				invocationToGetter); // actual
		testMethod.getBody().insertEnd(invocationToAssert);
	});
}
 
Example #28
Source File: Analyzer.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
public Map<CtMethod, List<CtLocalVariable>> analyze(CtType<?> ctClass) {
	CtTypeReference<Test> reference =
			ctClass.getFactory().Type().createReference(Test.class);
	return ctClass.getMethods().stream()
			.filter(ctMethod -> ctMethod.getAnnotation(reference) != null)
			.collect(Collectors.toMap(
					ctMethod -> ctMethod,
					this::analyze)
			);
}
 
Example #29
Source File: SupportOperators.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static boolean checkOcurrenceOfOtherParameters(CtMethod anotherMethod, CtMethod affectedMethod) {
	// anotherMethod.getParameters().stream().map(CtParameter.class::cast)
	// .collect(Collectors.toList()

	for (Object parameterFromAnotherM : anotherMethod.getParameters()) {
		CtParameter parAnother = (CtParameter) parameterFromAnotherM;

		// The parameter does not exist in the previous version
		if (!affectedMethod.getParameters().contains(parAnother)) {
			return false;
		}
	}
	// all parameters exist
	return true;
}
 
Example #30
Source File: Collector.java    From spoon-examples with GNU General Public License v2.0 5 votes vote down vote up
public void collect(Launcher launcher, CtMethod<?> testMethod, List<CtLocalVariable> localVariables) {
	CtClass testClass = testMethod.getParent(CtClass.class);
	testClass.removeMethod(testMethod);
	CtMethod<?> clone = testMethod.clone();
	instrument(clone, localVariables);
	testClass.addMethod(clone);
	System.out.println(clone);
	run(launcher, testClass, clone);
	testClass.removeMethod(clone);
	testClass.addMethod(testMethod);
}