diff --git a/changelog/6497.bugfix.rst b/changelog/6497.bugfix.rst new file mode 100644 index 00000000000..d1e824b66bc --- /dev/null +++ b/changelog/6497.bugfix.rst @@ -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`. diff --git a/src/_pytest/fixtures.py b/src/_pytest/fixtures.py index bae3d071674..b8976798750 100644 --- a/src/_pytest/fixtures.py +++ b/src/_pytest/fixtures.py @@ -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)