python - 模拟使用相对导入导入的模块的日志记录

标签 python unit-testing mocking

由于我们项目的结构和我们运行测试的方式,我们的库模块是通过测试模块导入的,例如:

from .. import foo_bar

现在,我想检查 foo_bar 模块中的函数是否针对某些参数发出警告。我试过这个:

from unittest.mock import patch

@patch('foo_bar.logging')
def test_distance(mock_logging):
    foo_bar.baz(None)
    assert mock_logging.warn.called

我得到了这个:

target = 'foo_bar'

    def _importer(target):
        components = target.split('.')
        import_path = components.pop(0)
>       thing = __import__(import_path)
E       ImportError: No module named 'foo_bar'

/tmp/envs/foo/lib/unittest/mock.py:1058: ImportError

当我尝试像这样更改补丁行时:

@patch('..foo_bar.logging')

我遇到了这个错误:

target = '..foo_bar'

    def _importer(target):
        components = target.split('.')
        import_path = components.pop(0)
>       thing = __import__(import_path)
E       ValueError: Empty module name

/tmp/envs/foo/lib/unittest/mock.py:1058: ValueError

知道如何在这些情况下使用 unittest.mock 中的 patch 函数吗?

最佳答案

您可以使用导入模块的__name__ 属性来实现相对导入模拟。

@patch(foo_bar.__name__ + '.logging')
def test_distance(mock_logging):
    ...

关于python - 模拟使用相对导入导入的模块的日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45799398/

相关文章:

python - Excel 文件未显示在 Google 云端硬盘中

c++ - parasoft C++ 单元测试题

c++ - 如何在模拟期望中调用 const std::function<> 和参数?

java - 模拟不起作用

methods - 防止equals方法的 stub

functional-programming - 是否有 Python 惯用语用于评估具有短路的函数/表达式列表?

python - 为什么刷新缓冲区中存储的字符很重要?

testing - 如何在 Haskell 中模拟测试?

python - 如何合并具有不同频率的字符串时间戳的数据帧

ruby-on-rails - 由于命名空间冲突而无法测试 RSpec?