【问题标题】:Pytest: Patch a global variablePytest:修补全局变量
【发布时间】:2021-10-22 19:59:41
【问题描述】:

如何使用 mock 或 pytest-mock 修补变量。假设该变量是在另一个 python 脚本中定义的,并且被许多其他脚本使用。我想在pytest_cmdline_main 中模拟它,以便相应地模拟所有使用该变量的脚本。

一个简单的例子是

在 env.py 中

VAR = "something"

在 conftest.py 中

import os
import sys
from unittest.mock import patch


TEST_DIR = os.path.dirname(os.path.realpath(__file__))


class MockThings():
    def __init__(self):
        self.setup()

    def setup(self):
        mock_var = patch('env.VAR').start()
        mock_var.return_value = "updated"


def pytest_cmdline_main(config):
    sys.path.append(TEST_DIR)
    MockThings()

在 test_something.py 中

from env import VAR


def test_sample():
    print(VAR)
    # do something else here
    assert False
    
def test_sample2():
    print(VAR)
    # do something else here
    assert False

当你运行pytest -v

测试将按预期失败,但在标准输出下会显示如下内容:<MagicMock name='VAR' id='140102687826416'>

因为它将模拟视为一个函数,所以如果我将print(VAR) 替换为print(VAR()),那么打印输出将是正确的(updated)。

如何模拟这个变量,而不是把它当作一个函数?我知道你可以在测试函数本身中设置VAR="updated",但我只是希望它被模拟,我想这不是我实际用例的一个很好的代表,但我只是想有一个可以运行的快速简单的测试代码并且容易理解。

【问题讨论】:

    标签: python mocking pytest


    【解决方案1】:

    假设你有这样的env.py

    VAR = "something"
    
    def func():
        return VAR
    

    然后,在test_something.py 中,您可以像这样模拟VAR

    import pytest
    
    from env.py import func
    
    
    @pytest.fixture
    def var(mocker):
        return mocker.patch("env.VAR", new="updated", autospec=False)
    
    
    def test_func(var):
        print(func())
        assert func() == "updated"
    

    在这种情况下,运行pytest . -v -s 会打印出来:

    test_something.py::test_func 更新
    通过

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-21
      • 2019-04-07
      • 1970-01-01
      • 2022-08-03
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      相关资源
      最近更新 更多