我对pytest mock和mocking open有问题。在
我想测试的代码如下:
import re
import os
def get_uid():
regex = re.compile('Serial\s+:\s*(\w+)')
uid = "NOT_DEFINED"
exists = os.path.isfile('/proc/cpuinfo')
if exists:
with open('/proc/cpuinfo', 'r') as file:
cpu_details = file.read()
uid = regex.search(cpu_details).group(1)
return uid
所以测试文件是:
^{pr2}$测试运行给出:
pytest
======================================= test session starts ========================================
platform linux -- Python 3.5.3, pytest-4.4.1, py-1.8.0, pluggy-0.9.0
rootdir: /home/robertpostill/software/gateway
plugins: mock-1.10.4
collected 3 items
cpu_info/test_cpu_info.py FFF [100%]
============================================= FAILURES =============================================
______________________________ TestCPUInfo.test_no_proc_cpuingo_file _______________________________
self = <test_cpu_info.TestCPUInfo object at 0x75e6eaf0>
def test_no_proc_cpuingo_file(self):
> mocker.patch(os.path.isfile).return_value(False)
E NameError: name 'mocker' is not defined
cpu_info/test_cpu_info.py:9: NameError
___________________________________ TestCPUInfo.test_no_cpu_info ___________________________________
self = <test_cpu_info.TestCPUInfo object at 0x75e69d70>
def test_no_cpu_info(self):
file_data = """
Hardware : BCM2835
Revision : a020d3
"""
> mocker.patch('__builtin__.open', mock_open(read_data=file_data))
E NameError: name 'mocker' is not defined
cpu_info/test_cpu_info.py:18: NameError
____________________________________ TestCPUInfo.test_cpu_info _____________________________________
self = <test_cpu_info.TestCPUInfo object at 0x75e694f0>
def test_cpu_info(self):
file_data = """
Hardware : BCM2835
Revision : a020d3
Serial : 00000000e54cf3fa
"""
> mocker.patch('__builtin__.open', mock_open(read_data=file_data))
E NameError: name 'mocker' is not defined
cpu_info/test_cpu_info.py:28: NameError
===================================== 3 failed in 0.36 seconds =====================================
我想我已经正确地声明了mocker fixture,但它似乎不是。。。我做错什么了?在
在您的测试中,没有太多关于模拟使用的问题。事实上,只有两种:
访问
mocker
fixture如果需要访问fixture的返回值,请在测试函数参数中包含其名称,例如:
运行测试时,
pytest
将自动将测试参数值映射到fixture值。在使用
mocker.patch
mocker.patch
只是^{unittest.mock.patch
。这意味着mocker.patch
与{在您的例子中,
mocker.patch(os.path.isfile).return_value(False)
不是patch
方法的正确用法。从docs:这意味着这条线
^{pr2}$应该是
测试行为与实际实现逻辑之间的差异
现在剩下的就是与实现有关的错误;您必须调整测试以测试正确的行为,或者修复实现错误。在
示例:
将始终引发,因为
"NOT_FOUND"
在代码中甚至不存在。在将始终引发,因为
uid = "NOT_DEFINED"
将始终被regex搜索结果覆盖,因此从未返回。在工作示例
假设您的测试是唯一的真理来源,我用上面描述的mock用法修复了两个错误,并调整了
get_uid()
的实现,以使测试通过:测试:
请注意,我使用的是python3,因此我不能修补};除此之外,代码应该与python2的变体相同。另外,由于使用了}的额外导入。在
__builtin__
并求助于修补{mocker
,所以我使用了mocker.mock_open
,因此节省了{相关问题 更多 >
编程相关推荐