Search in sources :

Example 6 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project evosuite by EvoSuite.

the class TestGenerationJob method run.

@Override
protected IStatus run(final IProgressMonitor monitor) {
    // && System.getProperty("evosuite.disable").equals("1")
    Boolean disabled = System.getProperty("evosuite.disable") != null;
    if (disabled) {
        System.out.println("TestGenerationJob: The EvoSuite plugin is disabled :(");
        return Status.OK_STATUS;
    }
    final String suiteFileName = getSuiteFileName(suiteClass);
    final IFile fileSuite = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path(suiteFileName));
    if (fileSuite != null && fileSuite.exists()) {
        // Open test suite in editor
        Display.getDefault().syncExec(new Runnable() {

            @Override
            public void run() {
                IWorkbenchWindow iw = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
                IWorkbenchPage page = iw.getActivePage();
                try {
                    IDE.openEditor(page, fileSuite, true);
                } catch (PartInitException e1) {
                    System.out.println("Could not open test suite");
                    e1.printStackTrace();
                }
            }
        });
        // Generated tests should be checked by tester?
        Boolean checkMarkers = System.getProperty("evosuite.markers.enforce") != null;
        if (checkMarkers) {
            String fileContents = readFileToString(suiteFileName);
            ASTParser parser = ASTParser.newParser(AST.JLS8);
            parser.setKind(ASTParser.K_COMPILATION_UNIT);
            parser.setStatementsRecovery(true);
            @SuppressWarnings("unchecked") Map<String, String> COMPILER_OPTIONS = new HashMap<String, String>(JavaCore.getOptions());
            COMPILER_OPTIONS.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7);
            COMPILER_OPTIONS.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7);
            COMPILER_OPTIONS.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7);
            parser.setUnitName(suiteClass);
            String[] encodings = { ENCODING };
            String[] classpaths = { classPath };
            String[] sources = { new File(suiteFileName).getParent() };
            parser.setEnvironment(classpaths, sources, encodings, true);
            parser.setSource(fileContents.toCharArray());
            CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
            final List<String> uncheckedMethods = new ArrayList<String>();
            compilationUnit.accept(new ASTVisitor() {

                @Override
                public boolean visit(MemberValuePair node) {
                    if (node.getName().toString().equals("checked") && !((BooleanLiteral) node.getValue()).booleanValue()) {
                        NormalAnnotation ann = (NormalAnnotation) node.getParent();
                        MethodDeclaration method = (MethodDeclaration) ann.getParent();
                        uncheckedMethods.add(method.getName().toString());
                        return false;
                    }
                    return true;
                }
            });
            if (uncheckedMethods.size() > 0) {
                Display.getDefault().syncExec(new Runnable() {

                    @Override
                    public void run() {
                        MessageDialog dialog = new MessageDialog(shell, "JUnit test suite contains unit tests that need to be checked", // image
                        null, "The JUnit test suite " + suiteClass + " contains test cases that need to be checked:\n" + uncheckedMethods.toString(), MessageDialog.OK, new String[] { "Ok" }, 0);
                        dialog.open();
                    }
                });
                return Status.OK_STATUS;
            }
        } else
            System.out.println("Not checking markers.");
    } else {
        System.out.println("File " + suiteFileName + " does not exist");
    // TODO: Dialog
    // Display.getDefault().syncExec(new Runnable() {
    // @Override
    // public void run() {
    // MessageDialog dialog = new MessageDialog(
    // shell,
    // "Error during test generation",
    // null, // image
    // "EvoSuite failed to generate tests for class"
    // + suiteClass,
    // MessageDialog.OK, new String[] { "Ok" }, 0);
    // dialog.open();
    // }
    // });
    // return Status.CANCEL_STATUS;
    }
    setThread(new Thread());
    running = true;
    clearMarkersTarget();
    String oldTgr = getOldTestGenerationResult();
    lastTest = oldTgr;
    ArrayList<TestGenerationResult> results = runEvoSuite(monitor);
    writeMarkersTarget(results);
    // uncomment after experiment
    if (writeAllMarkers)
        writeMarkersTestSuite();
    try {
        target.getProject().refreshLocal(IProject.DEPTH_INFINITE, null);
        // if ("true".equals(target.getProject().getPersistentProperty(
        // EvoSuitePropertyPage.REPORT_PROP_KEY))) {
        // syncWithUi(target);
        // };
        Display.getDefault().asyncExec(new Runnable() {

            @Override
            public void run() {
                try {
                    final IFile generatedSuite = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path(suiteFileName));
                    ICompilationUnit cu = JavaCore.createCompilationUnitFrom(generatedSuite);
                    IWorkbenchWindow iw = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow();
                    IWorkbenchPage page = iw.getActivePage();
                    IEditorPart part = IDE.openEditor(page, generatedSuite, true);
                    if (Activator.organizeImports()) {
                        OrganizeImportsAction a = new OrganizeImportsAction(part.getSite());
                        a.run(cu);
                        cu.commitWorkingCopy(true, null);
                        cu.save(null, true);
                    }
                } catch (PartInitException e1) {
                    System.out.println("Could not open test suite to organize imports");
                    e1.printStackTrace();
                } catch (JavaModelException e) {
                    System.out.println("Something went wrong while saving test suite after organizing imports");
                    e.printStackTrace();
                }
                ;
            }
        });
    } catch (CoreException e) {
        System.out.println("Dear me");
        e.printStackTrace();
    }
    Activator.CURRENT_WRITING_FILE = null;
    running = false;
    monitor.done();
    done(ASYNC_FINISH);
    Activator.FILE_QUEUE.update();
    return Status.OK_STATUS;
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) IFile(org.eclipse.core.resources.IFile) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TestGenerationResult(org.evosuite.result.TestGenerationResult) MemberValuePair(org.eclipse.jdt.core.dom.MemberValuePair) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) PartInitException(org.eclipse.ui.PartInitException) MessageDialog(org.eclipse.jface.dialogs.MessageDialog) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) OrganizeImportsAction(org.eclipse.jdt.ui.actions.OrganizeImportsAction) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IEditorPart(org.eclipse.ui.IEditorPart) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) CoreException(org.eclipse.core.runtime.CoreException) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Example 7 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project whole by wholeplatform.

the class JDTTransformerVisitor method visit.

@Override
public boolean visit(NormalAnnotation annotation) {
    org.whole.lang.java.model.NormalAnnotation ann = lf.createNormalAnnotation();
    NormalAnnotation normalAnnotation = (NormalAnnotation) annotation;
    acceptChild(normalAnnotation.getTypeName());
    ann.setTypeName(name);
    ann.getValues().clear();
    Iterator<?> iterator = normalAnnotation.values().iterator();
    while (iterator.hasNext()) {
        ((ASTNode) iterator.next()).accept(this);
        ann.getValues().wAdd(this.memberValuePair);
    }
    exp = ann;
    return false;
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation)

Example 8 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project evosuite by EvoSuite.

the class CodeGenerator method generateCode.

// FIXME specifying classes here might not be needed anymore, if we only instrument observed classes...
@SuppressWarnings("unchecked")
private CompilationUnit generateCode(final String cuName, final String packageName, final boolean postprocessing, final Class<?>... observedClasses) {
    if (cuName == null || cuName.isEmpty()) {
        throw new IllegalArgumentException("Illegal compilation unit name: " + cuName);
    }
    if (observedClasses == null || observedClasses.length == 0) {
        throw new IllegalArgumentException("No observed classes specified");
    }
    if (packageName == null) {
        throw new NullPointerException("package name must not be null");
    }
    // --- 1. step: extract class names
    final HashSet<String> observedClassNames = new HashSet<String>();
    for (int i = 0; i < observedClasses.length; i++) {
        observedClassNames.add(observedClasses[i].getName());
    }
    // --- 2. step: get all oids of the instances of the observed classes
    // NOTE: They are implicitly sorted by INIT_REC_NO because of the natural object creation order captured by the
    // instrumentation
    final TIntArrayList targetOIDs = new TIntArrayList();
    final int numInfoRecs = this.log.oidClassNames.size();
    for (int i = 0; i < numInfoRecs; i++) {
        if (observedClassNames.contains(this.log.oidClassNames.get(i))) {
            targetOIDs.add(this.log.oids.getQuick(i));
        }
    }
    // --- 3. step: init compilation unit
    final AST ast = AST.newAST(AST.JLS3);
    CompilationUnit cu = ast.newCompilationUnit();
    // package declaration
    final PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newName(packageName.split("\\.")));
    cu.setPackage(p1);
    // import specifications
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "org", "junit", "Test" }));
    cu.imports().add(id);
    // class declaration
    final TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName(cuName));
    td.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    cu.types().add(td);
    // test method construction
    final MethodDeclaration md = ast.newMethodDeclaration();
    md.setName(ast.newSimpleName("test"));
    md.thrownExceptions().add(ast.newSimpleName("Exception"));
    // sets @Test annotation to test method
    final NormalAnnotation annotation = ast.newNormalAnnotation();
    annotation.setTypeName(ast.newSimpleName("Test"));
    md.modifiers().add(annotation);
    // sets method to public
    md.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    td.bodyDeclarations().add(md);
    final Block block = ast.newBlock();
    md.setBody(block);
    // no invocations on objects of observed classes -> return empty but compilable CompilationUnit
    if (targetOIDs.isEmpty()) {
        return cu;
    }
    // --- 4. step: generating code starting with OID with lowest log rec no.
    final int numLogRecords = this.log.objectIds.size();
    int currentOID = targetOIDs.getQuick(0);
    try {
        // TODO knowing last logRecNo for termination criterion belonging to an observed instance would prevent processing unnecessary statements
        for (int currentRecord = this.log.oidRecMapping.get(currentOID); currentRecord < numLogRecords; currentRecord++) {
            currentOID = this.log.objectIds.getQuick(currentRecord);
            if (targetOIDs.contains(currentOID)) {
                this.restorceCodeFromLastPosTo(packageName, currentOID, currentRecord, postprocessing, ast, block);
                // forward to end of method call sequence
                currentRecord = findEndOfMethod(currentRecord, currentOID);
                // each method call is considered as object state modification -> so save last object modification
                log.updateWhereObjectWasInitializedFirst(currentOID, currentRecord);
            }
        }
    } catch (Exception e) {
        // System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"+this.log);
        throw new RuntimeException(e.getMessage(), e);
    }
    if (this.isXStreamNeeded) {
        id = ast.newImportDeclaration();
        id.setName(ast.newName(new String[] { "com", "thoughtworks", "xstream", "XStream" }));
        cu.imports().add(id);
        // create XSTREAM constant: private static final XStream XSTREAM = new XStream();
        final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
        vd.setName(ast.newSimpleName("XSTREAM"));
        final ClassInstanceCreation ci = ast.newClassInstanceCreation();
        ci.setType(this.createAstType("XStream", ast));
        vd.setInitializer(ci);
        final FieldDeclaration xstreamConst = ast.newFieldDeclaration(vd);
        xstreamConst.setType(this.createAstType("XStream", ast));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
        td.bodyDeclarations().add(xstreamConst);
        this.isXStreamNeeded = false;
    }
    // -- creates utility method to set field value via reflections
    if (this.isSetFieldMethodNeeded) {
        this.createSetFieldMethod(td, cu, ast);
        this.isSetFieldMethodNeeded = false;
    }
    // -- creates utility method to get field value via reflections
    if (this.isGetFieldMethodNeeded) {
        this.createGetFieldMethod(td, cu, ast);
        this.isGetFieldMethodNeeded = false;
    }
    // -- creates utility method to call method via reflections
    if (this.isCallMethodMethodNeeded) {
        this.createCallMethod(td, cu, ast);
        this.isCallMethodMethodNeeded = false;
    }
    // -- creates utility method to call constructor via reflections
    if (this.isNewInstanceMethodNeeded) {
        this.createNewInstanceMethod(td, cu, ast);
        this.isNewInstanceMethodNeeded = false;
    }
    return cu;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) TIntArrayList(gnu.trove.list.array.TIntArrayList) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) Block(org.eclipse.jdt.core.dom.Block) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) HashSet(java.util.HashSet) TIntHashSet(gnu.trove.set.hash.TIntHashSet)

Example 9 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project evosuite by EvoSuite.

the class JUnitCodeGenerator method before.

@SuppressWarnings("unchecked")
@Override
public void before(CaptureLog log) {
    ast = AST.newAST(AST.JLS3);
    cu = ast.newCompilationUnit();
    // package declaration
    final PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newName(packageName.split("\\.")));
    cu.setPackage(p1);
    // import specifications
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "org", "junit", "Test" }));
    cu.imports().add(id);
    // class declaration
    td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName(cuName));
    td.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    cu.types().add(td);
    // test method construction
    final MethodDeclaration md = ast.newMethodDeclaration();
    md.setName(ast.newSimpleName("test"));
    md.thrownExceptions().add(ast.newSimpleName("Exception"));
    // sets @Test annotation to test method
    final NormalAnnotation annotation = ast.newNormalAnnotation();
    annotation.setTypeName(ast.newSimpleName("Test"));
    md.modifiers().add(annotation);
    // sets method to public
    md.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    td.bodyDeclarations().add(md);
    methodBlock = ast.newBlock();
    md.setBody(methodBlock);
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration)

Example 10 with NormalAnnotation

use of org.eclipse.jdt.core.dom.NormalAnnotation in project generator by mybatis.

the class ExistingJavaFileVisitor method isGeneratedAnnotation.

@SuppressWarnings("unchecked")
private boolean isGeneratedAnnotation(Annotation annotation) {
    String typeName = annotation.getTypeName().getFullyQualifiedName();
    if (isGeneratedType(typeName)) {
        if (annotation.isNormalAnnotation()) {
            NormalAnnotation normalAnnotation = (NormalAnnotation) annotation;
            List<MemberValuePair> values = normalAnnotation.values();
            for (MemberValuePair pair : values) {
                String name = pair.getName().getFullyQualifiedName();
                String value = null;
                Expression exp = pair.getValue();
                if (exp instanceof StringLiteral) {
                    value = ((StringLiteral) exp).getLiteralValue();
                }
                if (MyBatisGenerator.class.getName().equals(value) && "value".equals(name)) {
                    return true;
                }
            }
        } else if (annotation.isSingleMemberAnnotation()) {
            SingleMemberAnnotation singleMemberAnnotation = (SingleMemberAnnotation) annotation;
            Expression exp = singleMemberAnnotation.getValue();
            String value = null;
            if (exp instanceof StringLiteral) {
                value = ((StringLiteral) exp).getLiteralValue();
            }
            if (MyBatisGenerator.class.getName().equals(value)) {
                return true;
            }
        }
    }
    return false;
}
Also used : MemberValuePair(org.eclipse.jdt.core.dom.MemberValuePair) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) Expression(org.eclipse.jdt.core.dom.Expression) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation)

Aggregations

NormalAnnotation (org.eclipse.jdt.core.dom.NormalAnnotation)23 MemberValuePair (org.eclipse.jdt.core.dom.MemberValuePair)13 SingleMemberAnnotation (org.eclipse.jdt.core.dom.SingleMemberAnnotation)10 ASTNode (org.eclipse.jdt.core.dom.ASTNode)9 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)8 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)7 Annotation (org.eclipse.jdt.core.dom.Annotation)6 Expression (org.eclipse.jdt.core.dom.Expression)6 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)6 AST (org.eclipse.jdt.core.dom.AST)5 StringLiteral (org.eclipse.jdt.core.dom.StringLiteral)5 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)4 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)4 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)4 HashSet (java.util.HashSet)3 ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)3 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)3 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)3 ImportDeclaration (org.eclipse.jdt.core.dom.ImportDeclaration)3 PackageDeclaration (org.eclipse.jdt.core.dom.PackageDeclaration)3