【问题标题】:How does one use pytest monkeypatch to patch a class如何使用 pytest monkeypatch 修补一个类
【发布时间】:2020-04-07 01:07:24
【问题描述】:

我想使用 [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)

在我的 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

【问题讨论】:

    标签: python class pytest monkeypatching


    【解决方案1】:

    对此进行了测试,对我有用:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-12-30
      • 1970-01-01
      • 2017-11-23
      • 2017-01-27
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多