|
| 1 | +/* |
| 2 | + * Copyright 2024 The Error Prone Authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.google.errorprone.bugpatterns; |
| 17 | + |
| 18 | +import static com.google.common.collect.Iterables.getLast; |
| 19 | +import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; |
| 20 | +import static com.google.errorprone.matchers.Description.NO_MATCH; |
| 21 | +import static com.google.errorprone.matchers.Matchers.instanceMethod; |
| 22 | +import static com.google.errorprone.matchers.Matchers.staticMethod; |
| 23 | +import static com.google.errorprone.util.ASTHelpers.getReceiver; |
| 24 | +import static com.google.errorprone.util.ASTHelpers.getStartPosition; |
| 25 | +import static com.google.errorprone.util.ASTHelpers.getSymbol; |
| 26 | +import static com.google.errorprone.util.ASTHelpers.hasAnnotation; |
| 27 | +import static com.google.errorprone.util.ASTHelpers.isSameType; |
| 28 | +import static java.lang.String.format; |
| 29 | + |
| 30 | +import com.google.common.collect.ImmutableMap; |
| 31 | +import com.google.common.collect.ImmutableSet; |
| 32 | +import com.google.errorprone.BugPattern; |
| 33 | +import com.google.errorprone.VisitorState; |
| 34 | +import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; |
| 35 | +import com.google.errorprone.fixes.SuggestedFix; |
| 36 | +import com.google.errorprone.fixes.SuggestedFixes; |
| 37 | +import com.google.errorprone.matchers.Description; |
| 38 | +import com.google.errorprone.matchers.Matcher; |
| 39 | +import com.sun.source.tree.AssignmentTree; |
| 40 | +import com.sun.source.tree.CompilationUnitTree; |
| 41 | +import com.sun.source.tree.ExpressionTree; |
| 42 | +import com.sun.source.tree.MethodInvocationTree; |
| 43 | +import com.sun.source.tree.Tree; |
| 44 | +import com.sun.source.tree.VariableTree; |
| 45 | +import com.sun.source.util.TreePath; |
| 46 | +import com.sun.source.util.TreePathScanner; |
| 47 | +import com.sun.tools.javac.code.Symbol.VarSymbol; |
| 48 | + |
| 49 | +/** A BugPattern; see the summary. */ |
| 50 | +@BugPattern( |
| 51 | + severity = WARNING, |
| 52 | + summary = "Prefer using when/thenReturn over doReturn/when for additional type safety.") |
| 53 | +public final class MockitoDoSetup extends BugChecker implements CompilationUnitTreeMatcher { |
| 54 | + @Override |
| 55 | + public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { |
| 56 | + ImmutableSet<VarSymbol> spies = findSpies(state); |
| 57 | + new SuppressibleTreePathScanner<Void, Void>(state) { |
| 58 | + |
| 59 | + @Override |
| 60 | + public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { |
| 61 | + handle(tree); |
| 62 | + return super.visitMethodInvocation(tree, null); |
| 63 | + } |
| 64 | + |
| 65 | + private void handle(MethodInvocationTree tree) { |
| 66 | + if (!DO_STUBBER.matches(tree, state)) { |
| 67 | + return; |
| 68 | + } |
| 69 | + TreePath whenPath = getCurrentPath().getParentPath().getParentPath(); |
| 70 | + Tree whenCall = whenPath.getLeaf(); |
| 71 | + if (!(whenCall instanceof MethodInvocationTree) |
| 72 | + || !INSTANCE_WHEN.matches((MethodInvocationTree) whenCall, state)) { |
| 73 | + return; |
| 74 | + } |
| 75 | + if (isSpy(((MethodInvocationTree) whenCall).getArguments().get(0))) { |
| 76 | + return; |
| 77 | + } |
| 78 | + Tree mockedMethod = whenPath.getParentPath().getParentPath().getLeaf(); |
| 79 | + |
| 80 | + if (!(mockedMethod instanceof MethodInvocationTree)) { |
| 81 | + return; |
| 82 | + } |
| 83 | + if (isSameType( |
| 84 | + getSymbol((MethodInvocationTree) mockedMethod).getReturnType(), |
| 85 | + state.getSymtab().voidType, |
| 86 | + state)) { |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + SuggestedFix.Builder fix = SuggestedFix.builder(); |
| 91 | + var when = SuggestedFixes.qualifyStaticImport("org.mockito.Mockito.when", fix, state); |
| 92 | + fix.replace(((MethodInvocationTree) whenCall).getMethodSelect(), when) |
| 93 | + .replace(state.getEndPosition(whenCall) - 1, state.getEndPosition(whenCall), "") |
| 94 | + .postfixWith( |
| 95 | + mockedMethod, |
| 96 | + format( |
| 97 | + ").%s(%s)", |
| 98 | + NAME_MAPPINGS.get(getSymbol(tree).getSimpleName().toString()), |
| 99 | + getParameterSource(tree, state))); |
| 100 | + |
| 101 | + state.reportMatch(describeMatch(tree, fix.build())); |
| 102 | + } |
| 103 | + |
| 104 | + private boolean isSpy(ExpressionTree tree) { |
| 105 | + var symbol = getSymbol(tree); |
| 106 | + return symbol != null |
| 107 | + && (spies.contains(symbol) || hasAnnotation(symbol, "org.mockito.Spy", state)); |
| 108 | + } |
| 109 | + }.scan(state.getPath(), null); |
| 110 | + return NO_MATCH; |
| 111 | + } |
| 112 | + |
| 113 | + private static String getParameterSource(MethodInvocationTree tree, VisitorState state) { |
| 114 | + return state |
| 115 | + .getSourceCode() |
| 116 | + .subSequence( |
| 117 | + getStartPosition(tree.getArguments().get(0)), |
| 118 | + state.getEndPosition(getLast(tree.getArguments()))) |
| 119 | + .toString(); |
| 120 | + } |
| 121 | + |
| 122 | + private static ImmutableSet<VarSymbol> findSpies(VisitorState state) { |
| 123 | + // NOTES: This is extremely conservative in at least two ways. |
| 124 | + // 1) We ignore an entire mock if _any_ method is mocked to throw, not just the relevant method. |
| 125 | + // 2) We could still refactor if the thenThrow comes _after_, or if the _only_ call is |
| 126 | + // thenThrow. |
| 127 | + ImmutableSet.Builder<VarSymbol> spiesOrThrows = ImmutableSet.builder(); |
| 128 | + new TreePathScanner<Void, Void>() { |
| 129 | + @Override |
| 130 | + public Void visitVariable(VariableTree tree, Void unused) { |
| 131 | + if (tree.getInitializer() != null && SPY.matches(tree.getInitializer(), state)) { |
| 132 | + spiesOrThrows.add(getSymbol(tree)); |
| 133 | + } |
| 134 | + return super.visitVariable(tree, null); |
| 135 | + } |
| 136 | + |
| 137 | + @Override |
| 138 | + public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { |
| 139 | + if (DO_THROW.matches(tree, state)) { |
| 140 | + var whenCall = getCurrentPath().getParentPath().getParentPath().getLeaf(); |
| 141 | + if ((whenCall instanceof MethodInvocationTree) |
| 142 | + && INSTANCE_WHEN.matches((MethodInvocationTree) whenCall, state)) { |
| 143 | + var whenTarget = getSymbol(((MethodInvocationTree) whenCall).getArguments().get(0)); |
| 144 | + if (whenTarget instanceof VarSymbol) { |
| 145 | + spiesOrThrows.add((VarSymbol) whenTarget); |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + if (THEN_THROW.matches(tree, state)) { |
| 150 | + var receiver = getReceiver(tree); |
| 151 | + if (STATIC_WHEN.matches(receiver, state)) { |
| 152 | + var mock = getReceiver(((MethodInvocationTree) receiver).getArguments().get(0)); |
| 153 | + var mockSymbol = getSymbol(mock); |
| 154 | + if (mockSymbol instanceof VarSymbol) { |
| 155 | + spiesOrThrows.add((VarSymbol) mockSymbol); |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + return super.visitMethodInvocation(tree, null); |
| 160 | + } |
| 161 | + |
| 162 | + @Override |
| 163 | + public Void visitAssignment(AssignmentTree tree, Void unused) { |
| 164 | + if (SPY.matches(tree.getExpression(), state)) { |
| 165 | + var symbol = getSymbol(tree.getVariable()); |
| 166 | + if (symbol instanceof VarSymbol) { |
| 167 | + spiesOrThrows.add((VarSymbol) symbol); |
| 168 | + } |
| 169 | + } |
| 170 | + return super.visitAssignment(tree, null); |
| 171 | + } |
| 172 | + }.scan(state.getPath().getCompilationUnit(), null); |
| 173 | + return spiesOrThrows.build(); |
| 174 | + } |
| 175 | + |
| 176 | + private static final ImmutableMap<String, String> NAME_MAPPINGS = |
| 177 | + ImmutableMap.of( |
| 178 | + "doAnswer", "thenAnswer", |
| 179 | + "doReturn", "thenReturn", |
| 180 | + "doThrow", "thenThrow"); |
| 181 | + private static final Matcher<ExpressionTree> DO_STUBBER = |
| 182 | + staticMethod().onClass("org.mockito.Mockito").namedAnyOf(NAME_MAPPINGS.keySet()); |
| 183 | + |
| 184 | + private static final Matcher<ExpressionTree> INSTANCE_WHEN = |
| 185 | + instanceMethod().onDescendantOf("org.mockito.stubbing.Stubber").named("when"); |
| 186 | + |
| 187 | + private static final Matcher<ExpressionTree> SPY = |
| 188 | + staticMethod().onClass("org.mockito.Mockito").named("spy"); |
| 189 | + |
| 190 | + private static final Matcher<ExpressionTree> DO_THROW = |
| 191 | + staticMethod().onClass("org.mockito.Mockito").named("doThrow"); |
| 192 | + |
| 193 | + private static final Matcher<ExpressionTree> STATIC_WHEN = |
| 194 | + staticMethod().onClass("org.mockito.Mockito").named("when"); |
| 195 | + |
| 196 | + private static final Matcher<ExpressionTree> THEN_THROW = |
| 197 | + instanceMethod().onDescendantOf("org.mockito.stubbing.OngoingStubbing").named("thenThrow"); |
| 198 | +} |
0 commit comments