stefan.stt
stefan.stt

Reputation: 2627

pytest stdout flush to a different file from the test output

Here I have tests.py containing:

import sys
sys.stdout = open('log2.log', 'w')


class TestH5Client:
    def test_something(self):
        print("Start")
        assert True
        print("End")

    def teardown_class(cls):
        print("OK")

I am running my test with the following shell command

pytest tests.py::TestH5Client::test_something >>log.log

and I want that log.log to contain the information of the test run and log2.log to contain all the prints, but log2.log is empty

Content of log.log (the content is what I expect):

============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.1.0, py-1.4.33, pluggy-0.4.0
rootdir: C:\Stefans\01.Learning_Python\27.pytest_std_ouput, inifile:
collected 2 items

tests.py .

========================== 1 passed in 0.01 seconds ===========================

Content of log2.log: the file is empty

Expectation for log2.log content:

Start
End
OK

So my questions are what I am doing wrong and how can I make it work this way, thank you in advance.

Upvotes: 1

Views: 895

Answers (1)

Pinna_be
Pinna_be

Reputation: 4617

I would guess that the default option of py.test is to capture al output by overriding sys.stdout, cancelling out your code to override sys.stdout.

I have tested three options that seem to solve your problem:

  1. Instead of overriding sys.stdout, you could override the print function, like eg print = lambda x: open('log2.log', 'a').write(str(x)+"\n")
    • will not log prints recursively
    • enables per file logging
  2. You could disable py.test's output capturing by adding the -s option to your execution command.
    • will print all prints in all your tests, also recursively
    • non-converted prints will probably cloud your log.log-file
  3. Use a decent logger framework.

Despite 3 being the biggest effort, depending on what you want to reach, I do believe that this is the best solution.

Upvotes: 1

Related Questions