简体   繁体   English

Pytest Monkeypatch 不适用于进口 Function

[英]Pytest Monkeypatch Doesn't Apply To Imported Function

I have a module set up roughly as follows:我有一个模块设置大致如下:

# foo.py
def generate_things_based_on_other_things():
  # some nasty things here

# bar.py
from foo import generate_things_based_on_other_things as generate

def coo():
  generate()

# conftest.py
import pytest

@pytest.fixture(autouse=True)
def patch_generate(monkeypatch):
  def mock_generate():
    print("hello!")

  monkeypatch.setattr("app.bar.generate", mock_generate)

# test_bar.py
from bar import coo

def test_coo():
  coo()

As per this answer I made sure to monkeypatch the actual imported instance of the function.根据这个答案,我确保对 function 的实际导入实例进行猴子补丁。 Any other path throws a "does not exist on module" error.任何其他路径都会引发"does not exist on module"错误。 However when I run the test I hit an error, because the original function generate is being called, despite it being monkeypatched.然而,当我运行测试时,我遇到了一个错误,因为原始的 function generate正在被调用,尽管它被猴子补丁。 I can't figure out why this patch won't stick the way I expect it too.我不明白为什么这个补丁也不会像我期望的那样坚持下去。 I would expect this test to print "hello.".我希望这个测试能打印出“hello.”。

Your paths seem not to match.你的路径似乎不匹配。 You do from bar import coo , but use setattr with app.bar .from bar import coo执行,但将setattrapp.bar一起使用。 To be sure, you can use the other form of setattr instead, which takes the object and the attribute names separately, eg:可以肯定的是,您可以使用另一种形式的setattr ,它分别采用 object 和属性名称,例如:

import bar  # or "from app import bar", whichever is correct for you

@pytest.fixture(autouse=True)
def patch_generate(monkeypatch):
    def mock_generate():
        print("hello!")

    monkeypatch.setattr(bar, "generate", mock_generate)

This way you can be reasonably sure that you are patching the correct object.这样您就可以合理地确定您正在修补正确的 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM