简体   繁体   中英

Reading a Unit Test to a file in python with a custom function

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?

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM