Skip to content

Commit

Permalink
Disallow unordered sequences in pytest.approx
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoddemus committed Feb 23, 2022
1 parent 9af3e23 commit 87dfbb4
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/9692.improvement.rst
@@ -0,0 +1 @@
:func:`pytest.approx` now raises a :class:`TypeError` when given an unordered sequence (such as :class:`set`).
7 changes: 5 additions & 2 deletions src/_pytest/python_api.py
Expand Up @@ -311,7 +311,7 @@ class ApproxSequencelike(ApproxBase):

def __repr__(self) -> str:
seq_type = type(self.expected)
if seq_type not in (tuple, list, set):
if seq_type not in (tuple, list):
seq_type = list
return "approx({!r})".format(
seq_type(self._approx_scalar(x) for x in self.expected)
Expand Down Expand Up @@ -372,6 +372,9 @@ def _yield_comparisons(self, actual):

def _check_type(self) -> None:
__tracebackhide__ = True
if not isinstance(self.expected, Sequence):
msg = f"pytest.approx() only supports ordered sequences, but got: {repr(self.expected)}"
raise TypeError(msg)
for index, x in enumerate(self.expected):
if isinstance(x, type(self.expected)):
msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}"
Expand Down Expand Up @@ -515,7 +518,7 @@ class ApproxDecimal(ApproxScalar):


def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
"""Assert that two numbers (or two sets of numbers) are equal to each other
"""Assert that two numbers (or two ordered sequences of numbers) are equal to each other
within some tolerance.
Due to the :std:doc:`tutorial/floatingpoint`, numbers that we
Expand Down
5 changes: 5 additions & 0 deletions testing/python/approx.py
Expand Up @@ -868,3 +868,8 @@ def __len__(self):

expected = MySizedIterable()
assert [1, 2, 3, 4] == approx(expected)

def test_allow_ordered_sequences_only(self) -> None:
"""pytest.approx() should raise an error on unordered sequences (#9692)."""
with pytest.raises(TypeError, match="only supports ordered sequences"):
assert {1, 2, 3} == approx({1, 2, 3})

0 comments on commit 87dfbb4

Please sign in to comment.