|
| 1 | +/* |
| 2 | + * SonarQube Python Plugin |
| 3 | + * Copyright (C) 2011-2022 SonarSource SA |
| 4 | + * mailto:info AT sonarsource DOT com |
| 5 | + * |
| 6 | + * This program is free software; you can redistribute it and/or |
| 7 | + * modify it under the terms of the GNU Lesser General Public |
| 8 | + * License as published by the Free Software Foundation; either |
| 9 | + * version 3 of the License, or (at your option) any later version. |
| 10 | + * |
| 11 | + * This program is distributed in the hope that it will be useful, |
| 12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 14 | + * Lesser General Public License for more details. |
| 15 | + * |
| 16 | + * You should have received a copy of the GNU Lesser General Public License |
| 17 | + * along with this program; if not, write to the Free Software Foundation, |
| 18 | + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 19 | + */ |
| 20 | +package org.sonar.python.checks.tests; |
| 21 | + |
| 22 | +import java.util.Comparator; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Optional; |
| 25 | +import java.util.Set; |
| 26 | +import org.sonar.check.Rule; |
| 27 | +import org.sonar.plugins.python.api.PythonSubscriptionCheck; |
| 28 | +import org.sonar.plugins.python.api.SubscriptionContext; |
| 29 | +import org.sonar.plugins.python.api.symbols.Symbol; |
| 30 | +import org.sonar.plugins.python.api.symbols.Usage; |
| 31 | +import org.sonar.plugins.python.api.tree.ArgList; |
| 32 | +import org.sonar.plugins.python.api.tree.Argument; |
| 33 | +import org.sonar.plugins.python.api.tree.AssignmentStatement; |
| 34 | +import org.sonar.plugins.python.api.tree.CallExpression; |
| 35 | +import org.sonar.plugins.python.api.tree.Expression; |
| 36 | +import org.sonar.plugins.python.api.tree.Name; |
| 37 | +import org.sonar.plugins.python.api.tree.QualifiedExpression; |
| 38 | +import org.sonar.plugins.python.api.tree.RegularArgument; |
| 39 | +import org.sonar.plugins.python.api.tree.Tree; |
| 40 | +import org.sonar.plugins.python.api.types.InferredType; |
| 41 | +import org.sonar.python.tests.UnittestUtils; |
| 42 | +import org.sonar.python.tree.TreeUtils; |
| 43 | +import org.sonar.python.types.InferredTypes; |
| 44 | + |
| 45 | +import static org.sonar.plugins.python.api.types.BuiltinTypes.NONE_TYPE; |
| 46 | + |
| 47 | +@Rule(key = "S5845") |
| 48 | +public class AssertOnDissimilarTypesCheck extends PythonSubscriptionCheck { |
| 49 | + private static final String MESSAGE = "Change this assertion to not compare dissimilar types"; |
| 50 | + private static final String MESSAGE_SECONDARY = "Last assignment of \"%s\""; |
| 51 | + private static final Set<String> assertToCheckEquality = Set.of("assertEqual", "assertNotEqual"); |
| 52 | + private static final Set<String> assertToCheckIdentity = Set.of("assertIs", "assertIsNot"); |
| 53 | + private static final String FIRST_ARG_KEYWORD = "first"; |
| 54 | + private static final String SECOND_ARG_KEYWORD = "second"; |
| 55 | + |
| 56 | + @Override |
| 57 | + public void initialize(Context context) { |
| 58 | + context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, ctx -> { |
| 59 | + CallExpression callExpression = (CallExpression) ctx.syntaxNode(); |
| 60 | + if (!callExpression.callee().is(Tree.Kind.QUALIFIED_EXPR)) { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + QualifiedExpression qualifiedExpression = (QualifiedExpression) callExpression.callee(); |
| 65 | + if ((!(qualifiedExpression.qualifier().is(Tree.Kind.NAME) && ((Name) qualifiedExpression.qualifier()).name().equals("self"))) |
| 66 | + || !UnittestUtils.isWithinUnittestTestCase(qualifiedExpression)) { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + checkArguments(ctx, callExpression, qualifiedExpression); |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | + private static void checkArguments(SubscriptionContext ctx, CallExpression callExpression, QualifiedExpression qualifiedExpression) { |
| 75 | + boolean isAnAssertIdentity = assertToCheckIdentity.contains(qualifiedExpression.name().name()); |
| 76 | + boolean isAnAssertEquality = assertToCheckEquality.contains(qualifiedExpression.name().name()); |
| 77 | + |
| 78 | + if (!isAnAssertEquality && !isAnAssertIdentity) { |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + ArgList args = callExpression.argumentList(); |
| 83 | + if (args == null) { |
| 84 | + return; |
| 85 | + } |
| 86 | + |
| 87 | + List<Argument> arguments = args.arguments(); |
| 88 | + RegularArgument firstArg = TreeUtils.nthArgumentOrKeyword(0, FIRST_ARG_KEYWORD, arguments); |
| 89 | + RegularArgument secondArg = TreeUtils.nthArgumentOrKeyword(1, SECOND_ARG_KEYWORD, arguments); |
| 90 | + if (firstArg == null || secondArg == null) { |
| 91 | + return; |
| 92 | + } |
| 93 | + |
| 94 | + Expression left = firstArg.expression(); |
| 95 | + Expression right = secondArg.expression(); |
| 96 | + |
| 97 | + if (canArgumentsBeIdentical(left, right)) { |
| 98 | + return; |
| 99 | + } |
| 100 | + |
| 101 | + if (isAnAssertIdentity || !canArgumentsBeEqual(left, right)) { |
| 102 | + PreciseIssue issue = ctx.addIssue(args, message(left, right)); |
| 103 | + getLastAssignment(left).ifPresent(assign -> issue.secondary(assign, String.format(MESSAGE_SECONDARY, ((Name)left).name()))); |
| 104 | + getLastAssignment(right).ifPresent(assign -> issue.secondary(assign, String.format(MESSAGE_SECONDARY, ((Name)right).name()))); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + private static String message(Expression left, Expression right) { |
| 109 | + String leftTypeName = InferredTypes.typeName(left.type()); |
| 110 | + String rightTypeName = InferredTypes.typeName(right.type()); |
| 111 | + String message = MESSAGE; |
| 112 | + if (leftTypeName != null && rightTypeName != null) { |
| 113 | + message += " (" + leftTypeName + " and " + rightTypeName + ")"; |
| 114 | + } |
| 115 | + message += "."; |
| 116 | + return message; |
| 117 | + } |
| 118 | + |
| 119 | + private static Optional<AssignmentStatement> getLastAssignment(Expression expr) { |
| 120 | + if (!expr.is(Tree.Kind.NAME)) { |
| 121 | + return Optional.empty(); |
| 122 | + } |
| 123 | + |
| 124 | + Symbol symbol = ((Name) expr).symbol(); |
| 125 | + if (symbol == null) { |
| 126 | + return Optional.empty(); |
| 127 | + } |
| 128 | + |
| 129 | + Usage lastAssignment = symbol.usages().stream() |
| 130 | + .sorted(Comparator.comparingInt(u -> u.tree().firstToken().line())) |
| 131 | + .takeWhile(usage -> usage != ((Name) expr).usage()) |
| 132 | + .filter(usage -> usage.kind() == Usage.Kind.ASSIGNMENT_LHS) |
| 133 | + .reduce((first, second) -> second) |
| 134 | + .orElse(null); |
| 135 | + |
| 136 | + return Optional.ofNullable(lastAssignment) |
| 137 | + .map(assignment -> (AssignmentStatement) TreeUtils.firstAncestorOfKind(assignment.tree(), Tree.Kind.ASSIGNMENT_STMT)); |
| 138 | + } |
| 139 | + |
| 140 | + private static boolean canArgumentsBeIdentical(Expression left, Expression right) { |
| 141 | + return left.type().isIdentityComparableWith(right.type()) || left.type().canOnlyBe(NONE_TYPE) || right.type().canOnlyBe(NONE_TYPE); |
| 142 | + } |
| 143 | + |
| 144 | + private static boolean canArgumentsBeEqual(Expression left, Expression right) { |
| 145 | + String leftCategory = InferredTypes.getBuiltinCategory(left.type()); |
| 146 | + String rightCategory = InferredTypes.getBuiltinCategory(right.type()); |
| 147 | + boolean leftCanImplementEqOrNe = canImplementEqOrNe(left); |
| 148 | + boolean rightCanImplementEqOrNe = canImplementEqOrNe(right); |
| 149 | + |
| 150 | + if ((leftCategory != null && leftCategory.equals(rightCategory))) { |
| 151 | + return true; |
| 152 | + } |
| 153 | + |
| 154 | + return (leftCanImplementEqOrNe || rightCanImplementEqOrNe) |
| 155 | + && (leftCategory == null || rightCategory == null) |
| 156 | + && (leftCategory == null || rightCanImplementEqOrNe) |
| 157 | + && (rightCategory == null || leftCanImplementEqOrNe); |
| 158 | + } |
| 159 | + |
| 160 | + private static boolean canImplementEqOrNe(Expression expression) { |
| 161 | + InferredType type = expression.type(); |
| 162 | + return type.canHaveMember("__eq__") || type.canHaveMember("__ne__"); |
| 163 | + } |
| 164 | + |
| 165 | + @Override |
| 166 | + public CheckScope scope() { |
| 167 | + return CheckScope.ALL; |
| 168 | + } |
| 169 | +} |
0 commit comments