简体   繁体   English

如何对使用Popen的函数进行单元测试?

[英]How to unit test a function that uses Popen?

I am writing a program which contains a lot of file operation. 我正在编写一个包含大量文件操作的程序。 Some operations are done by calling subprocess.Popen , eg, split -l 50000 ${filename} , gzip -d -f ${filename} ${filename}. 一些操作是通过调用subprocess.Popen完成的,例如, split -l 50000 ${filename}gzip -d -f ${filename} ${filename}. .

Now I want to unit test the functionality of the program. 现在我想单元测试程序的功能。 But how could I unit test these functions? 但是我怎么能对这些功能进行单元测试?

Any suggestions? 有什么建议?

The canonical way is to mock out the call to Popen and replace the results with some test data. 规范的方法是模拟对Popen的调用,并用一些测试数据替换结果。 Have a look at the mock library documentation . 看看mock库文档 1 1

You'd do something like this: 你会做这样的事情:

with mock.patch.object(subprocess, 'Popen') as mocked_popen:
    mocked_popen.return_value.communicate.return_value = some_fake_result
    function_which_uses_popen_communicate()

Now you can do some checking or whatever you want to test... 现在你可以做一些检查或者你想要测试的任何东西......

1 Note that this was included in the standard library as unittest.mock in python3.3. 1请注意,它在python3.3中作为unittest.mock包含在标准库中。

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

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