Open kunaltyagi opened 9 months ago
What would you suggest as the correct fix?
If the assert doesn't have a message, a generic message can be used alongside the assert condition. Eg: for assert x != y
if x == y:
msg = f"Expected: 'x != y', found: x = {x}, y = {y}"
raise ValueError(msg)
If there's a message accompanying the assert, eg: assert x != y, "some message"
if x == y:
msg = "some message"
raise ValueError(msg)
This is what I've observed people replace their code with when faced with this error. The most often item people might want to change is the error type but this default would more than suffice the 80-20 rule
AssertionError
would seem the more natural substitution, as already done when auto-fixing B011
.
Sure, that does make more sense
If this is implemented, might it wreak havoc on tests?
I don't think so. Asserts in tests are ignored in the projects I've used ruff with
Huh, weird! I had to go out of my way to explicitly declare the following in my pyproject.toml
[tool.ruff.per-file-ignores]
"*test_*.py" = ["S101"]
Without that, I get loads of errors about the use of "assert" in tests.
We don't disable any specific rules in tests by default, so something like what you have there @cosmojg is expected and correct.
Ah, got it, thanks for the clarification! That makes sense.
It's an interesting philosophical question whether tests are part of the language itself or merely a product thereof. Regardless, it seems that bandit
maintains the same behavior upstream so the point is moot. I suppose some users might prefix scripts with "test" to mean that they are tests in some other sense. Also, the Python interpreter itself doesn't differentiate even though the standard library does (see: unittest
), and at the end of the day, explicit behavior generally causes fewer problems than implicit behavior.
All of that said, I agree that autofixing with an AssertionError
exception is the way to go!
@cosmojg I found that I was wrong in my guess and all the projects (I work(ed) on) all had the following common items:
[tool.ruff.per-file-ignores]
# Tests can use magic values, assertions, and relative imports
"tests/**/*" = ["PLR2004", "S101", "TID252"]
Has there been any progress on this?
code:
assert x != 0
ruff: 0.0.291 command:ruff check --fix --fixable S101 .
error:S101 Use of
assertdetected
This is an easy fix to substitute in the code specially when opted-in by the developer (if not automatically)