Skip to content

Commit

Permalink
Fix unguarded == comparison in fixtures.
Browse files Browse the repository at this point in the history
Closes: #6497
  • Loading branch information
kohr-h committed Jan 22, 2020
1 parent 85df6bb commit fb3975f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 4 additions & 0 deletions changelog/6497.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix bug in the comparison of request key with cached key in fixture.

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`.
The implemented fix first compares using ``is``, and guards the subsequent ``==`` comparison against `TypeError` and `AttributeError`.
12 changes: 11 additions & 1 deletion src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,17 @@ def execute(self, request):
cached_result = getattr(self, "cached_result", None)
if cached_result is not None:
result, cache_key, err = cached_result
if my_cache_key == cache_key:
# comparison with `==` can fail, e.g. for NumPy arrays, so we try `is`
# first and guard the subsequent `==` comparison
cache_valid = False
if my_cache_key is cache_key:
cache_valid = True
else:
try:
cache_valid = bool(my_cache_key == cache_key)
except (TypeError, ValueError):
pass
if cache_valid:
if err is not None:
_, val, tb = err
raise val.with_traceback(tb)
Expand Down

0 comments on commit fb3975f

Please sign in to comment.