如何 monkeypatch/mock 模块和环境

有时,测试需要调用依赖于全局设置的功能,或者调用不易测试的代码(例如网络访问)。monkeypatch fixture 帮助您安全地设置/删除属性、字典项或环境变量,或修改 sys.path 以进行导入。

monkeypatch fixture 提供了以下帮助方法,用于安全地修补和模拟测试中的功能:

所有修改将在请求的测试函数或 fixture 完成后撤销。raising 参数决定如果设置/删除操作的目标不存在,是否会引发 KeyErrorAttributeError

考虑以下场景:

1. 为测试修改函数行为或类属性,例如,您有一个 API 调用或数据库连接,在测试中不会执行,但您知道预期的输出应该是什么。使用 monkeypatch.setattr 使用您期望的测试行为修补函数或属性。这可以包括您自己的函数。使用 monkeypatch.delattr 在测试中删除函数或属性。

2. 修改字典的值,例如,您有一个全局配置,想为某些测试用例进行修改。使用 monkeypatch.setitem 修补测试中的字典。monkeypatch.delitem 可用于删除项。

3. 修改测试的环境变量,例如,测试在环境变量缺失时程序行为,或将多个值设置为已知变量。monkeypatch.setenvmonkeypatch.delenv 可用于这些修补。

4. 使用 monkeypatch.setenv("PATH", value, prepend=os.pathsep) 修改 $PATH,并使用 monkeypatch.chdir 在测试期间更改当前工作目录的上下文。

5. 使用 monkeypatch.syspath_prepend 修改 sys.path,这也会调用 pkg_resources.fixup_namespace_packagesimportlib.invalidate_caches()

6. 使用 monkeypatch.context 仅在特定作用域内应用修补,这有助于控制复杂 fixture 的清理或对标准库 (stdlib) 的修补。

有关 monkeypatch 博客文章 的介绍材料及其动机的讨论。

Monkeypatching 函数

考虑一个您正在处理用户目录的场景。在测试环境中,您不希望测试依赖于正在运行的用户。monkeypatch 可以用于修补依赖于用户的函数,使其始终返回特定值。

在这个示例中,monkeypatch.setattr 用于修补 Path.home,以便在运行测试时始终使用已知的测试路径 Path("/abc")。这消除了测试对正在运行用户的任何依赖。必须在调用将使用修补函数的函数之前调用 monkeypatch.setattr。测试函数完成后,Path.home 的修改将被撤销。

# contents of test_module.py with source code and the test
from pathlib import Path


def getssh():
    """Simple function to return expanded homedir ssh path."""
    return Path.home() / ".ssh"


def test_getssh(monkeypatch):
    # mocked return function to replace Path.home
    # always return '/abc'
    def mockreturn():
        return Path("/abc")

    # Application of the monkeypatch to replace Path.home
    # with the behavior of mockreturn defined above.
    monkeypatch.setattr(Path, "home", mockreturn)

    # Calling getssh() will use mockreturn in place of Path.home
    # for this test with the monkeypatch.
    x = getssh()
    assert x == Path("/abc/.ssh")

Monkeypatching 返回对象:构建 mock 类

monkeypatch.setattr 可以与类结合使用,以模拟函数返回的对象而不是值。想象一个简单的函数,它接受一个 API URL 并返回 JSON 响应。

# contents of app.py, a simple API retrieval example
import requests


def get_json(url):
    """Takes a URL, and returns the JSON."""
    r = requests.get(url)
    return r.json()

出于测试目的,我们需要模拟 r,即返回的响应对象。模拟的 r 需要一个 .json() 方法,该方法返回一个字典。这可以通过在我们的测试文件中定义一个类来表示 r 来完成。

# contents of test_app.py, a simple test for our API retrieval
# import requests for the purposes of monkeypatching
import requests

# our app.py that includes the get_json() function
# this is the previous code block example
import app


# custom class to be the mock return value
# will override the requests.Response returned from requests.get
class MockResponse:
    # mock json() method always returns a specific testing dictionary
    @staticmethod
    def json():
        return {"mock_key": "mock_response"}


def test_get_json(monkeypatch):
    # Any arguments may be passed and mock_get() will always return our
    # mocked object, which only has the .json() method.
    def mock_get(*args, **kwargs):
        return MockResponse()

    # apply the monkeypatch for requests.get to mock_get
    monkeypatch.setattr(requests, "get", mock_get)

    # app.get_json, which contains requests.get, uses the monkeypatch
    result = app.get_json("https://fakeurl")
    assert result["mock_key"] == "mock_response"

monkeypatch 使用我们的 mock_get 函数对 requests.get 应用模拟。mock_get 函数返回 MockResponse 类的一个实例,该实例有一个 json() 方法,被定义为返回一个已知的测试字典,并且不需要任何外部 API 连接。

您可以根据您正在测试的场景构建具有适当复杂度的 MockResponse 类。例如,它可以包含一个始终返回 Trueok 属性,或者根据输入字符串从模拟的 json() 方法返回不同的值。

此模拟可以通过使用 fixture 在测试之间共享。

# contents of test_app.py, a simple test for our API retrieval
import pytest
import requests

# app.py that includes the get_json() function
import app


# custom class to be the mock return value of requests.get()
class MockResponse:
    @staticmethod
    def json():
        return {"mock_key": "mock_response"}


# monkeypatched requests.get moved to a fixture
@pytest.fixture
def mock_response(monkeypatch):
    """Requests.get() mocked to return {'mock_key':'mock_response'}."""

    def mock_get(*args, **kwargs):
        return MockResponse()

    monkeypatch.setattr(requests, "get", mock_get)


# notice our test uses the custom fixture instead of monkeypatch directly
def test_get_json(mock_response):
    result = app.get_json("https://fakeurl")
    assert result["mock_key"] == "mock_response"

此外,如果模拟被设计为应用于所有测试,则 fixture 可以移动到 conftest.py 文件并使用 autouse=True 选项。

全局修补示例:阻止“requests”库进行远程操作

如果您想阻止“requests”库在所有测试中执行 HTTP 请求,您可以这样做:

# contents of conftest.py
import pytest


@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
    """Remove requests.sessions.Session.request for all tests."""
    monkeypatch.delattr("requests.sessions.Session.request")

这个 autouse fixture 将为每个测试函数执行,它将删除方法 request.session.Session.request,以便测试中任何创建 HTTP 请求的尝试都将失败。

注意

请注意,不建议修补 opencompile 等内置函数,因为它可能会破坏 pytest 的内部机制。如果无法避免,传递 --tb=native--assert=plain--capture=no 可能会有所帮助,尽管不能保证。

注意

请注意,修补 stdlib 函数和 pytest 使用的一些第三方库可能会破坏 pytest 本身,因此在这些情况下,建议使用 MonkeyPatch.context() 将修补限制在您想要测试的代码块中

import functools


def test_partial(monkeypatch):
    with monkeypatch.context() as m:
        m.setattr(functools, "partial", 3)
        assert functools.partial == 3

有关详细信息,请参阅 #3290

Monkeypatching 环境变量

如果您正在使用环境变量,通常需要为了测试目的安全地更改其值或从系统中删除它们。monkeypatch 提供了使用 setenvdelenv 方法来实现此目的的机制。我们的示例代码:

# contents of our original code file e.g. code.py
import os


def get_os_user_lower():
    """Simple retrieval function.
    Returns lowercase USER or raises OSError."""
    username = os.getenv("USER")

    if username is None:
        raise OSError("USER environment is not set.")

    return username.lower()

有两种潜在路径。首先,USER 环境变量被设置为一个值。其次,USER 环境变量不存在。使用 monkeypatch 可以安全地测试这两种路径,而不会影响正在运行的环境。

# contents of our test file e.g. test_code.py
import pytest


def test_upper_to_lower(monkeypatch):
    """Set the USER env var to assert the behavior."""
    monkeypatch.setenv("USER", "TestingUser")
    assert get_os_user_lower() == "testinguser"


def test_raise_exception(monkeypatch):
    """Remove the USER env var and assert OSError is raised."""
    monkeypatch.delenv("USER", raising=False)

    with pytest.raises(OSError):
        _ = get_os_user_lower()

这种行为可以移入 fixture 结构并在测试之间共享。

# contents of our test file e.g. test_code.py
import pytest


@pytest.fixture
def mock_env_user(monkeypatch):
    monkeypatch.setenv("USER", "TestingUser")


@pytest.fixture
def mock_env_missing(monkeypatch):
    monkeypatch.delenv("USER", raising=False)


# notice the tests reference the fixtures for mocks
def test_upper_to_lower(mock_env_user):
    assert get_os_user_lower() == "testinguser"


def test_raise_exception(mock_env_missing):
    with pytest.raises(OSError):
        _ = get_os_user_lower()

Monkeypatching 字典

monkeypatch.setitem 可用于在测试期间安全地将字典的值设置为特定值。以这个简化的连接字符串示例为例:

# contents of app.py to generate a simple connection string
DEFAULT_CONFIG = {"user": "user1", "database": "db1"}


def create_connection_string(config=None):
    """Creates a connection string from input or defaults."""
    config = config or DEFAULT_CONFIG
    return f"User Id={config['user']}; Location={config['database']};"

出于测试目的,我们可以将 DEFAULT_CONFIG 字典修补为特定值。

# contents of test_app.py
# app.py with the connection string function (prior code block)
import app


def test_connection(monkeypatch):
    # Patch the values of DEFAULT_CONFIG to specific
    # testing values only for this test.
    monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user")
    monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db")

    # expected result based on the mocks
    expected = "User Id=test_user; Location=test_db;"

    # the test uses the monkeypatched dictionary settings
    result = app.create_connection_string()
    assert result == expected

您可以使用 monkeypatch.delitem 来删除值。

# contents of test_app.py
import pytest

# app.py with the connection string function
import app


def test_missing_user(monkeypatch):
    # patch the DEFAULT_CONFIG t be missing the 'user' key
    monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)

    # Key error expected because a config is not passed, and the
    # default is now missing the 'user' entry.
    with pytest.raises(KeyError):
        _ = app.create_connection_string()

fixture 的模块化特性为您提供了灵活性,可以为每个潜在的模拟定义单独的 fixture,并在需要的测试中引用它们。

# contents of test_app.py
import pytest

# app.py with the connection string function
import app


# all of the mocks are moved into separated fixtures
@pytest.fixture
def mock_test_user(monkeypatch):
    """Set the DEFAULT_CONFIG user to test_user."""
    monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user")


@pytest.fixture
def mock_test_database(monkeypatch):
    """Set the DEFAULT_CONFIG database to test_db."""
    monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db")


@pytest.fixture
def mock_missing_default_user(monkeypatch):
    """Remove the user key from DEFAULT_CONFIG"""
    monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)


# tests reference only the fixture mocks that are needed
def test_connection(mock_test_user, mock_test_database):
    expected = "User Id=test_user; Location=test_db;"

    result = app.create_connection_string()
    assert result == expected


def test_missing_user(mock_missing_default_user):
    with pytest.raises(KeyError):
        _ = app.create_connection_string()

API 参考

查阅 MonkeyPatch 类的文档。