pytestmocks并声明类级别的fixtu

2024-10-01 22:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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,但它似乎不是。。。我做错什么了?在


Tags: pytestselfinfouiddatadefproc
1条回答
网友
1楼 · 发布于 2024-10-01 22:36:50

在您的测试中,没有太多关于模拟使用的问题。事实上,只有两种:

访问mockerfixture

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

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

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

使用mocker.patch

mocker.patch只是^{}的一个填充物,没什么别的;它只是为了方便起见,这样您就不必到处导入unittest.mock.patch。这意味着mocker.patch与{}具有相同的签名,当您对stdlib的正确使用有疑问时,可以随时查阅stdlib的文档。在

在您的例子中,mocker.patch(os.path.isfile).return_value(False)不是patch方法的正确用法。从docs

target should be a string in the form 'package.module.ClassName'.

...

patch() takes arbitrary keyword arguments. These will be passed to the Mock (or new_callable) on construction.

这意味着这条线

^{pr2}$

应该是

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

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

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

示例:

assert result == "NOT_FOUND"

将始终引发,因为"NOT_FOUND"在代码中甚至不存在。在

assert result == "NOT_DEFINED"

将始终引发,因为uid = "NOT_DEFINED"将始终被regex搜索结果覆盖,因此从未返回。在

工作示例

假设您的测试是唯一的真理来源,我用上面描述的mock用法修复了两个错误,并调整了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"

请注意,我使用的是python3,因此我不能修补__builtin__并求助于修补{};除此之外,代码应该与python2的变体相同。另外,由于使用了mocker,所以我使用了mocker.mock_open,因此节省了{}的额外导入。在

相关问题 更多 >

    热门问题