mocking subprocess.Popen dependant on import style(模拟 subprocess.Popen 依赖于导入样式)
问题描述
在尝试模拟 Popen 时,只有在单元测试代码和主模块代码中子流程的导入匹配时,我才能使其成功.
When attempting to mock Popen I can only get it to succeed if the importing of subprocess matches in both unit test code and main module code.
给定以下模块 listdir.py:
Given following module listdir.py:
from subprocess import Popen, PIPE
def listdir(dir):
cmd = ['ls', dir]
pc = Popen(cmd, stdout=PIPE, stderr=PIPE)
out, err = pc.communicate()
if pc.returncode != 0:
raise Exception
return out
以及下面的单元测试代码test_listdir.py
and following unit test code test_listdir.py
import subprocess
import listdir
import mock
@mock.patch.object(subprocess, 'Popen', autospec=True)
def test_listdir(mock_popen):
mock_popen.return_value.returncode = 0
mock_popen.return_value.communicate.return_value = ("output", "Error")
listdir.listdir("/fake_dir")
由于某些原因,Popen 没有被模拟,因为两个 python 模块之间的导入样式不同,并且运行测试总是引发异常.
For some reason Popen is not being mocked, due to the import style being different between the two python modules, and running the test always raises an exception.
如果我更改 listdir.py 以导入所有子进程,例如
If I change listdir.py to import all of subproces e.g.
import subprocess
def listdir(dir):
cmd = ['ls', dir]
pc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = pc.communicate()
if pc.returncode != 0:
raise ListingErrorException
return out
然后在测试中返回输出".
Then "output" is returned in the test.
任何人都想解释一下为什么,我的偏好是from subprocess import Popen, Pipe in 这两个模块,但我就是无法模拟.
Anyone care to shed some light on why, my preference would be to have from subprocess import Popen, Pipe in both modules, but I just can't get that to mock.
推荐答案
你需要在 listdir 中修补 Popen 的副本,而不是你刚刚导入的那个.所以,不要使用 @mock.patch.object(subprocess, 'Popen', autospec=True),试试 @mock.patch.object(listdir, 'Popen', autospec=True)
You need to patch the copy of Popen in listdir, not the one you just imported. So, instead of @mock.patch.object(subprocess, 'Popen', autospec=True), try @mock.patch.object(listdir, 'Popen', autospec=True)
有关详细信息,请参阅此文档:http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch
See this doc for more info: http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch
这篇关于模拟 subprocess.Popen 依赖于导入样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模拟 subprocess.Popen 依赖于导入样式
基础教程推荐
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
