def test_raises_cyclic_reference(self, method):
        """Ensure pytest.raises does not leave a reference cycle (#1965)."""
        import gc

        class T:
            def __call__(self):
                raise ValueError

        t = T()
        refcount = len(gc.get_referrers(t))

        if method == "function":
            pytest.raises(ValueError, t)
        elif method == "function_match":
            pytest.raises(ValueError, t).match("^$")
        elif method == "with":
            with pytest.raises(ValueError):
                t()
        elif method == "with_raisesexc":
            with pytest.RaisesExc(ValueError):
                t()
        elif method == "with_group":
            with pytest.RaisesGroup(ValueError, allow_unwrapped=True):
                t()
        else:  # pragma: no cover
            raise AssertionError("bad parametrization")

        # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()
        assert sys.exc_info() == (None, None, None)

        assert refcount == len(gc.get_referrers(t))
Ensure pytest.raises does not leave a reference cycle (#1965).
testing/python/raises.py