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)
测试过这个,对我有用:
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)