私は、多くのChildX
クラスによって継承されるParent
クラスを持っています。親クラスを模擬して
class Parent(object): # the class that should be mocked
def __init__(self):
assert False # should never happen, because we're supposed to use the mock instead
class Child1(Parent):
def method_1(self):
return 3
class MockParent(object): # this one should replace Parent
def __init__(self):
assert True
私はpytestで実行するテストスイートを持っている、と私は確信してこれらのテストの間に、ということにしたい、毎回ChildX
がインスタンス化され、インスタンスがMockParent
のメソッドの代わりにParent
のものを呼ぶだろう(私は上記の例を多く簡略化したが、__init__
メソッドのみが関係するわけではない)。私はやることができたすべてを一つおきChildX
クラス1にパッチを適用した瞬間のために
、:
class FixturePatcher(object):
def __init__(self, klass):
self.klass = klass
self.patcher = None
def __enter__(self):
self.patcher = mock.patch.object(self.klass, '__bases__', (MockParent,))
return self.patcher.__enter__()
def __exit__(self, *_, **__):
self.patcher.is_local = True
@pytest.fixture()
def mock_parent_on_child1():
with FixturePatcher(Child1):
return Child1()
def test_mock_child1(mock_parent_on_child1):
assert mock_parent_on_child1.method_1() == 3
しかし、私は多くのChildX
のクラスを持って、時にはChildY
がChildZ
のメソッド内でインスタンス化して使用されています私はそれらすべてにパッチを当てることはできません。
Parent
をMockParent
に置き換えようと多くのことを試みましたが、いずれも機能しませんでした。私の失敗した試みのいくつかは次のとおりです:
@mock.patch('src.parent.Parent', MockParent)
def test_mock_parent():
assert Child1().method_1() == 3 # Parent's __init__ method is still called
@mock.patch('src.parent.Parent.__getattribute__', lambda self, name: MockParent.__getattribute__(self, name))
def test_mock_parent():
assert Child1().method_1() == 3 # same results here
def test_mock_parent(monkeypatch):
monkeypatch.setattr('src.parent.Parent', MockParent)
assert Child1().method_1() == 3 # and still the same here
これは可能ですか?私はpython2.7と最新バージョンのpytest
とmock
を使用しています。
私は本当にこの本当の意味でこの試みを試み、それがうまくいくかどうか教えてください! – julienc
私はいくつかの回避策を実行しなければなりませんでしたが、ついにそれを作ったのです!私は '__subclasses__'に出会ったことはありません。それは魅力のように機能します! – julienc