Skip to content

Commit 2f22b31

Browse files
SONARPY-685 Fix false-positive with unformatted logger messages (#780)
1 parent 6c00a77 commit 2f22b31

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

python-checks/src/main/java/org/sonar/python/checks/StringFormatCorrectnessCheck.java

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -128,20 +128,24 @@ private static void checkLoggerLog(SubscriptionContext ctx, CallExpression callE
128128
return;
129129
}
130130

131+
if (arguments.size() == 1) {
132+
// If the logger is called without additional arguments, the message will not be parsed as a string format.
133+
// However, we still want to report if we see a valid string format without any format arguments.
134+
StringFormat.createFromPrintfStyle(IGNORE_SYNTAX_ERRORS, literal.trimmedQuotesValue()).ifPresent(format -> {
135+
if (format.numExpectedArguments() != 0) {
136+
reportIssue(ctx, firstArgument, literal, "Add argument(s) corresponding to the message's replacement field(s).");
137+
}
138+
});
139+
return;
140+
}
141+
131142
Optional<StringFormat> formatOptional = StringFormat.createFromPrintfStyle(
132143
syntaxIssueReporter(ctx, firstArgument, literal), literal.trimmedQuotesValue());
133144
if (!formatOptional.isPresent()) {
134145
return;
135146
}
136147

137148
StringFormat format = formatOptional.get();
138-
if (arguments.size() == 1) {
139-
if (format.numExpectedArguments() != 0) {
140-
reportIssue(ctx, firstArgument, literal, "Add argument(s) corresponding to the message's replacement field(s).");
141-
}
142-
return;
143-
}
144-
145149
Token argIssueFrom = arguments.get(1).firstToken();
146150
Token argIssueTo = arguments.get(arguments.size() - 1).lastToken();
147151

python-checks/src/test/resources/checks/stringFormatCorrectness.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ def logger_format():
7979
logging.error("%d", *t) # FN
8080
logging.error(msg="%d", kw1='42')
8181

82+
logging.error("This is valid % % %") # Ok
83+
8284
import logging as renamed_logging
8385
renamed_logging.error("Foo %s", "Bar", 'Too many') # Noncompliant
8486

0 commit comments

Comments
 (0)