From db106d60855fa7536eadbe1d0a38bb65abb6511f Mon Sep 17 00:00:00 2001 From: Vincent Barbaresi Date: Fri, 19 Oct 2018 18:59:23 +0200 Subject: [PATCH] Fix logging usage in hooks pytest_sessionstart/finish #3340 --- changelog/3340.bugfix.rst | 1 + src/_pytest/logging.py | 23 ++++++++++++++++++++ testing/logging/test_reporting.py | 36 +++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 changelog/3340.bugfix.rst diff --git a/changelog/3340.bugfix.rst b/changelog/3340.bugfix.rst new file mode 100644 index 000000000..72b889d01 --- /dev/null +++ b/changelog/3340.bugfix.rst @@ -0,0 +1 @@ +Fix logging messages not shown in hooks ``pytest_sessionstart()`` and ``pytest_sessionfinish()``. diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py index ee6795250..8244c8030 100644 --- a/src/_pytest/logging.py +++ b/src/_pytest/logging.py @@ -497,6 +497,29 @@ class LoggingPlugin(object): with self._runtest_for(None, "finish"): yield + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_sessionfinish(self): + with self.live_logs_context(): + if self.log_cli_handler: + self.log_cli_handler.set_when("sessionfinish") + if self.log_file_handler is not None: + with catching_logs(self.log_file_handler, level=self.log_file_level): + yield + else: + yield + + @pytest.hookimpl(hookwrapper=True, tryfirst=True) + def pytest_sessionstart(self): + self._setup_cli_logging() + with self.live_logs_context(): + if self.log_cli_handler: + self.log_cli_handler.set_when("sessionstart") + if self.log_file_handler is not None: + with catching_logs(self.log_file_handler, level=self.log_file_level): + yield + else: + yield + @pytest.hookimpl(hookwrapper=True) def pytest_runtestloop(self, session): """Runs all collected test items.""" diff --git a/testing/logging/test_reporting.py b/testing/logging/test_reporting.py index 498b4c5bd..5863e0115 100644 --- a/testing/logging/test_reporting.py +++ b/testing/logging/test_reporting.py @@ -966,3 +966,39 @@ def test_collection_logging_to_file(testdir): assert "Normal message" in contents assert "debug message in test_simple" not in contents assert "info message in test_simple" in contents + + +def test_log_in_hooks(testdir): + log_file = testdir.tmpdir.join("pytest.log").strpath + + testdir.makeini( + """ + [pytest] + log_file={} + log_file_level = INFO + log_cli=true + """.format( + log_file + ) + ) + testdir.makeconftest( + """ + import logging + + def pytest_runtestloop(session): + logging.info('runtestloop') + + def pytest_sessionstart(session): + logging.info('sessionstart') + + def pytest_sessionfinish(session, exitstatus): + logging.info('sessionfinish') + """ + ) + result = testdir.runpytest() + result.stdout.fnmatch_lines(["*sessionstart*", "*runtestloop*", "*sessionfinish*"]) + with open(log_file) as rfh: + contents = rfh.read() + assert "sessionstart" in contents + assert "runtestloop" in contents + assert "sessionfinish" in contents