vikkyhacks
vikkyhacks

Reputation: 3230

Read py.test's output as object

Earlier I was using python unittest in my project, and with it came unittest.TextTestRunner and unittest.defaultTestLoader.loadTestsFromTestCase. I used them for the following reasons,

  1. Control the execution of unittest using a wrapper function which calls the unittests's run method. I did not want the command line approach.

  2. Read the unittest's output from the result object and upload the results to a bug tracking system which allow us to generate some complex reports on code stability.

Recently there was a decision made to switch to py.test, how can I do the above using py.test ? I don't want to parse any CLI/HTML to get the output from py.test. I also don't want to write too much code on my unit test file to do this.

Can someone help me with this ?

Upvotes: 3

Views: 1133

Answers (2)

Sergey Vasilyev
Sergey Vasilyev

Reputation: 4189

You can use the pytest's hook to intercept the test result reporting:

conftest.py:

import pytest

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_logreport(report):
    yield

    # Define when you want to report:
    # when=setup/call/teardown,
    # fields: .failed/.passed/.skipped
    if report.when == 'call' and report.failed:

        # Add to the database or an issue tracker or wherever you want.
        print(report.longreprtext)
        print(report.sections)
        print(report.capstdout)
        print(report.capstderr)

Similarly, you can intercept one of these hooks to inject your code at the needed stage (in some cases, with the try-except around yield):

  • pytest_runtest_protocol(item, nextitem)
  • pytest_runtest_setup(item)
  • pytest_runtest_call(item)
  • pytest_runtest_teardown(item, nextitem)
  • pytest_runtest_makereport(item, call)
  • pytest_runtest_logreport(report)

Read more: Writing pytest plugins

All of this can be easily done either with a tiny plugin made as a simple installable library, or as a pseudo-plugin conftest.py which just lies around in one of the directories with the tests.

Upvotes: 4

Don Kirkby
Don Kirkby

Reputation: 56650

It looks like pytest lets you launch from Python code instead of using the command line. It looks like you just pass the same arguments to the function call that would be on the command line.

Pytest will create resultlog format files, but the feature is deprecated. The documentation suggests using the pytest-tap plugin that produces files in the Test Anything Protocol.

Upvotes: 1

Related Questions