Skip to content

Commit

Permalink
Remove unnecessary numpy import (#9798)
Browse files Browse the repository at this point in the history
Fix #9726
  • Loading branch information
kianelbo committed Mar 21, 2022
1 parent 6a6a32c commit 3297bb2
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 17 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -185,6 +185,7 @@ Katerina Koukiou
Keri Volans
Kevin Cox
Kevin J. Foley
Kian Eliasi
Kian-Meng Ang
Kodi B. Arfer
Kojo Idrissa
Expand Down
1 change: 1 addition & 0 deletions changelog/9726.bugfix.rst
@@ -0,0 +1 @@
An unnecessary ``numpy`` import inside :func:`pytest.approx` was removed.
3 changes: 1 addition & 2 deletions src/_pytest/python_api.py
Expand Up @@ -319,7 +319,6 @@ def __repr__(self) -> str:

def _repr_compare(self, other_side: Sequence[float]) -> List[str]:
import math
import numpy as np

if len(self.expected) != len(other_side):
return [
Expand All @@ -340,7 +339,7 @@ def _repr_compare(self, other_side: Sequence[float]) -> List[str]:
abs_diff = abs(approx_value.expected - other_value)
max_abs_diff = max(max_abs_diff, abs_diff)
if other_value == 0.0:
max_rel_diff = np.inf
max_rel_diff = math.inf
else:
max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))
different_ids.append(i)
Expand Down
32 changes: 17 additions & 15 deletions testing/python/approx.py
Expand Up @@ -92,9 +92,7 @@ def do_assert(lhs, rhs, expected_message, verbosity_level=0):


class TestApprox:
def test_error_messages(self, assert_approx_raises_regex):
np = pytest.importorskip("numpy")

def test_error_messages_native_dtypes(self, assert_approx_raises_regex):
assert_approx_raises_regex(
2.0,
1.0,
Expand Down Expand Up @@ -135,6 +133,22 @@ def test_error_messages(self, assert_approx_raises_regex):
],
)

# Specific test for comparison with 0.0 (relative diff will be 'inf')
assert_approx_raises_regex(
[0.0],
[1.0],
[
r" comparison failed. Mismatched elements: 1 / 1:",
rf" Max absolute difference: {SOME_FLOAT}",
r" Max relative difference: inf",
r" Index \| Obtained\s+\| Expected ",
rf"\s*0\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
],
)

def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex):
np = pytest.importorskip("numpy")

a = np.linspace(0, 100, 20)
b = np.linspace(0, 100, 20)
a[10] += 0.5
Expand Down Expand Up @@ -175,18 +189,6 @@ def test_error_messages(self, assert_approx_raises_regex):
)

# Specific test for comparison with 0.0 (relative diff will be 'inf')
assert_approx_raises_regex(
[0.0],
[1.0],
[
r" comparison failed. Mismatched elements: 1 / 1:",
rf" Max absolute difference: {SOME_FLOAT}",
r" Max relative difference: inf",
r" Index \| Obtained\s+\| Expected ",
rf"\s*0\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
],
)

assert_approx_raises_regex(
np.array([0.0]),
np.array([1.0]),
Expand Down

0 comments on commit 3297bb2

Please sign in to comment.