问题描述
在单元测试中,我使用monkeypatch
来更改dict
中的条目。
from hypothesis import given,strategies
test_dict = {"first": "text1","second": "text2"}
@given(val=strategies.text())
def test_monkeypath(monkeypatch,val):
monkeypatch.setitem(test_dict,"second",val)
assert isinstance(test_dict["second"],str)
测试通过,但是用pytest
执行以下测试代码时,我得到警告。
=================================================================================================================== warnings summary ====================================================================================================================
.PyCharm2019.2/config/scratches/hypothesis_monkeypatch.py::test_monkeypath
c:\users\d292498\appdata\local\conda\conda\envs\pybt\lib\site-packages\hypothesis\extra\pytestplugin.py:172: HypothesisDeprecationWarning: .PyCharm2019.2/config/scratches/hypothesis_monkeypatch.py::test_monkeypath uses the 'monkeypatch' fixture,wh
ich is reset between function calls but not between test cases generated by `@given(...)`. You can change it to a module- or session-scoped fixture if it is safe to reuse; if not we recommend using a context manager inside your test function. See h
ttps://docs.pytest.org/en/latest/fixture.html#sharing-test-data for details on fixture scope.
note_deprecation(
-- Docs: https://docs.pytest.org/en/stable/warnings.html
============================================================================================================= 1 passed,1 warning in 0.30s ==============================================================================================================
这是否意味着dict的值将只更改一次,而不管hypothesis
会生成多少个测试用例?
我不确定在这种情况下如何使用上下文管理器。有人可以指出我正确的方向吗?
解决方法
您的问题是,对于所有测试调用,该字典仅被修补一次,并且假设向您发出警告。如果您在monkeypatch.setitem
行之前有任何逻辑,那就太糟糕了!
您可以通过using monkeypatch directly来解决此问题,而不是通过治具:
from hypothesis import given,strategies
from _pytest.monkeypatch import MonkeyPatch
test_dict = {"first": "text1","second": "text2"}
@given(val=strategies.text())
def test_monkeypath(val):
assert test_dict["second"] == "text2" # this would fail in your version
with MonkeyPatch().context() as mp:
mp.setitem(test_dict,"second",val)
assert test_dict["second"] == val
assert test_dict["second"] == "text2"
et voila ,没有警告。
,@given(val=strategies.text())
def test_monkeypath(monkeypatch,val):
with monkeypatch.context() as m:
m.setitem(test_dict,val)
assert isinstance(test_dict["second"],str)