pytest-mocks并声明类级别的夹具

时间:2019-04-27 00:46:56

标签: python mocking pytest

我在pytest-mock和模拟打开方面遇到麻烦。

我要测试的代码如下:

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

所以测试文件是:

import os
import pytest

from cpu_info import uid

@pytest.mark.usefixtures("mocker")
class TestCPUInfo(object):
    def test_no_proc_cpuinfo_file(self):
        mocker.patch(os.path.isfile).return_value(False)
        result = uid.get_uid()
        assert result == "NOT_FOUND"

    def test_no_cpu_info_in_file(self):
        file_data = """
Hardware    : BCM2835
Revision    : a020d3
        """
        mocker.patch('__builtin__.open', mock_open(read_data=file_data))
        result = uid.get_uid()
        assert result == "NOT_DEFINED"

    def test_cpu_info(self):
        file_data = """
Hardware    : BCM2835
Revision    : a020d3
Serial      : 00000000e54cf3fa
        """
        mocker.patch('__builtin__.open', mock_open(read_data=file_data))
        result = uid.get_uid()
        assert result == "00000000e54cf3fa"

测试运行显示:

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 =====================================

我认为我已经正确地声明了嘲笑者的固定装置,但是似乎没有...我在做什么错?

1 个答案:

答案 0 :(得分:0)

在您的测试中,模拟用法的问题并不多。实际上,只有两个:

访问mocker固定装置

如果需要访问灯具的返回值,请在测试函数参数中包含其名称,例如:

class TestCPUInfo:
    def test_no_proc_cpuinfo_file(self, mocker):
        mocker.patch(...)

pytest将在运行测试时自动将测试参数值映射到夹具值。

使用mocker.patch

mocker.patch只是unittest.mock.patch的填充物,仅此而已;它只是为了方便起见,因此您不必在任何地方导入unittest.mock.patch。这意味着mocker.patchunittest.mock.patch具有相同的签名,并且在怀疑正确使用stdlib的文档时始终可以查阅。

在这种情况下,mocker.patch(os.path.isfile).return_value(False)不是patch方法的正确用法。来自docs

  

target 应该是'package.module.ClassName'形式的字符串。

     

...

     

patch()采用任意关键字参数。这些将在构造时传递给Mock(或new_callable)。

这意味着该行

mocker.patch(os.path.isfile).return_value(False)

应该是

mocker.patch('os.path.isfile', return_value=False)

测试行为与实际实现逻辑之间的差异

现在剩下的就是与实现有关的错误;您必须调整测试以测试正确的行为或解决实施错误。

示例:

assert result == "NOT_FOUND"

总是会出现,因为代码中甚至没有"NOT_FOUND"

assert result == "NOT_DEFINED"

总是会上升,因为uid = "NOT_DEFINED"总是会被正则表达式搜索结果覆盖,因此永远不会返回。

工作示例

假设您的测试是事实的唯一来源,我使用上述模拟用法修复了两个错误,并修改了get_uid()的实现以使测试通过:

import os
import re

def get_uid():
    regex = re.compile(r'Serial\s+:\s*(\w+)')
    exists = os.path.isfile('/proc/cpuinfo')
    if not exists:
        return 'NOT_FOUND'
    with open('/proc/cpuinfo', 'r') as file:
        cpu_details = file.read()
        match = regex.search(cpu_details)
        if match is None:
            return 'NOT_DEFINED'
        return match.group(1)

测试:

import pytest
import uid


class TestCPUInfo:

    def test_no_proc_cpuinfo_file(self, mocker):
        mocker.patch('os.path.isfile', return_value=False)
        result = uid.get_uid()
        assert result == "NOT_FOUND"

    def test_no_cpu_info_in_file(self, mocker):
        file_data = """
Hardware    : BCM2835
Revision    : a020d3
        """
    mocker.patch('builtins.open', mocker.mock_open(read_data=file_data))
        result = uid.get_uid()
        assert result == "NOT_DEFINED"

    def test_cpu_info(self, mocker):
        file_data = """
Hardware    : BCM2835
Revision    : a020d3
Serial      : 00000000e54cf3fa
        """
    mocker.patch('builtins.open', mocker.mock_open(read_data=file_data))
        result = uid.get_uid()
        assert result == "00000000e54cf3fa"

请注意,我使用的是Python 3,因此无法修补__builtin__,而不能修补builtins;除此之外,代码应与Python 2变体相同。另外,由于无论如何都使用mocker,所以我使用了mocker.mock_open,从而节省了unittest.mock.mock_open的其他导入。

相关问题