简体   繁体   English

如何使用 side_effect 修补对象的属性

[英]How to patch an object's attributes with `side_effect`

So I have a file some_class.py with:所以我有一个文件some_class.py

class SomeReader:
    def read_path(self, url):
        return "read_path"


class SomeClass:
    def __init__(self, url):
        self.reader = SomeReader(url)
        print(self.reader.read_path(""))

And a test file some_class_test.py :还有一个测试文件some_class_test.py

from some_class import SomeClass, SomeReader

@patch("some_class.SomeReader")
def test_some_class(mock_some_reader):
    def mock_read_path(url):
        return "mock_read_path"

    mock_some_reader.read_path.side_effect = mock_read_path

    SomeClass("")

I'm expecting that when I run this test, it will print mock_read_path but instead it prints <MagicMock name='SomeReader().read_path()' id='140701381288480'> .我期望当我运行这个测试时,它会打印mock_read_path而是打印<MagicMock name='SomeReader().read_path()' id='140701381288480'> How do I fix this?我该如何解决? I want to mock both the class initialization of SomeReader , hence I use @patch("some_class.SomeReader") .我想模拟 SomeReader 的SomeReader初始化,因此我使用@patch("some_class.SomeReader") But I also want to mock the read_path function of SomeReader , hence I have mock_some_reader.read_path.side_effect = mock_read_path but that doesn't seem to work.但我也想模拟read_path的 read_path SomeReader ,因此我有mock_some_reader.read_path.side_effect = mock_read_path但这似乎不起作用。

What you're doing is making a mock of the class itself, not the instances of the classes.您正在做的是模拟 class 本身,而不是类的实例。 The mock replaces call to instantiate SomeReader(url) (basically replacing the __init__ method of the class).模拟替换调用以实例化SomeReader(url) (基本上替换类的__init__方法)。

What you want to do is then mock the return value of the fake instance being created by SomeReader(url)然后你要做的是模拟SomeReader(url)创建的假实例的返回值

@patch("some_class.SomeReader")
def test_some_class(mock_some_reader):
    def mock_read_path(url):
        return "mock_read_path"

    mock_some_reader.return_value.read_path.side_effect = mock_read_path

    SomeClass("")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM