When working with floating-point numbers in tests, comparing exact equality often fails due to inherent precision limitations, which results in flaky or unreliable tests.
You can use pytest.approx()
to compare floating-point numbers with a reasonable tolerance, making your tests more robust and readable.
Here’s a code example to show its usefulness:
# Without pytest.approx - test fails
def test_calculation_without_approx():
result = 0.1 + 0.2
assert result == 0.3 # This fails!
# With pytest.approx - test passes
def test_calculation_with_approx():
result = 0.1 + 0.2
assert result == pytest.approx(0.3) # This passes!
# Works with sequences too
def test_list_of_floats():
results = [0.1 + 0.2, 0.2 + 0.4]
expected = [0.3, 0.6]
assert results == pytest.approx(expected)
In these examples:
- The first test fails because 0.1 + 0.2 in floating-point arithmetic doesn’t exactly equal 0.3.
- The second test passes because
pytest.approx()
allows for a small tolerance in the comparison (by default, relative tolerance of 1e-6). - The third example shows how it works with lists of numbers, making it convenient for comparing multiple results at once.