pytest:使用假设时的monkeypatch

问题描述

在单元测试中,我使用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 ,没有警告。

,

使用monkeypatch context manager

@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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...