3

pytest does not capture print() statements (stdout output) which are located in pytest_sessionfinish() or code which is called in there. What's best practice to get same or similar behavior like print() statements located in tests, fixtures, etc.?

# conftest.py

def pytest_sessionfinish(session, exitstatus):
    print('This wont be captured (like in tests) but output independent of pytest exit status (exitstatus).')
    if exitstatus == 0:
        print('stdout shall be captured/suppressed in case of overall test PASS.')
    else:
        print('stdout shall be output in case of overall test FAIL and any other error.')
thinwybk
  • 4,193
  • 2
  • 40
  • 76
  • Print statements are captured inside tests, and `pytest_sessionfinish` hook is not part of any test, so the capturing machinery is not defined there. Why do you want to capture prints there anyway? Unlike the tests, there's no foreign code to be run in hooks. – hoefling Aug 10 '18 at 10:20
  • Im my use case I [check the overall test result in `session_finish()`](https://stackoverflow.com/a/51714659/5308983) and execute logic + print to stdout in case of FAIL. – thinwybk Aug 10 '18 at 10:33
  • Can you add a [mcve]? – hoefling Aug 10 '18 at 10:35
  • You can capture the prints by replacing `sys.stdout` with `io.StringIO`, for example like described in [this answer](https://stackoverflow.com/a/13250224/2650249). Builtin fixtures `capsys` and `caplog` are for capturing prints/logs inside tests and are not available in hooks. However, I still don't get it - can't you just not print anything when the `exitstatus` is 0? – hoefling Aug 10 '18 at 13:23
  • I would like to be able to print debug output which is located outside tests in case I have configured it via command line options (`-s`, `-vvv`, etc.) as I am able to do for debug output in tests. – thinwybk Aug 10 '18 at 13:35

0 Answers0