如何使用 pytest Monkeypatch 来修补类

use*_*643 11 python monkeypatching class pytest

我想使用 [pytest Monkeypatch][1] 来模拟导入到单独模块中的类。这实际上可能吗?如果可能的话,如何做到这一点?我似乎还没有看到这种具体情况的例子。假设您有一个应用程序并在 Something.py 中导入了 A 类

from something import A #Class is imported

class B :
  def __init__(self) :
   self.instance = A() #class instance is created

  def f(self, value) :
    return self.instance.g(value)
Run Code Online (Sandbox Code Playgroud)

在我的 test.py 中我想在 B 中模拟 A

from something import B

#this is where I would mock A such that
def mock_A :
  def g(self, value) :
    return 2*value

#Then I would call B
c = B()
print(c.g(2)) #would be 4

I see how monkeypatch can be used to patch instances of classes, but how is it done for classes that have not yet been instantiated?  Is it possible?  Thanks!

  [1]: https://docs.pytest.org/en/latest/monkeypatch.html
Run Code Online (Sandbox Code Playgroud)

yed*_*tko 7

测试过这个,对我有用:

def test_thing(monkeypatch):
    def patched_g(self, value):
        return value * 2

    monkeypatch.setattr(A, 'g', patched_g)
    b = B()
    assert b.f(2) == 4
Run Code Online (Sandbox Code Playgroud)

  • 我不明白为什么这是批准的答案。当然它可以工作,但是您是否需要为每个属性执行“monkeypath”?创建一个包含所需方法的模拟类并通过一次调用 Monkeypatch 来使用完整的类而不是多次调用会更简单。不是吗? (5认同)