由于我们项目的结构和我们运行测试的方式,我们的库模块是通过测试模块导入的,例如:
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/