jeudi 7 février 2019

Redirect all type of exceptions and stdout logs in a file during test execution - Python 3

My goal is to have a file with the results from my unit tests including any exceptions logged that arose.

I am executing my python test script using pytest which generates an xml file with the exact details i want. The problem is that this file is generated right after the execution of the test finishes and not during its execution like I want.

Here is the command I execute my test with:

python -m pytest test_signout.py --junitxml ./results/TestsOut.xml -vs

I have tried to redirect the stdout to a file with success but of course this doesn't contain any details related to exceptions such as assertion errors that I want to get.

I have tried the same method for stderr but the file stays empty.

Here is what I am trying to do:

@contextmanager
def redirected_stdout(filename):
    original_stderr = sys.stderr
    sys.stderr = open(filename, 'at')
    try:
        yield
    finally:
        sys.stderr = original_stderr

The way I am using this method is by adding the following command at the start of each of my methods and I then include all of my code within this:

with redirected_stdout("./results/TestsOut.log"):

Is there a way I could get both stderr and stdout logged during runtime or is there an another way to achieve what I want?

After I generate this file I am planning as the last step of my test to read it and pass it to the test management solution I use.

Aucun commentaire:

Enregistrer un commentaire