如何对模块和环境进行猴子补丁/模拟¶
有时测试需要调用依赖于全局设置的功能,或者调用不易测试的代码,例如网络访问。monkeypatch fixture 帮助你安全地设置/删除属性、字典项或环境变量,或者修改sys.path用于导入。
monkeypatch fixture 为在测试中安全地打补丁和模拟功能提供了以下辅助方法
所有修改将在请求测试函数或 fixture 完成后撤消。raising 参数决定如果设置/删除操作的目标不存在是否会引发KeyError或AttributeError。
考虑以下场景
1. 为测试修改函数行为或类的属性,例如,你不会为测试进行 API 调用或数据库连接,但你知道预期的输出应该是什么。使用monkeypatch.setattr用你期望的测试行为来修补函数或属性。这可以包括你自己的函数。使用monkeypatch.delattr为测试移除函数或属性。
2. 修改字典的值,例如,你有一个全局配置,你想为某些测试用例修改它。使用monkeypatch.setitem为测试修补字典。monkeypatch.delitem可用于移除项。
3. 为测试修改环境变量,例如,测试程序在缺少环境变量时的行为,或为已知变量设置多个值。monkeypatch.setenv和monkeypatch.delenv可用于这些补丁。
4. 使用monkeypatch.setenv("PATH", value, prepend=os.pathsep)修改$PATH,并使用monkeypatch.chdir在测试期间更改当前工作目录的上下文。
5. 使用monkeypatch.syspath_prepend修改sys.path,这也会调用pkg_resources.fixup_namespace_packages和importlib.invalidate_caches()。
6. 使用monkeypatch.context仅在特定范围应用补丁,这有助于控制复杂 fixture 的拆卸或对标准库的补丁。
请参阅猴子补丁博客文章,了解一些介绍材料和对其动机的讨论。
猴子补丁函数¶
考虑一个你正在使用用户目录的场景。在测试的背景下,你不希望你的测试依赖于正在运行的用户。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")
猴子补丁返回对象:构建模拟类¶
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类。例如,它可以包含一个始终返回True的ok属性,或者根据输入字符串从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”库在所有测试中执行 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")
此自动使用 fixture 将为每个测试函数执行,它将删除方法request.session.Session.request,以便测试中任何创建 http 请求的尝试都将失败。
注意
请注意,不建议修补内置函数,例如open、compile等,因为它可能会破坏 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。
猴子补丁环境变量¶
如果你正在使用环境变量,你经常需要安全地更改值或从系统中删除它们以进行测试。monkeypatch提供了使用setenv和delenv方法来执行此操作的机制。我们的示例代码来测试
# 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()
猴子补丁字典¶
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类的文档。