diff --git a/AUTHORS b/AUTHORS index eb3c016a570..fe96e0d79b3 100644 --- a/AUTHORS +++ b/AUTHORS @@ -59,6 +59,7 @@ Denis Kirisov Diego Russo Dmitry Dygalo Dmitry Pribysh +Drew Ackerman Duncan Betts Edison Gustavo Muenz Edoardo Batini diff --git a/_pytest/python_api.py b/_pytest/python_api.py index 8e09a4a6fd3..bfd5f137274 100644 --- a/_pytest/python_api.py +++ b/_pytest/python_api.py @@ -443,12 +443,16 @@ def approx(expected, rel=None, abs=None, nan_ok=False): # This has the advantage that it made it easy to support mapping types # (i.e. dict). The old code accepted mapping types, but would only compare # their keys, which is probably not what most people would expect. - - if _is_numpy_array(expected): + if isinstance(expected, String): + raise TypeError("Strings can not be approximated") + elif _is_numpy_array(expected): cls = ApproxNumpy elif isinstance(expected, Mapping): cls = ApproxMapping elif isinstance(expected, Sequence) and not isinstance(expected, String): + for value in expected: + if isinstance(value, (Sequence, String, Mapping)): + raise TypeError("Sequence contained a value that was not float or int") cls = ApproxSequence elif isinstance(expected, Decimal): cls = ApproxDecimal diff --git a/changelog/3473.bugfix.rst b/changelog/3473.bugfix.rst new file mode 100644 index 00000000000..508e63c08e8 --- /dev/null +++ b/changelog/3473.bugfix.rst @@ -0,0 +1,2 @@ +``pytest.approx`` does not handle strings, but this was not easily apparent so it now raises a ``TypeError`` when a string is passed in as the expected argument. +``pytest.approx`` did not check all elements in a sequence to make sure they were valid type, a ``TypeError`` is now raised when an invalid element is in a sequence. \ No newline at end of file diff --git a/testing/python/approx.py b/testing/python/approx.py index 9ca21bdf8e9..acd1aa3ef78 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -243,6 +243,10 @@ def test_int(self): assert approx(x, rel=5e-6, abs=0) == a assert approx(x, rel=5e-7, abs=0) != a + def test_string(self): + with pytest.raises(TypeError): + approx('abc') + def test_decimal(self): within_1e6 = [ (Decimal('1.000001'), Decimal('1.0')),