-
Notifications
You must be signed in to change notification settings - Fork 36
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
Introduce MockitoMockClassReference
check
#454
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d742d6c
Introduce MockitoMockClassReference bug check
Badbond 87956a2
Add check for compatible variable tree types and extend test cases
Badbond 20be36d
Add test for unimplemented edge-cases
Badbond 54973a6
Self-apply and add XXX
Badbond 70a4cb1
Add another XXX
Badbond cabec75
Suggestions
rickie fedd8ef
Implement return type matches and do not flag variable class arguments
Badbond e1b5f72
Suggestion to restructure the check
rickie 2c1d096
Suggestions
Stephan202 fd70908
Suggestions (2)
Stephan202 180ddf6
Add XXX
rickie f0c7563
Suggestion
rickie File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
90 changes: 90 additions & 0 deletions
90
...e-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/MockitoMockClassReference.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
package tech.picnic.errorprone.bugpatterns; | ||
|
||
import static com.google.errorprone.BugPattern.LinkType.CUSTOM; | ||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; | ||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION; | ||
import static com.google.errorprone.matchers.Matchers.allOf; | ||
import static com.google.errorprone.matchers.Matchers.argument; | ||
import static com.google.errorprone.matchers.Matchers.isSameType; | ||
import static com.google.errorprone.matchers.Matchers.isVariable; | ||
import static com.google.errorprone.matchers.Matchers.not; | ||
import static com.google.errorprone.matchers.Matchers.staticMethod; | ||
import static tech.picnic.errorprone.bugpatterns.util.Documentation.BUG_PATTERNS_BASE_URL; | ||
|
||
import com.google.auto.service.AutoService; | ||
import com.google.errorprone.BugPattern; | ||
import com.google.errorprone.VisitorState; | ||
import com.google.errorprone.bugpatterns.BugChecker; | ||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; | ||
import com.google.errorprone.fixes.SuggestedFixes; | ||
import com.google.errorprone.matchers.Description; | ||
import com.google.errorprone.matchers.Matcher; | ||
import com.google.errorprone.util.ASTHelpers; | ||
import com.sun.source.tree.ExpressionTree; | ||
import com.sun.source.tree.LambdaExpressionTree; | ||
import com.sun.source.tree.MethodInvocationTree; | ||
import com.sun.source.tree.MethodTree; | ||
import com.sun.source.tree.Tree; | ||
import com.sun.source.tree.VariableTree; | ||
import java.util.List; | ||
|
||
/** | ||
* A {@link BugChecker} that flags the use of {@link org.mockito.Mockito#mock(Class)} and {@link | ||
* org.mockito.Mockito#spy(Class)} where instead the type to be mocked or spied can be derived from | ||
* context. | ||
*/ | ||
// XXX: This check currently does not flag method invocation arguments. When adding support for | ||
// this, consider that in some cases the type to be mocked or spied must be specified explicitly so | ||
// as to disambiguate between method overloads. | ||
// XXX: This check currently does not flag (implicit or explicit) lambda return expressions. | ||
// XXX: This check currently does not drop suppressions that become obsolete after the | ||
// suggested fix is applied; consider adding support for this. | ||
@AutoService(BugChecker.class) | ||
@BugPattern( | ||
summary = "Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods", | ||
link = BUG_PATTERNS_BASE_URL + "MockitoMockClassReference", | ||
linkType = CUSTOM, | ||
severity = SUGGESTION, | ||
tags = SIMPLIFICATION) | ||
public final class MockitoMockClassReference extends BugChecker | ||
implements MethodInvocationTreeMatcher { | ||
private static final long serialVersionUID = 1L; | ||
private static final Matcher<MethodInvocationTree> MOCKITO_MOCK_OR_SPY = | ||
allOf( | ||
argument(0, allOf(isSameType(Class.class.getName()), not(isVariable()))), | ||
staticMethod().onClass("org.mockito.Mockito").namedAnyOf("mock", "spy")); | ||
|
||
/** Instantiates a new {@link MockitoMockClassReference} instance. */ | ||
public MockitoMockClassReference() {} | ||
|
||
@Override | ||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { | ||
if (!MOCKITO_MOCK_OR_SPY.matches(tree, state) || !isTypeDerivableFromContext(tree, state)) { | ||
return Description.NO_MATCH; | ||
} | ||
|
||
List<? extends ExpressionTree> arguments = tree.getArguments(); | ||
return describeMatch(tree, SuggestedFixes.removeElement(arguments.get(0), arguments, state)); | ||
} | ||
|
||
private static boolean isTypeDerivableFromContext(MethodInvocationTree tree, VisitorState state) { | ||
Tree parent = state.getPath().getParentPath().getLeaf(); | ||
switch (parent.getKind()) { | ||
case VARIABLE: | ||
return !ASTHelpers.hasNoExplicitType((VariableTree) parent, state) | ||
&& areSameType(tree, parent, state); | ||
case ASSIGNMENT: | ||
return areSameType(tree, parent, state); | ||
case RETURN: | ||
Tree context = state.findEnclosing(LambdaExpressionTree.class, MethodTree.class); | ||
return context instanceof MethodTree | ||
&& areSameType(tree, ((MethodTree) context).getReturnType(), state); | ||
default: | ||
return false; | ||
} | ||
} | ||
|
||
private static boolean areSameType(Tree treeA, Tree treeB, VisitorState state) { | ||
return ASTHelpers.isSameType(ASTHelpers.getType(treeA), ASTHelpers.getType(treeB), state); | ||
} | ||
} |
136 changes: 136 additions & 0 deletions
136
...ntrib/src/test/java/tech/picnic/errorprone/bugpatterns/MockitoMockClassReferenceTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
package tech.picnic.errorprone.bugpatterns; | ||
|
||
import com.google.errorprone.BugCheckerRefactoringTestHelper; | ||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; | ||
import com.google.errorprone.CompilationTestHelper; | ||
import org.junit.jupiter.api.Test; | ||
|
||
final class MockitoMockClassReferenceTest { | ||
@Test | ||
void identification() { | ||
CompilationTestHelper.newInstance(MockitoMockClassReference.class, getClass()) | ||
.addSourceLines( | ||
"A.java", | ||
"import static org.mockito.Mockito.mock;", | ||
"import static org.mockito.Mockito.spy;", | ||
"import static org.mockito.Mockito.withSettings;", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note to self: always check for more edge cases that we can test 😛. |
||
"", | ||
"import java.util.List;", | ||
"import java.util.Objects;", | ||
"import org.mockito.invocation.InvocationOnMock;", | ||
"", | ||
"class A {", | ||
" {", | ||
" Double d = Objects.requireNonNullElseGet(null, () -> mock(Double.class));", | ||
" Double d2 =", | ||
" Objects.requireNonNullElseGet(", | ||
" null,", | ||
" () -> {", | ||
" return mock(Double.class);", | ||
" });", | ||
" }", | ||
"", | ||
" void m() {", | ||
" Number variableMock = 42;", | ||
" // BUG: Diagnostic contains:", | ||
" variableMock = mock(Number.class);", | ||
" // BUG: Diagnostic contains:", | ||
" variableMock = mock(Number.class, \"name\");", | ||
" // BUG: Diagnostic contains:", | ||
" variableMock = mock(Number.class, InvocationOnMock::callRealMethod);", | ||
" // BUG: Diagnostic contains:", | ||
" variableMock = mock(Number.class, withSettings());", | ||
" variableMock = mock(Integer.class);", | ||
" variableMock = 42;", | ||
" // BUG: Diagnostic contains:", | ||
" List rawMock = mock(List.class);", | ||
" // BUG: Diagnostic contains:", | ||
" List<String> genericMock = mock(List.class);", | ||
" var varMock = mock(Integer.class);", | ||
" Class<? extends Number> numberType = Integer.class;", | ||
" Number variableTypeMock = mock(numberType);", | ||
" Object subtypeMock = mock(Integer.class);", | ||
"", | ||
" Number variableSpy = 42;", | ||
" // BUG: Diagnostic contains:", | ||
" variableSpy = spy(Number.class);", | ||
" variableSpy = spy(Integer.class);", | ||
" variableSpy = 42;", | ||
" // BUG: Diagnostic contains:", | ||
" List rawSpy = spy(List.class);", | ||
" // BUG: Diagnostic contains:", | ||
" List<String> genericSpy = spy(List.class);", | ||
" var varSpy = spy(Integer.class);", | ||
" Number variableTypeSpy = spy(numberType);", | ||
" Object subtypeSpy = spy(Integer.class);", | ||
" Object objectSpy = spy(new Object());", | ||
"", | ||
" Objects.hash(mock(Integer.class));", | ||
" Integer i = mock(mock(Integer.class));", | ||
" String s = new String(mock(String.class));", | ||
" }", | ||
"", | ||
" Double getDoubleMock() {", | ||
" return Objects.requireNonNullElseGet(", | ||
" null,", | ||
" () -> {", | ||
" return mock(Double.class);", | ||
" });", | ||
" }", | ||
"", | ||
" Integer getIntegerMock() {", | ||
" // BUG: Diagnostic contains:", | ||
" return mock(Integer.class);", | ||
" }", | ||
"", | ||
" <T> T getGenericMock(Class<T> clazz) {", | ||
" return mock(clazz);", | ||
" }", | ||
"", | ||
" Number getSubTypeMock() {", | ||
" return mock(Integer.class);", | ||
" }", | ||
"}") | ||
.doTest(); | ||
} | ||
|
||
@Test | ||
void replacement() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can simplify this test, since this fix isn't (so) context dependent. |
||
BugCheckerRefactoringTestHelper.newInstance(MockitoMockClassReference.class, getClass()) | ||
.addInputLines( | ||
"A.java", | ||
"import static org.mockito.Mockito.mock;", | ||
"import static org.mockito.Mockito.spy;", | ||
"import static org.mockito.Mockito.withSettings;", | ||
"", | ||
"import org.mockito.invocation.InvocationOnMock;", | ||
"", | ||
"class A {", | ||
" void m() {", | ||
" Number simpleMock = mock(Number.class);", | ||
" Number namedMock = mock(Number.class, \"name\");", | ||
" Number customAnswerMock = mock(Number.class, InvocationOnMock::callRealMethod);", | ||
" Number customSettingsMock = mock(Number.class, withSettings());", | ||
" Number simpleSpy = spy(Number.class);", | ||
" }", | ||
"}") | ||
.addOutputLines( | ||
"A.java", | ||
"import static org.mockito.Mockito.mock;", | ||
"import static org.mockito.Mockito.spy;", | ||
"import static org.mockito.Mockito.withSettings;", | ||
"", | ||
"import org.mockito.invocation.InvocationOnMock;", | ||
"", | ||
"class A {", | ||
" void m() {", | ||
" Number simpleMock = mock();", | ||
" Number namedMock = mock(\"name\");", | ||
" Number customAnswerMock = mock(InvocationOnMock::callRealMethod);", | ||
" Number customSettingsMock = mock(withSettings());", | ||
" Number simpleSpy = spy();", | ||
" }", | ||
"}") | ||
.doTest(TestMode.TEXT_MATCH); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There can be caveats when the passed argument is a variable that can lead into non-compilable/working-with-Mockito code, e.g. the following is odd and won't work:
There might be cases where we could still replace the variable, but I couldn't find an elegant way for it without going into the caveats. For example the trivial:
Feel free to play around and see if you find an elegant way.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I think it's fair to leave this out of scope.