How to avoid extra newline using "pytest_terminal_summary" hook

Viewed 558

In conftest.py I implemented this:

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    terminalreporter.section("My session")
    terminalreporter.write("My message")

The output is exactly what I'm looking for:

====================================== test session starts ======================================

...                                    

========================================== My session ===========================================
My message
================================ 1 passed, 8 deselected in 2.06s ================================

However, when the tests fail it look like this:

========================================== My session ===========================================
My message==================================== short test summary info ====================================
FAILED tests/test_example.py::test_example - assert 0
================================ 1 failed, 8 deselected in 2.32s ================================

The newline is missing.

Instead of terminalreporter.write() I also tried terminalreporter.line() but in this case, the output when there is no error is incorrect:

========================================== My session ===========================================
My message

================================ 1 passed, 8 deselected in 2.07s ================================

I also tried with terminalreporter.write_line():

========================================== My session ===========================================

My message
================================ 1 passed, 8 deselected in 2.03s ================================

None provide the solution I'm looking for with the proper new lines.

Of course I could check the value of exitstatus and add extra newline if needed, but does it exist a more elegant way to simply write a line to the terminal without extra one?

1 Answers

The trick is to call terminalreporter.ensure_newline() to insert a linebreak when necessary. However, on test run failure this may have no effect if ensure_newline() was just called before (to avoid inserting lots of linebreaks unnecessarily), so you have to set terminalreporter.currentfspath to something truthful:

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    terminalreporter.section("My session")
    terminalreporter.write("My message")
    terminalreporter.currentfspath = 1
    terminalreporter.ensure_newline()
Related