Skip to content

Commit fb3975f

Browse files
committed
Fix unguarded == comparison in fixtures.
Closes: #6497
1 parent 85df6bb commit fb3975f

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

changelog/6497.bugfix.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix bug in the comparison of request key with cached key in fixture.
2+
3+
A construct ``if key == cached_key:`` can fail either because ``==`` is explicitly disallowed, or for, e.g., NumPy arrays, where the result of ``a == b`` cannot generally be converted to `bool`.
4+
The implemented fix first compares using ``is``, and guards the subsequent ``==`` comparison against `TypeError` and `AttributeError`.

src/_pytest/fixtures.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -894,7 +894,17 @@ def execute(self, request):
894894
cached_result = getattr(self, "cached_result", None)
895895
if cached_result is not None:
896896
result, cache_key, err = cached_result
897-
if my_cache_key == cache_key:
897+
# comparison with `==` can fail, e.g. for NumPy arrays, so we try `is`
898+
# first and guard the subsequent `==` comparison
899+
cache_valid = False
900+
if my_cache_key is cache_key:
901+
cache_valid = True
902+
else:
903+
try:
904+
cache_valid = bool(my_cache_key == cache_key)
905+
except (TypeError, ValueError):
906+
pass
907+
if cache_valid:
898908
if err is not None:
899909
_, val, tb = err
900910
raise val.with_traceback(tb)

0 commit comments

Comments
 (0)