Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add junit 3 test (disabled) #134

Merged
merged 3 commits into from
Jan 18, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ public class MYCleanUpConstants {
*
*/
public static final String JUNIT_CLEANUP= "cleanup.junitcleanup"; //$NON-NLS-1$
/**
*
*/
public static final String JUNIT3_CLEANUP= "cleanup.junit3cleanup"; //$NON-NLS-1$
/**
*
*/
Expand Down Expand Up @@ -119,6 +123,10 @@ public class MYCleanUpConstants {
*
*/
public static final String JUNIT_CLEANUP_4_TEST= "cleanup.junitcleanup_4_test"; //$NON-NLS-1$
/**
*
*/
public static final String JUNIT_CLEANUP_3_TEST= "cleanup.junitcleanup_3_test"; //$NON-NLS-1$
/**
*
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import org.sandbox.jdt.internal.corext.fix.helper.RuleTemporayFolderJUnitPlugin;
import org.sandbox.jdt.internal.corext.fix.helper.RuleTestnameJUnitPlugin;
import org.sandbox.jdt.internal.corext.fix.helper.RunWithJUnitPlugin;
import org.sandbox.jdt.internal.corext.fix.helper.TestJUnit3Plugin;
import org.sandbox.jdt.internal.corext.fix.helper.TestJUnitPlugin;
import org.sandbox.jdt.internal.ui.fix.MultiFixMessages;

Expand All @@ -55,6 +56,7 @@ public enum JUnitCleanUpFixCore {
BEFORE(new BeforeJUnitPlugin()),
AFTER(new AfterJUnitPlugin()),
TEST(new TestJUnitPlugin()),
TEST3(new TestJUnit3Plugin()),
BEFORECLASS(new BeforeClassJUnitPlugin()),
AFTERCLASS(new AfterClassJUnitPlugin()),
IGNORE(new IgnoreJUnitPlugin()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
Expand Down Expand Up @@ -182,6 +184,12 @@ public abstract class AbstractTool<T> {
private static final String BEFORE_EACH_CALLBACK= "BeforeEachCallback";

protected static final String ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH= "org.junit.jupiter.api.extension.ExtendWith";
protected static final Set<String> twoparam= Set.of("assertEquals", "assertNotEquals", "assertArrayEquals",
"assertSame","assertNotSame","assertThat");
protected static final Set<String> oneparam= Set.of("assertTrue", "assertFalse", "assertNull", "assertNotNull");
private static final Set<String> noparam= Set.of("fail");
protected static final Set<String> allassertionmethods= Stream.of(twoparam, oneparam, noparam).flatMap(Set::stream)
.collect(Collectors.toSet());

public static Collection<String> getUsedVariableNames(ASTNode node) {
CompilationUnit root= (CompilationUnit) node.getRoot();
Expand Down Expand Up @@ -967,18 +975,18 @@ protected boolean isLifecycleMethod(MethodDeclaration method, String methodName)
return methodName.equals(method.getName().getIdentifier());
}

private boolean isStringType(Expression expression, Class<String> classType) {
protected boolean isStringType(Expression expression, Class<String> classType) {
ITypeBinding typeBinding = expression.resolveTypeBinding();
return typeBinding != null && classType.getCanonicalName().equals(typeBinding.getQualifiedName());
}

private boolean isSubtypeOf(ITypeBinding subtype, ITypeBinding supertype) {
protected boolean isSubtypeOf(ITypeBinding subtype, ITypeBinding supertype) {
return subtype != null
&& supertype != null
&& (isTypeOrSubtype(subtype, supertype.getQualifiedName()) || implementsInterface(subtype, supertype));
}

private boolean isTypeOrSubtype(ITypeBinding typeBinding, String qualifiedName) {
protected boolean isTypeOrSubtype(ITypeBinding typeBinding, String qualifiedName) {
while (typeBinding != null) {
if (qualifiedName.equals(typeBinding.getQualifiedName())) {
return true;
Expand Down Expand Up @@ -1262,8 +1270,6 @@ public void reorderParameters(MethodInvocation node, ASTRewrite rewriter, TextEd
}
}



private void replaceFieldWithExtensionDeclaration(ClassInstanceCreation classInstanceCreation,
String nestedClassName, boolean fieldStatic, ASTRewrite rewriter, AST ast, TextEditGroup group,
ImportRewrite importRewriter) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@
*/

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
Expand All @@ -60,13 +58,6 @@
*/
public class AssertJUnitPlugin extends AbstractTool<ReferenceHolder<Integer, JunitHolder>> {

static final Set<String> twoparam= Set.of("assertEquals", "assertNotEquals", "assertArrayEquals",
"assertSame","assertNotSame","assertThat");
static final Set<String> oneparam= Set.of("assertTrue", "assertFalse", "assertNull", "assertNotNull");
private static final Set<String> noparam= Set.of("fail");
private static final Set<String> allassertionmethods= Stream.of(twoparam, oneparam, noparam).flatMap(Set::stream)
.collect(Collectors.toSet());

@Override
public void find(JUnitCleanUpFixCore fixcore, CompilationUnit compilationUnit,
Set<CompilationUnitRewriteOperationWithSourceRange> operations, Set<ASTNode> nodesprocessed) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,283 @@
/*******************************************************************************
* Copyright (c) 2021 Carsten Hammer.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Carsten Hammer
*******************************************************************************/
package org.sandbox.jdt.internal.corext.fix.helper;

import java.util.List;

/*-
* #%L
* Sandbox junit cleanup
* %%
* Copyright (C) 2024 hammer
* %%
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License, v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is
* available at https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
* #L%
*/

import java.util.Set;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.MarkerAnnotation;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange;
import org.eclipse.text.edits.TextEditGroup;
import org.sandbox.jdt.internal.common.HelperVisitor;
import org.sandbox.jdt.internal.common.ReferenceHolder;
import org.sandbox.jdt.internal.corext.fix.JUnitCleanUpFixCore;

/**
*
*
*/
public class TestJUnit3Plugin extends AbstractTool<ReferenceHolder<Integer, JunitHolder>> {

@Override
public void find(JUnitCleanUpFixCore fixcore, CompilationUnit compilationUnit,
Set<CompilationUnitRewriteOperationWithSourceRange> operations, Set<ASTNode> nodesprocessed) {
ReferenceHolder<Integer, JunitHolder> dataholder= new ReferenceHolder<>();
HelperVisitor.callTypeDeclarationVisitor("junit.framework.TestCase", compilationUnit, dataholder,
nodesprocessed,
(visited, aholder) -> processFoundNode(fixcore, operations, visited, aholder, nodesprocessed));
}

private boolean processFoundNode(JUnitCleanUpFixCore fixcore,
Set<CompilationUnitRewriteOperationWithSourceRange> operations, TypeDeclaration node,
ReferenceHolder<Integer, JunitHolder> dataholder, Set<ASTNode> nodesprocessed) {
if (!nodesprocessed.contains(node)) {
boolean nothingtochange= true;
for (MethodDeclaration method : node.getMethods()) {
if (!isTestMethod(method)) {
nothingtochange= false;
}
}
if (nothingtochange) {
return false;
}

nodesprocessed.add(node);
JunitHolder mh= new JunitHolder();
mh.minv= node;
dataholder.put(dataholder.size(), mh);
operations.add(fixcore.rewrite(dataholder));
}
return false;
}

private void correctAssertionOrder(MethodInvocation node, ASTRewrite rewriter, AST ast, TextEditGroup group) {

Check warning

Code scanning / PMD

Avoid unused private methods such as 'correctAssertionOrder(MethodInvocation, ASTRewrite, AST, TextEditGroup)'. Warning

Avoid unused private methods such as 'correctAssertionOrder(MethodInvocation, ASTRewrite, AST, TextEditGroup)'.

Check warning

Code scanning / PMD

Avoid unused method parameters such as 'holder'. Warning

Avoid unused method parameters such as 'ast'.

Check notice

Code scanning / Pmd (reported by Codacy)

Avoid unused private methods such as 'correctAssertionOrder(MethodInvocation,ASTRewrite,AST,TextEditGroup)'. Note

Avoid unused private methods such as 'correctAssertionOrder(MethodInvocation,ASTRewrite,AST,TextEditGroup)'.

Check notice

Code scanning / Pmd (reported by Codacy)

Avoid unused method parameters such as 'ast'. Note

Avoid unused method parameters such as 'ast'.
String methodName = node.getName().getIdentifier();

// Prüfe, ob es sich um eine bekannte Assertion handelt
if ("assertEquals".equals(methodName) || "assertArrayEquals".equals(methodName)) {
List<?> arguments = node.arguments();
if (arguments.size() == 3) {
// Reorganisiere die Reihenfolge: message, expected, actual -> expected, actual, message
Expression expected = (Expression) arguments.get(1);
Expression actual = (Expression) arguments.get(2);
Expression message = (Expression) arguments.get(0);

ListRewrite listRewrite = rewriter.getListRewrite(node, MethodInvocation.ARGUMENTS_PROPERTY);
listRewrite.replace((ASTNode) arguments.get(0), expected, group);
listRewrite.replace((ASTNode) arguments.get(1), actual, group);
listRewrite.replace((ASTNode) arguments.get(2), message, group);
}
}
}

private boolean isTestMethod(MethodDeclaration method) {
// Konstruktoren ausschließen
if (method.isConstructor()) {
return false;
}

String methodName = method.getName().getIdentifier();

// Prüfen auf typische JUnit 3-Testmethoden
if (methodName.startsWith("test")) {
return true;
}

// Prüfen auf alternative Namensschemata
if (methodName.endsWith("_test") || methodName.startsWith("should") || methodName.contains("Test")) {
return true;
}

// Zusätzliche Bedingungen: public, void, keine Parameter
return Modifier.isPublic(method.getModifiers()) && "void".equals(method.getReturnType2().toString())
&& method.parameters().isEmpty();
}


@Override
void process2Rewrite(TextEditGroup group, ASTRewrite rewriter, AST ast, ImportRewrite importRewriter,
JunitHolder mh) {
TypeDeclaration node= mh.getTypeDeclaration();
// Remove `extends TestCase`
Type superclass= node.getSuperclassType();
if (superclass != null && "TestCase".equals(superclass.toString())) {
rewriter.remove(node.getSuperclassType(), group);
}

for (MethodDeclaration method : node.getMethods()) {
if (isSetupMethod(method)) {
convertToAnnotation(method, "BeforeEach", importRewriter, rewriter, ast, group);
} else if (isTeardownMethod(method)) {
convertToAnnotation(method, "AfterEach", importRewriter, rewriter, ast, group);
} else if (isTestMethod(method)) {
addAnnotationToMethod(method, "Test", importRewriter, rewriter, ast, group);
}

// Bearbeite Assertions und Assumptions in allen relevanten Methoden
if (method.getBody() != null) {
rewriteAssertionsAndAssumptions(method, rewriter, ast, group,importRewriter);
}
}

}

private void rewriteAssertionsAndAssumptions(MethodDeclaration method, ASTRewrite rewriter, AST ast, TextEditGroup group, ImportRewrite importRewriter) {
method.accept(new ASTVisitor() {
@Override
public boolean visit(MethodInvocation node) {
// Überprüfen, ob das MethodBinding aufgelöst werden kann
if (node.resolveMethodBinding() != null) {
String fullyQualifiedName = node.resolveMethodBinding().getDeclaringClass().getQualifiedName();

if ("junit.framework.Assert".equals(fullyQualifiedName) || "junit.framework.Assume".equals(fullyQualifiedName)) {
// correctAssertionOrder(node, rewriter, ast, group);

reorderParameters(node, rewriter, group, oneparam, twoparam);
// SimpleName newQualifier= ast.newSimpleName(ASSERTIONS);
// Expression expression= assertexpression;
// if (expression != null) {
// ASTNodes.replaceButKeepComment(rewriter, expression, newQualifier, group);
// }




// Ändere den Qualifier (z.B. Assert.assertEquals -> Assertions.assertEquals)
rewriter.set(node.getExpression(), SimpleName.IDENTIFIER_PROPERTY, "Assertions", group);
// ASTNodes.replaceButKeepComment(rewriter, expression, newQualifier, group);

// Passe Importe an
addImportForAssertion(node.getName().getIdentifier(), ast, rewriter, group, importRewriter);
}
}

return super.visit(node);
}
});
}


private void addImportForAssertion(String assertionMethod, AST ast, ASTRewrite rewriter, TextEditGroup group, ImportRewrite importRewriter) {

Check warning

Code scanning / PMD

Avoid unused method parameters such as 'holder'. Warning

Avoid unused method parameters such as 'ast'.

Check warning

Code scanning / PMD

Avoid unused method parameters such as 'holder'. Warning

Avoid unused method parameters such as 'rewriter'.

Check warning

Code scanning / PMD

Avoid unused method parameters such as 'holder'. Warning

Avoid unused method parameters such as 'group'.

Check notice

Code scanning / Pmd (reported by Codacy)

Avoid unused method parameters such as 'rewriter'. Note

Avoid unused method parameters such as 'rewriter'.

Check notice

Code scanning / Pmd (reported by Codacy)

Avoid unused method parameters such as 'group'. Note

Avoid unused method parameters such as 'group'.

Check notice

Code scanning / Pmd (reported by Codacy)

Avoid unused method parameters such as 'ast'. Note

Avoid unused method parameters such as 'ast'.
String importToAdd = null;

switch (assertionMethod) {

Check notice

Code scanning / Pmd (reported by Codacy)

Switch statements should be exhaustive, add a default case (or missing enum branches) Note

Switch statements should be exhaustive, add a default case (or missing enum branches)
case "assertEquals":
case "assertArrayEquals":
case "assertTrue":
case "assertFalse":
case "assertNull":
case "assertNotNull":
importToAdd = "org.junit.jupiter.api.Assertions";
break;
case "assumeTrue":
case "assumeFalse":
case "assumeNotNull":
importToAdd = "org.junit.jupiter.api.Assumptions";
break;
case "assertThat":
importToAdd = "org.hamcrest.MatcherAssert";
break;
}
Comment on lines +209 to +226

Check warning

Code scanning / PMD

Switch statements or expressions should be exhaustive, add a default case (or missing enum branches) Warning

Switch statements or expressions should be exhaustive, add a default case (or missing enum branches)

if (importToAdd != null) {
importRewriter.addImport(importToAdd);
}
}


private boolean isSetupMethod(MethodDeclaration method) {
return "setUp".equals(method.getName().getIdentifier()) && method.parameters().isEmpty()
&& method.getReturnType2() == null;
}

private boolean isTeardownMethod(MethodDeclaration method) {
return "tearDown".equals(method.getName().getIdentifier()) && method.parameters().isEmpty()
&& method.getReturnType2() == null;
}

private void convertToAnnotation(MethodDeclaration method, String annotation, ImportRewrite importRewrite,
ASTRewrite rewrite, AST ast, TextEditGroup group) {
// Add annotation
ListRewrite modifiers= rewrite.getListRewrite(method, MethodDeclaration.MODIFIERS2_PROPERTY);
MarkerAnnotation newMarkerAnnotation= ast.newMarkerAnnotation();
newMarkerAnnotation.setTypeName(ast.newSimpleName(annotation));
modifiers.insertFirst(newMarkerAnnotation, group);
importRewrite.addImport("org.junit.jupiter.api." + annotation.substring(1));
}

private void addAnnotationToMethod(MethodDeclaration method, String annotation, ImportRewrite importRewrite,
ASTRewrite rewrite, AST ast, TextEditGroup group) {
// Füge die Annotation zum Methodenkopf hinzu
ListRewrite modifiers= rewrite.getListRewrite(method, MethodDeclaration.MODIFIERS2_PROPERTY);
MarkerAnnotation newMarkerAnnotation= ast.newMarkerAnnotation();
newMarkerAnnotation.setTypeName(ast.newSimpleName(annotation)); // annotation sollte nur den Namen enthalten, z.
// B. "Test"
modifiers.insertFirst(newMarkerAnnotation, group);

// Import der Annotation hinzufügen
importRewrite.addImport("org.junit.jupiter.api." + annotation);
}

@Override
public String getPreview(boolean afterRefactoring) {
if (afterRefactoring) {
return """
import org.junit.jupiter.api.Test;
"""; //$NON-NLS-1$
}
return """
import junit.framework.TestCase;
"""; //$NON-NLS-1$
}

@Override
public String toString() {
return "TestCase"; //$NON-NLS-1$
}
}
Loading
Loading