如何使用 pytest monkeypatch 来修补 class
How does one use pytest monkeypatch to patch a class
我想使用 [pytest monkeypatch][1] 模拟一个 class 被导入
到一个单独的模块中。这真的可能吗?如果可能的话,如何做到这一点?似乎我还没有看到这种确切情况的例子。假设您有一个应用程序并在 something.py
中导入了 class 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
测试了这个,对我有用:
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
我想使用 [pytest monkeypatch][1] 模拟一个 class 被导入 到一个单独的模块中。这真的可能吗?如果可能的话,如何做到这一点?似乎我还没有看到这种确切情况的例子。假设您有一个应用程序并在 something.py
中导入了 class Afrom 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
测试了这个,对我有用:
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