From 2b71cb9c381effaea13fa00c096a8f4c76a663b5 Mon Sep 17 00:00:00 2001 From: Victor Date: Fri, 17 Aug 2018 00:26:12 +0200 Subject: [PATCH] Added activation/deactivation of capture fixture in logging emit. --- src/_pytest/capture.py | 16 ++++++++++++++-- src/_pytest/logging.py | 2 ++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/_pytest/capture.py b/src/_pytest/capture.py index faa767a86..34d42821f 100644 --- a/src/_pytest/capture.py +++ b/src/_pytest/capture.py @@ -85,6 +85,7 @@ class CaptureManager(object): def __init__(self, method): self._method = method self._global_capturing = None + self._current_item = None def _getcapture(self, method): if method == "fd": @@ -121,15 +122,23 @@ class CaptureManager(object): cap.suspend_capturing(in_=in_) return outerr - def activate_fixture(self, item): + def activate_fixture(self, item=None): """If the current item is using ``capsys`` or ``capfd``, activate them so they take precedence over the global capture. """ + if item is None: + if self._current_item is None: + return + item = self._current_item fixture = getattr(item, "_capture_fixture", None) if fixture is not None: fixture._start() - def deactivate_fixture(self, item): + def deactivate_fixture(self, item=None): + if item is None: + if self._current_item is None: + return + item = self._current_item """Deactivates the ``capsys`` or ``capfd`` fixture of this item, if any.""" fixture = getattr(item, "_capture_fixture", None) if fixture is not None: @@ -151,6 +160,7 @@ class CaptureManager(object): @pytest.hookimpl(hookwrapper=True) def pytest_runtest_setup(self, item): + self._current_item = item self.resume_global_capture() # no need to activate a capture fixture because they activate themselves during creation; this # only makes sense when a fixture uses a capture fixture, otherwise the capture fixture will @@ -160,6 +170,7 @@ class CaptureManager(object): @pytest.hookimpl(hookwrapper=True) def pytest_runtest_call(self, item): + self._current_item = item self.resume_global_capture() # it is important to activate this fixture during the call phase so it overwrites the "global" # capture @@ -169,6 +180,7 @@ class CaptureManager(object): @pytest.hookimpl(hookwrapper=True) def pytest_runtest_teardown(self, item): + self._current_item = item self.resume_global_capture() self.activate_fixture(item) yield diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py index 1472b0dbd..65ac2d24b 100644 --- a/src/_pytest/logging.py +++ b/src/_pytest/logging.py @@ -573,6 +573,7 @@ class _LiveLoggingStreamHandler(logging.StreamHandler): def emit(self, record): if self.capture_manager is not None: + self.capture_manager.deactivate_fixture() self.capture_manager.suspend_global_capture() try: if not self._first_record_emitted: @@ -589,3 +590,4 @@ class _LiveLoggingStreamHandler(logging.StreamHandler): finally: if self.capture_manager is not None: self.capture_manager.resume_global_capture() + self.capture_manager.activate_fixture()