swallowed-failure
A handler catches the failure of the assertion it guards.
- Group
- Tests
- Runs
- On by default
- Level
- warning
- Reads
- Tests
- Fix
- None: which exception the test expects is the author's to say
- Defends
- Fidelity: when the code is broken, the test fails.
Why
The test asserts inside a try whose handler catches every exception, or the assertion's own, and neither raises again nor fails the test, so the test passes when the assertion does not hold. A handler that names a narrower class, and one that fails the test itself, are not reported.
The fix, as Ur suggests it: move the assertion out of the try, or catch only the exception the test expects.
For agents
Never catch every exception around a test's assertions; catch only the exception the test expects, and assert outside the handler.
Example
shop/prices.pydef discounted(price, percent):
return price - price * percent // 100
tests/test_prices.pyfrom shop.prices import discounted
def test_discount_is_applied():
try:
total = discounted(200, 25)
assert total == 150
except Exception:
pass
$ ur lint --rule swallowed-failure
warning[swallowed-failure]: a handler in test `test_discount_is_applied` catches the failure of the assertion it guards, so the test passes when the assertion fails
--> ./tests/test_prices.py:5:5-9 test `test_discount_is_applied`
= hint: move the assertion out of the `try`, or catch only the exception the test expects
= see: Cost-Benefit Analysis of a Test, Google Testing Blog (2008-03-12), https://testing.googleblog.com/2008/03/cost-benefit-analysis-of-test.html
0 clone classes and 1 test finding in 2 files
Source
Cost-Benefit Analysis of a Test, Google Testing Blog (2008-03-12).