如何在Pytest中模拟(monkeypatch)ContextVar



我目前在我的FastApi项目中使用asgi_correlation_id python包。此包公开了一个名为correlation_id的ContextVar。

用法很简单:

from asgi_correlation_id.context import correlation_id
id = correlation_id.get()

现在,正是这一行,我想为我的pytests进行猴痘。

以下是我一整天都在尝试的东西:

#try1
def mock_correlation_id():
return 123456
monkeypatch.setattr(correlation_id, "get", mock_correlation_id)
#try2
def mock_correlation_id():
return None
monkeypatch.setattr("asgi_correlation_id.context.correlation_id.get", mock_correlation_id)
#try3
def mock_correlation_id():
return mock_id.get()
mock_id = ContextVar("mock_id", default=None)
monkeypatch.setattr("asgi_correlation_id.context.correlation_id.get", mock_correlation_id)
#try4
monkeypatch.setattr("asgi_correlation_id.context.correlation_id.get", lambda: None)
#try5
monkeypatch.setattr("asgi_correlation_id.context.correlation_id.get", lambda: 1234567)

但每一次,我都会遇到同样的错误:

Attribute error: 'ContextVar' object attribute 'get' is read-only.
/pythonpath/_pytest/monkeypatch.py:360: Attribute Error

我很惊讶,我在网上找不到任何嘲讽上下文的实现。有人能帮我吗?

使用set()reset()方法是否适用?

from contextvars import ContextVar
c = ContextVar("my_var")
c.set("old_val")

async def test_var():
assert c.get() == "old_val"
token = c.set("new_val")
assert c.get() == "new_val"
c.reset(token)
assert c.get() == "old_val"

相关内容

  • 没有找到相关文章

最新更新