1

I have a long series of unit tests that I am trying to parse into a text file, and while I know this can be accomplished with a few different uses of calling unittest.main(), I'm having a bit of a hiccup because the code I am working on needs to use a function. It is currently written as

unittest.TextTestRunner(verbosity=2).run(customFunction())

of which the stdout is read by another file with

p = Popen(command, stdout=PIPE, stderr=STDOUT stdin=PIPE)
result = p.communicate()

# Write result to .txt file

The only issue with this is that the program hangs when assigning the result variable to the console output due to some other programs the unit tests have to call. I'm trying to rewrite the code to have the unit test itself spit out into a log file (as opposed to parsing the console output into a text file), but I'm running into some hiccups in rewritting this using unittest.main() due to the custom function that has to be provided. Does anyone have any advice or solutions on how to go about doing this?

2 Answers 2

3

I found out how to do this on my own: there is a stream option that you can use with TextTestRunner, which will direct the output of unittest to whatever file object you want. So if you want to write to a txt file, you would write:

logFile = open("C:/folder/logfile.txt", "w")
unittest.TextTestRunner(stream=logFile, verbosity=2).run(customFunction())
logFile.close()

Just figured I would share this so that if anyone runs into the same problem later, they don't run into the fustration I did.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to redirect the output to a log file as well as console. Your example redirects the output to log file and prints nothing on the console.
Have you tried using the original example in the question? You can probably use a different method than what I had to resort to using if you don't have the same limitations that I did in the original post.
1

When we using stream in Python will be better provide catcher for the problem code areas and once again to insure I advise use such a structure:

stream = open("...", "w")
try:
    unittest.TextTestRunner(stream=stream, verbosity=2).run(suite)
finally:
    stream.close()

But in my opinion this catcher code is a large and it was easier to write like this:

with open("...", "w") as stream:
    unittest.TextTestRunner(stream=stream, verbosity=2).run(suite)

Perhaps there is a better style?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.