0

我正在尝试使用我的errbot测试来修补依赖项。我遇到的问题是 errbot 如何导入模块。它不是静态的,并且在我添加测试或它们以不同的顺序测试时会破坏我的补丁装饰器。

我有一个名为 EDB (edb.py) 的插件。在 edb.py 中,我使用import pyedb. 这位于我的site-packages.

我有我的测试文件 test_edb.py 我尝试像这样修补我的测试方法

pytest_plugins = ["errbot.backends.test"]
extra_plugin_dir = '.'

from unittest.mock import patch  # noqa: E402

@patch('yapsy_loaded_plugin_EDB_1.pyedb', autospec=True)
def test_edb_testlist(pyedb_mock, testbot):
    testbot.push_message('!edb testlist')

    assert "Okay, let me get..." == testbot.pop_message()
    assert "I don't see any..." == testbot.pop_message()

Errbotyapsy_loaded_plugin_EDB_<xx>为模块导入添加了此路径,但 xx 取决于运行测试的顺序。这不起作用,我需要一些静态导入路径mypath.pyedb

我希望有一种不同的方法来解决这个问题。也许我可以更改导入模块的方式,使其不依赖于 errbot 导入?

这是Errbot 测试的链接以供参考。

4

1 回答 1

0

我的解决方案感觉有点老套,但它确实有效。如果有人有更优雅的解决方案,请分享。如果没有其他回复,我会在一段时间后接受我自己的答案。

所以我以前遇到过这个问题,但我想我仍然不够熟悉 Python 中的补丁是如何工作的,知道在哪里打补丁。在阅读了“在哪里修补”文档后(再次:))我有一个解决方法,因为使用 errbot 进行动态导入。

errbot 项目文件夹看起来像

errbot-project/
├── data/
│   ├── ...
├── plugins/
│   ├── plugin1/
|       ├── ...
|   ├── plugin2/
|       ├── ...

我注意到,当 errbot 运行项目目录../errbot-project和所有插件目录(例如../errbot-project/plugins/plugin1)时,都会添加到sys.path.

所以我在我的项目目录中添加了一个包,并将它导入到我的插件中。然后我可以从该包中可靠地修补我的依赖项。再次阅读Where to Patch文档以获得完整的解释。它看起来像这样。

errbot-project/
├── data/
│   ├── ...
├── plugins/
│   ├── plugin1/
|       ├── ...
|   ├── plugin2/
|       ├── ...
├── plugin_deps/
|       ├── __init__.py

我的../errbot-project/plugin_deps/__init__.py样子

...
import dep1
import dep2
...

然后在我的插件中我使用

...
import plugin_deps as pdep
...
def method():
    pdep.dep1.method()
...
# note, you cannot use 
# from plugin_deps import dep1
# this changes 'where' python looks up the module and
# and 'breaks' your patch 

最后我的测试代码看起来像

@patch('plugin_deps.dep1', autospec=True) 
def test_get_tl_tabulation(my_mock, testbot):
    # test code here
于 2017-10-30T12:04:53.420 回答