Skip to content

Commit 419095c

Browse files
author
Vincent Barbaresi
committed
Fix logging usage in hooks pytest_sessionstart/finish #3340
1 parent 93bdbf7 commit 419095c

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

changelog/3340.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix logging messages not shown in hooks `pytest_sessionstart()` and `pytest_sessionfinish()`.

src/_pytest/logging.py

+23
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,29 @@ def pytest_runtest_logfinish(self):
497497
with self._runtest_for(None, "finish"):
498498
yield
499499

500+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
501+
def pytest_sessionfinish(self):
502+
with self.live_logs_context():
503+
if self.log_cli_handler:
504+
self.log_cli_handler.set_when("sessionfinish")
505+
if self.log_file_handler is not None:
506+
with catching_logs(self.log_file_handler, level=self.log_file_level):
507+
yield
508+
else:
509+
yield
510+
511+
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
512+
def pytest_sessionstart(self):
513+
self._setup_cli_logging()
514+
with self.live_logs_context():
515+
if self.log_cli_handler:
516+
self.log_cli_handler.set_when("sessionstart")
517+
if self.log_file_handler is not None:
518+
with catching_logs(self.log_file_handler, level=self.log_file_level):
519+
yield
520+
else:
521+
yield
522+
500523
@pytest.hookimpl(hookwrapper=True)
501524
def pytest_runtestloop(self, session):
502525
"""Runs all collected test items."""

testing/logging/test_reporting.py

+36
Original file line numberDiff line numberDiff line change
@@ -966,3 +966,39 @@ def test_simple():
966966
assert "Normal message" in contents
967967
assert "debug message in test_simple" not in contents
968968
assert "info message in test_simple" in contents
969+
970+
971+
def test_log_in_hooks(testdir):
972+
log_file = testdir.tmpdir.join("pytest.log").strpath
973+
974+
testdir.makeini(
975+
"""
976+
[pytest]
977+
log_file={}
978+
log_file_level = INFO
979+
log_cli=true
980+
""".format(
981+
log_file
982+
)
983+
)
984+
testdir.makeconftest(
985+
"""
986+
import logging
987+
988+
def pytest_runtestloop(session):
989+
logging.info('runtestloop')
990+
991+
def pytest_sessionstart(session):
992+
logging.info('sessionstart')
993+
994+
def pytest_sessionfinish(session, exitstatus):
995+
logging.info('sessionfinish')
996+
"""
997+
)
998+
result = testdir.runpytest()
999+
result.stdout.fnmatch_lines(["*sessionstart*", "*runtestloop*", "*sessionfinish*"])
1000+
with open(log_file) as rfh:
1001+
contents = rfh.read()
1002+
assert "sessionstart" in contents
1003+
assert "runtestloop" in contents
1004+
assert "sessionfinish" in contents

0 commit comments

Comments
 (0)