【发布时间】:2019-04-02 19:31:57
【问题描述】:
我试图在我的 Python 测试用例中模拟 elasticsearch.Elasticsearch.indices.exists 函数,但我收到以下导入错误。但是,仅模拟 elasticsearch.Elasticsearch 工作正常。
@ddt
class TestElasticSearchConnector(unittest.TestCase):
@patch('elasticsearch.Elasticsearch.indices.exists')
@patch('connectors.elastic_search_connector.ElasticSearchConnector._get_local_conn')
def test_check_index(self, mock_es, _get_local_conn):
mock_es = Mock()
mock_es._index_exists = False
mock_es.indices.exists.return_value = True
mock_es.create.return_value = {'result': 'created'}
在此处获取模拟导入错误
================================================ ======================== 错误:test_check_index (tests.base.TestESConnector) -------------------------------------------------- -------------------- 回溯(最近一次通话最后): _dot_lookup 中的文件“/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py”,第 1197 行 返回getattr(事物,comp) AttributeError:类型对象“Elasticsearch”没有属性“索引”
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1297, in patched
arg = patching.__enter__()
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1353, in __enter__
self.target = self.getter()
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1523, in <lambda>
getter = lambda: _importer(target)
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1210, in _importer
thing = _dot_lookup(thing, comp, import_path)
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1199, in _dot_lookup
__import__(import_path)
ModuleNotFoundError: No module named 'elasticsearch.Elasticsearch'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
测试导入
>> user$ python
Python 3.6.1 (default, May 10 2017, 09:46:05)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from elasticsearch import Elasticsearch
>>>
>>>
【问题讨论】:
标签: python elasticsearch mocking