简体   繁体   English

使用自定义函数将单元测试读取到python中的文件

[英]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. 我有一系列的单元测试,我试图解析成一个文本文件,虽然我知道这可以通过调用unittest.main()的一些不同用途来实现,但我有点打嗝,因为我正在处理的代码需要使用一个函数。 It is currently written as 它目前写成

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

of which the stdout is read by another file with stdout由另一个文件读取

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. 我正在尝试重写代码以使单元测试本身吐出到日志文件中(而不是将控制台输出解析为文本文件),但是我在使用unittest.main重写这个问题时遇到了一些小问题( )由于必须提供自定义功能。 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. 我发现了如何自己完成这个:有一个可以与TextTestRunner一起使用的流选项,它将unittest的输出指向你想要的任何文件对象。 So if you want to write to a txt file, you would write: 所以如果你想写一个txt文件,你会写:

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. 只是想我会分享这个,以便如果有人在以后遇到同样的问题,他们不会遇到我所做的fustration。

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: 当我们在Python中使用stream时,会更好地为问题代码区域提供捕获器,并再次确保我建议使用这样的结构:

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? 也许有更好的风格?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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