diff --git a/_pytest/logging.py b/_pytest/logging.py index 095115cd9..f6affc8a2 100644 --- a/_pytest/logging.py +++ b/_pytest/logging.py @@ -477,7 +477,7 @@ class _LiveLoggingStreamHandler(logging.StreamHandler): if not self._first_record_emitted or self._when == 'teardown': self.stream.write('\n') self._first_record_emitted = True - if not self._section_name_shown: + if not self._section_name_shown and self._when: self.stream.section('live log ' + self._when, sep='-', bold=True) self._section_name_shown = True logging.StreamHandler.emit(self, record) diff --git a/changelog/3184.bugfix b/changelog/3184.bugfix new file mode 100644 index 000000000..875358776 --- /dev/null +++ b/changelog/3184.bugfix @@ -0,0 +1 @@ +Fix bug where logging happening at hooks outside of "test run" hooks would cause an internal error. diff --git a/testing/logging/test_reporting.py b/testing/logging/test_reporting.py index f5272aa09..8dfe04ad9 100644 --- a/testing/logging/test_reporting.py +++ b/testing/logging/test_reporting.py @@ -272,6 +272,60 @@ def test_log_cli_default_level_sections(testdir, request): ]) +def test_live_logs_unknown_sections(testdir, request): + """Check that with live logging enable we are printing the correct headers during + start/setup/call/teardown/finish.""" + filename = request.node.name + '.py' + testdir.makeconftest(''' + import pytest + import logging + + def pytest_runtest_protocol(item, nextitem): + logging.warning('Unknown Section!') + + def pytest_runtest_logstart(): + logging.warning('>>>>> START >>>>>') + + def pytest_runtest_logfinish(): + logging.warning('<<<<< END <<<<<<<') + ''') + + testdir.makepyfile(''' + import pytest + import logging + + @pytest.fixture + def fix(request): + logging.warning("log message from setup of {}".format(request.node.name)) + yield + logging.warning("log message from teardown of {}".format(request.node.name)) + + def test_log_1(fix): + logging.warning("log message from test_log_1") + + ''') + testdir.makeini(''' + [pytest] + log_cli=true + ''') + + result = testdir.runpytest() + result.stdout.fnmatch_lines([ + '*WARNING*Unknown Section*', + '{}::test_log_1 '.format(filename), + '*WARNING* >>>>> START >>>>>*', + '*-- live log setup --*', + '*WARNING*log message from setup of test_log_1*', + '*-- live log call --*', + '*WARNING*log message from test_log_1*', + 'PASSED *100%*', + '*-- live log teardown --*', + '*WARNING*log message from teardown of test_log_1*', + '*WARNING* <<<<< END <<<<<<<*', + '=* 1 passed in *=', + ]) + + def test_log_cli_level(testdir): # Default log file level testdir.makepyfile('''