diff --git a/changelog/4192.bugfix.rst b/changelog/4192.bugfix.rst new file mode 100644 index 000000000..86ed95360 --- /dev/null +++ b/changelog/4192.bugfix.rst @@ -0,0 +1 @@ +Fix filename reported by ``warnings.warn`` when using ``recwarn`` under python2. diff --git a/src/_pytest/recwarn.py b/src/_pytest/recwarn.py index 5adc42d26..8738fe0b8 100644 --- a/src/_pytest/recwarn.py +++ b/src/_pytest/recwarn.py @@ -158,7 +158,18 @@ class WarningsRecorder(warnings.catch_warnings): def warn(*args, **kwargs): kwargs.setdefault("stacklevel", 1) kwargs["stacklevel"] += 1 - return self._saved_warn(*args, **kwargs) + + # emulate resetting the warn registry + f_globals = sys._getframe(kwargs["stacklevel"] - 1).f_globals + if "__warningregistry__" in f_globals: + orig = f_globals["__warningregistry__"] + f_globals["__warningregistry__"] = None + try: + return self._saved_warn(*args, **kwargs) + finally: + f_globals["__warningregistry__"] = orig + else: + return self._saved_warn(*args, **kwargs) warnings.warn, self._saved_warn = warn, warnings.warn return self