Skip to content

Fix logging usage in hooks pytest_sessionstart/finish #4204

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/3340.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix logging messages not shown in hooks ``pytest_sessionstart()`` and ``pytest_sessionfinish()``.
23 changes: 23 additions & 0 deletions src/_pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,29 @@ def pytest_runtest_logfinish(self):
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."""
Expand Down
36 changes: 36 additions & 0 deletions testing/logging/test_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -966,3 +966,39 @@ def test_simple():
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