How can I display the test name * after * a test using pytest?

Most of the time when I use pytest the output is very, very long. More than a hundred lines. And often times I want this exit, I really do it. --tb=short

not really a good approach. But I don't want to scroll back 200 lines in my tmux window to find my test result, because that is very annoying too.

What I would like to have is something like this:

______________________ >>test_my_test_with_a_lot_of_output _______________________
# imagine lots of test output here
______________________ <<test_my_test_with_a_lot_of_output _______________________

      

Is there any flag or parameter that I can use in py.test to achieve this kind of output?

+3


source to share


3 answers


You can add one fixture to your main / root conftest.py

, which will be called automatically before and after each test script. how

@pytest.fixture(scope='function', autouse=True)
def test_log(request):
    logging.info("Test '{}' STARTED".format(request.node.nodeid)) # Here logging is used, you can use whatever you want to use for logs
    def fin():
        logging.info("Test '{}' COMPLETED".format(request.node.nodeid))
    request.addfinalizer(fin)

      



Here request.node.nodeid

gives you the name of your test.

+1


source


I couldn't find an easy way to achieve this using hooks. But here's how I implement it. However, this is not an ideal implementation.

# contest.py
import pytest
import _pytest

class TerminalReporter(_pytest.terminal.TerminalReporter):
    def _gettestname(self, rep):
        # actually "rename" original method for clarity
        return super()._getfailureheadline(rep)

    def _getfailureheadline(self, rep):
        # instead of test name
        # (which is originally printed at the top of report)
        # return prefixed name
        return '>>' + self._gettestname(rep)

    def _outrep_summary(self, rep):
        super()._outrep_summary(rep)
        # after printing test report end, print out test name again
        # XXX: here we hard-code color, so red will be used even for passed tests
        # (if passes logging is enabled)
        # You can add some more logic with analyzing report status
        self.write_sep('_', '<<' + self._gettestname(rep), red=True)

@pytest.hookimpl(trylast=True)
def pytest_configure(config):
    # overwrite original TerminalReporter plugin with our subclass
    # we want this hook to be executed after all other implementations
    # to be able to unregister original plugin
    reporter = TerminalReporter(config)
    config.pluginmanager.unregister(name='terminalreporter')
    config.pluginmanager.register(reporter, 'terminalreporter')

      



For inspiration on expanding this approach to a chapter _pytest.terminal.TerinalReporter

.

0


source


Use "pytest -rA" when running tests

see docs here

0


source







All Articles