Skip to content

Commit

Permalink
SONARPY-1338 Fix FP on S5655 when the argument is a valid TypedDict (S…
Browse files Browse the repository at this point in the history
  • Loading branch information
sallaigy authored Apr 14, 2023
1 parent 0b6180e commit 2745be6
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ public void visitReturnStatement(ReturnStatement returnStatement) {
Expression expression = expressions.get(0);
InferredType inferredType = expression.type();
if (returnType.mustBeOrExtend("typing.TypedDict")) {
// Avoid FPs for TypedDict
// TODO SONARPY-1340: This is a workaround to avoid FPs with TypedDict, however, this produces false-negatives. We should have a more
// fine-grained solution to check dictionaries against TypedDict.
return;
}

Expand Down
11 changes: 10 additions & 1 deletion python-checks/src/test/resources/checks/argumentType.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import _heapq
import imaplib
from unittest.mock import Mock
from typing import Dict, Tuple, Set
from typing import Dict, Tuple, Set, TypedDict
from collections import OrderedDict, Counter
from emoji import emojize

Expand Down Expand Up @@ -130,6 +130,15 @@ def with_tuple(a : Tuple[int]): ...
with_tuple((42, 43)) # OK
with_tuple(42) # Noncompliant

class Movie(TypedDict):
name: str
year: int

def with_typed_dict(movie: Movie): ...
with_typed_dict({'name': "Ad Astra", 'year': 2019}) # Ok
with_typed_dict({'name': "Ad Astra", 'year': 2019, 'other': 'foo'}) # FN


def edge_cases():
ambiguous = 42
def ambiguous(a: str): ...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ public class InferredTypes {
// str <=> bytes equivalence only for Python2
HARDCODED_COMPATIBLE_TYPES.put(BuiltinTypes.STR, new HashSet<>(Arrays.asList(UNICODE, BYTES)));
HARDCODED_COMPATIBLE_TYPES.put(BYTES, new HashSet<>(Collections.singletonList(BuiltinTypes.STR)));
// TODO SONARPY-1340: This is a workaround to avoid FPs with TypedDict, however, this produces false-negatives. We should have a more
// fine-grained solution to check dictionaries against TypedDict.
HARDCODED_COMPATIBLE_TYPES.put(BuiltinTypes.DICT, Set.of("typing.TypedDict"));
}

protected static final Map<String, String> BUILTINS_TYPE_CATEGORY = new HashMap<>();
Expand Down

0 comments on commit 2745be6

Please sign in to comment.