[英]how to mock an elasticsearch object in pytest test?
我有一個 class 處理與 elasticsearch 的連接並使用elasticsearch 庫。 我正在嘗試在 pytest 單元測試中使用pytest_elasticsearch模擬 elasticsearch object。 我不太確定如何 go 關於這個。
我試過這個:
import pytest
from pytest_elasticsearch import factories
elasticsearch_proc = factories.elasticsearch_proc(port=-1,
index_store_type='fs')
elasticsearch = factories.elasticsearch('elasticsearch_proc')
class TestSuccessResponses:
@pytest.fixture()
def create_es_index(self, elasticsearch):
elasticsearch.indices.create(index='test-index')
def test_insert_record(self, elasticsearch):
elasticsearch.create('test-index', '1', {'id': '1',
'type': 'Scrambled'}, refresh=True)
custom_query = {"size": 10, "query": {"match_all": {}}}
actual_response = es_client.client_query(elasticsearch, 'test-index', custom_query)
print(actual_response)
我收到此錯誤:
test setup failed
self = <[AttributeError("'ElasticSearchExecutor' object has no attribute 'command'") raised in repr()] ElasticSearchExecutor object at 0x7fb8289d4fa0>
我不知道如何解決這個問題以及如何前進。
我使用aioresponses
( https://github.com/pnuckowski/aioresponses )管理並直接模擬了應該執行的 HTTP 請求。
import mock
import pytest
#from mock patch elasticsearch to get the transcript
@pytest.fixture(scope="session")
def es():
es_mock = mock.patch('elasticsearch.Elasticsearch.get')
return es_mock
def test_get_transcript(es):
es.return_value = {
"_source ": {"transcriptid": "78376763-c9d4-455e-a093-ae3cbcfe8a6b",
"multiple_speaker_term":[
{
"speaker": 1,
"start": 0.0,
"end": 1.0,
"content": "hello world",
}]}
}
assert es.return_value != None
print(es.return_value)
#也可以傳入一個object來讀取.json文件作為es.return_value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.