【问题标题】:Pytest Monkeypatch Doesn't Apply To Imported FunctionPytest Monkeypatch 不适用于导入的函数
【发布时间】:2022-01-02 02:12:44
【问题描述】:

我有一个模块设置大致如下:

# 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()

根据this answer,我确保对函数的实际导入实例进行猴子补丁。任何其他路径都会引发 "does not exist on module" 错误。 然而,当我运行测试时,我遇到了一个错误,因为原始函数 generate 正在被调用,尽管它已被猴子补丁。 我不明白为什么这个补丁也不会像我期望的那样坚持下去。 我希望这个测试能打印出“hello!”。

【问题讨论】:

    标签: python pytest monkeypatching


    【解决方案1】:

    您的路径似乎不匹配。您使用from bar import coo,但使用setattrapp.bar。可以肯定的是,您可以改用其他形式的setattr,它将对象和属性名称分开,例如:

    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)
    

    这样您可以合理地确定您正在修补正确的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2012-06-26
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多