unittest2pytest icon indicating copy to clipboard operation
unittest2pytest copied to clipboard

`pytest.approx` for `self.assertAlmostEqual`

Open janosh opened this issue 3 years ago • 1 comments

The replacement for self.assertAlmostEqual(3, 3.0) is round(abs(3 - 3.0), 7) == 0.

How about replacing it with pytest.approx(3) == 3.0 instead? [pytest docs]

janosh avatar Aug 06 '22 02:08 janosh

One big advantage of pytest.appox is that it correctly handles iterables like lists and tuples. Example:

xy = (1.0, 2.0)
assert round(abs(xy - (1, 2)), 7) == 0

fails with

TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

whereas


xy = (1.0, 2.0)
assert pytest.approx(xy) == (1, 2)

passes.

janosh avatar Aug 06 '22 02:08 janosh