【问题标题】:How to use fudge.patch with pytest如何在 pytest 中使用 fudge.patch
【发布时间】:2018-03-23 03:36:38
【问题描述】:

我正在从 nose 切换到 pytest 并且在使用 fudge 创建模拟/伪造时遇到问题,因为 @fudge.patch 将它们传递给测试函数,但 pytest 将测试函数参数解释为固定装置。

我想知道 pytest 和 fudge 是否从根本上不兼容,或者我是否缺少一个技巧。我更喜欢 fudge 而不是 mock,因为它允许您在测试之前更直观地设置期望值,所有这些都在一个地方进行,而 mock 通过在测试之前定义返回值和之后定义预期调用来拆分事物。

有了鼻子,我可以像这样用fudge.Fake 进行猴子补丁:

from datetime import datetime
from fudge import patch

def today():
    return datetime.utcnow()

def something():
    return today()

test_time = datetime(2018, 1, 1, 12, 34, 56)

@patch('today')
def test_something(fake_today):
    fake_today.expects_call().returns(test_time)
    result = something()
    assert result == test_time

请注意 fudge 如何让您在一个地方设置预期调用和虚假返回,我发现这比 mock 更直观。

但是,使用 pytest 会引发异常,因为 pytest 将测试函数的参数解释为夹具,并且不知道名为 fake_today 的夹具:

test setup failed
file example.py, line 13
  @patch('today')
  def test_something(fake_today):
E       fixture 'fake_today' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_xml_attribute, record_xml_property, recwarn, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

我可以将fake_today 声明为夹具,但我认为 pytest 不会检查期望值,如果这样做了,那么无论在何处使用夹具,它都会始终具有相同的期望值,这并不总是有意义的。

我可以在测试函数中使用monkeypatch 夹具来注入Fakes,但这不如使用装饰器那么简洁。

我还可以像这样定义返回 Fake 的固定装置:

@pytest.fixture
def request(monkeypatch):
    """
    Fake Session.request method so tests can mock expected REST requests.
    """
    fake_request = fudge.Fake()
    monkeypatch.setattr('requests.sessions.Session.request', fake_request)
    yield fake_request
    fudge.verify()

但是你必须为你想要注入的每个Fake 这样做,这看起来很笨重。

不知道什么是最好的方法。

【问题讨论】:

    标签: python pytest fudge


    【解决方案1】:

    根据this issue comment fudge 不打算与 pytest 兼容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-16
      • 2023-01-27
      • 2021-11-30
      • 1970-01-01
      • 2020-10-11
      相关资源
      最近更新 更多