float-equality
An assertion compares floating-point values exactly.
- Group
- Tests
- Runs
- On by default
- Level
- note
- Reads
- Tests
- Fix
- None: the tolerance is the author's to choose
- Defends
- Resilience: the test fails only when the code is broken.
Why
One side of an equality assertion is a floating-point constant, so the test fails on a rounding difference that is not a bug. An assertion or matcher that compares within a tolerance, such as assertAlmostEqual, toBeCloseTo, or pytest.approx, and an assertion given a tolerance after its two values, are not reported.
The fix, as Ur suggests it: compare within a tolerance, with the framework's approximate assertion.
For agents
Compare floating-point values within a tolerance, with the framework's approximate assertion, never for exact equality.
Example
shop/tax.pydef with_tax(price, rate):
return price * (1 + rate)
tests/test_tax.pyfrom shop.tax import with_tax
def test_adds_tax():
assert with_tax(10, 0.07) == 10.7
$ ur lint --rule float-equality
note[float-equality]: `assert` in test `test_adds_tax` compares a floating-point value exactly, so it fails on a rounding difference
--> ./tests/test_tax.py:5:5 test `test_adds_tax`
= hint: compare within a tolerance, with the framework's approximate assertion
= see: TotT: Floating-Point Comparison, Google Testing Blog (2008-10-16), https://testing.googleblog.com/2008/10/tott-floating-point-comparison.html
0 clone classes and 1 test finding in 2 files
Source
TotT: Floating-Point Comparison, Google Testing Blog (2008-10-16).