“从”样式导入如何处理导入模块的依赖性?

时间:2019-04-26 23:37:24

标签: python import module mocking pytest

我试图弄清楚python导入系统别名是使用'from'关键字导入的模块的依赖项。

特别是,我的用例是编写unittest.mock.patch语句,以模拟使用“从”导入的对象的属性,并且该对象使用从另一个模块导入的内容。但是,更广泛地说,我只想了解导入系统的工作原理。

通过一个例子,我的问题可能更有意义:

假设我们在某些模块a中有一些类A,它使用模块b中的类

a.py:

from b import B

class A:
    def __init__(self):
        B.use_some_static_method()

        # OR

        self.b_instance = B()

然后,例如,在某些测试代码中,我们想在测试A对象时模拟B。我将如何编写补丁声明?

test_a.py:

from a import A


def test_a(mocker):
    # Mock with pytest-mock's mocker
    mock_b = mocker.patch('<some path>')

    a = A()
    a.do_something_with_B()

我要替代什么路径?我意识到我可以简单地使用import a来代替,然后模拟a.B,但是我对理解导入系统以及它的工作方式和工作原理更加感兴趣。

0 个答案:

没有答案