简体   繁体   English

模拟 subprocess.Popen 与字典作为标准输出

[英]Mock subprocess.Popen with dictionary as stdout

I have a function我有一个 function

def execute(process: subprocess.Popen):
    if not isinstance(process, subprocess.Popen):
        raise ValueError('expected: subprocessPopen, found: %s' % type(process))

    data = io.TextIOWrapper(process.stdout, encoding='utf-8')
    func1(data_input)

I want to unit test it, where I want data as a dictionary which is to be passed to func1 as an argument but not able to find a way out.我想对其进行单元测试,我希望将data作为dictionary传递给func1作为参数但无法找到出路。

import mock

def test_run_func():
    subprocess.Popen = mock.MagicMock(return_value=expected_return_value)
    # The rest of your test...

Something like should work.类似的东西应该工作。

Have a look at the spec argument to the Mock object, in order to make it pass the isinstance() test:查看 Mock object 的spec参数,以使其通过isinstance()测试:

Have a look at the patch decorator for how to replace the process.stdout member with, eg, a io.BytesIO object:查看patch装饰器,了解如何用例如io.BytesIO object 替换process.stdout成员:

You also might want to consider the examples given here:您可能还想考虑此处给出的示例:

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

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