如何对使用 Popen 的函数进行单元测试? [英] How to unit test a function that uses Popen?

查看:39
本文介绍了如何对使用 Popen 的函数进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包含大量文件操作的程序.有些操作是通过调用subprocess.Popen来完成的,例如,split -l 50000 ${filename}, gzip -d -f ${filename} ${filename}..

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}..

现在我想对程序的功能进行单元测试.但是我如何对这些函数进行单元测试?

Now I want to unit test the functionality of the program. But how could I unit test these functions?

有什么建议吗?

推荐答案

规范的方法是模拟对 Popen 的调用并用一些测试数据替换结果.查看mock 库文档.1

The canonical way is to mock out the call to Popen and replace the results with some test data. Have a look at the mock library documentation.1

你会做这样的事情:

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请注意,这在python3.3中作为unittest.mock包含在标准库中.

1Note that this was included in the standard library as unittest.mock in python3.3.

这篇关于如何对使用 Popen 的函数进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆