In my conftest.py, I implemented the hook like this:
```python
def pytest_terminal_summary(terminalreporter, exitstatus, config):
terminalreporter.section("My session")
terminalreporter.write("My message")
The output works fine when tests pass:
====================================== test session starts ======================================
...
========================================== My session ===========================================
My message
================================ 1 passed, 8 deselected in 2.06s ================================
But when tests fail, the newline is missing:
========================================== My session ===========================================
My message==================================== short test summary info ====================================
FAILED tests/test_example.py::test_example - assert 0
================================ 1 failed, 8 deselected in 2.32s ================================
I also tried `terminalreporter.line()` and `terminalreporter.write_line()`, but neither gives consistent results with proper newlines in all cases. Is there a cleaner way to write a line in `pytest_terminal_summary` without having extra or missing newlines?
A simple trick I use is always calling write_line() rather than write(). write() doesn’t automatically add a newline, which is why you see it merged with the next section when tests fail. For example:
def pytest_terminal_summary(terminalreporter, exitstatus, config):
terminalreporter.section("My session")
terminalreporter.write_line("My message")
write_line() ensures proper newlines in all cases — whether tests pass or fail — and keeps the formatting consistent with pytest’s built-in summaries.
If you need precise control over spacing, you can append \n to your write() calls. I’ve used this when I want a custom gap between my section and the summary:
def pytest_terminal_summary(terminalreporter, exitstatus, config):
terminalreporter.section("My session")
terminalreporter.write("My message\n")
It’s a small change but fixes the issue of messages running into the pytest summary, especially when there are failures.
I found the most robust approach is to always pair section() with write_line() and avoid write(). section() handles its own formatting, and write_line() respects newlines reliably:
def pytest_terminal_summary(terminalreporter, exitstatus, config):
terminalreporter.section("My session")
terminalreporter.write_line("My message")
terminalreporter.write_line("") # optional extra space for readability
````Preformatted text`
This ensures the custom summary section is clearly separated, whether the tests pass or fail. I now use this pattern in all my plugins to avoid weird formatting issues.