我正在測驗模塊 match_view.py 中的一個函式(下)
from dbaccess.repository import bulk_update_zingr_id, bulk_insert_ingredients_matching_table
from services.matching_ingr_zingr import ingr_zing_match_mult_search
from services.FileStorage import dumpModel
from flask import Blueprint, request
from datetime import date
import pandas as pd
import logging
import time
match = Blueprint("match", __name__)
@match.route("/", methods=['GET', 'POST'], strict_slashes=False)
def index():
if request.method == 'POST':
logging.warning(""" RODAR O ELASTICSEARCH PARA INGREDIENTES ZAPLY ANTES DE RODAR O MATCHING""")
ingredients_list = request.get_json()
start = time.time()
results, resume, payload = ingr_zing_match_mult_search(ingredients_list)
today = date.today().strftime("%b-%d-%Y")
dumpModel(results.to_dict(), f"result_table_{today}")
dumpModel(resume.to_dict(), f"resume_table_{today}")
bulk_update_zingr_id(payload)
bulk_insert_ingredients_matching_table(resume)
tot_row = len(list(set(resume['Raw_Ingred'])))
end = time.time()
tempo = round(((end - start)), 4)
logging.warning(f"O tempo para processamento da request foi de: {tempo/60} minutos, {tempo/tot_row} segundos por item para {tot_row} ingredientes.")
return payload
else:
return "Use o método POST para processar os dados."
我嘗試了兩種方式。
1o嘗試模擬函式的路徑'src.api.matching.match_view.ingr_zing_match_mult_search'(運行但不要模擬)。
test_00_api.py
import pytest
import sys, os
sys.path.append(os.path.realpath(os.path.dirname(__file__) "/src"))
def test_match_view_post_retorno_correto(client, mocker):
result_expected = {'sal a gosto': 594, '1 cebola picada': 44}
mocker.patch('src.api.matching.match_view.ingr_zing_match_mult_search',
return_value=[[], [], {'sal a gosto': 594, '1 cebola picada': 44}])
RESOURCE_URL = "/match"
resp = client.post(RESOURCE_URL, json=['sal a gosto', '1 cebola picada'])
assert resp.status_code == 200
assert result_expected in resp.get_data(as_text=True)
2o 嘗試模擬路徑 'src.api.matching.index.match_view.ingr_zing_match_mult_search' 但引發錯誤(AttributeError: <function index at 0x000001A600339DC8> 沒有屬性 'ingr_zing_match_mult_search')。
test_00_api.py
import pytest
import sys, os
sys.path.append(os.path.realpath(os.path.dirname(__file__) "/src"))
def test_match_view_post_retorno_correto(client, mocker):
result_expected = {'sal a gosto': 594, '1 cebola picada': 44}
mocker.patch('src.api.matching.match_view.index.ingr_zing_match_mult_search',
return_value=[[], [], {'sal a gosto': 594, '1 cebola picada': 44}])
RESOURCE_URL = "/match"
resp = client.post(RESOURCE_URL, json=['sal a gosto', '1 cebola picada'])
assert resp.status_code == 200
assert result_expected in resp.get_data(as_text=True)
我的專案結構是:
src
|--- api
| |--- matching
| |--- match_view.py
|
tests
|--- test_src
|--- test_00_api.py
模擬函式ingr_zing_match_mult_search()的正確方法是什么?
@Macintosh_89 這是我最后一次嘗試和錯誤:
from src.api.matching import match_view
import pytest
import sys, os
sys.path.append(os.path.realpath(os.path.dirname(__file__) "/src"))
def test_match_view_post_retorno_correto(mocker, client):
result_expected = {'sal a gosto': 594, '1 cebola picada': 44}
mocker.patch('src.api.matching.match_view.ingr_match_mult_search',
return_value=[[], [], {'sal a gosto': 594, '1 cebola picada': 44}])
RESOURCE_URL = "/match"
resp = client.post(RESOURCE_URL, json=['sal a gosto', '1 cebola picada'])
assert resp.status_code == 200
assert result_expected in resp.get_data(as_text=True)
錯誤:
======================================================================================================= FAILURES =======================================================================================================
_________________________________________________________________________________________ test_match_view_post_retorno_correto _________________________________________________________________________________________
mocker = <pytest_mock.plugin.MockerFixture object at 0x0000017527CB7908>, client = <FlaskClient <Flask 'src.app'>>
def test_match_view_post_retorno_correto(mocker, client):
result_expected = {'sal a gosto': 594, '1 cebola picada': 44}
mocker.patch('src.api.matching.match_view.ingr_match_mult_search',
> return_value=[[], [], {'sal a gosto': 594, '1 cebola picada': 44}])
tests\test_src\test_00_api.py:64:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\..\..\miniconda3\envs\match_prod_ingr\lib\site-packages\pytest_mock\plugin.py:402: in __call__
**kwargs
..\..\..\miniconda3\envs\match_prod_ingr\lib\site-packages\pytest_mock\plugin.py:201: in _start_patch
mocked = p.start() # type: unittest.mock.MagicMock
..\..\..\miniconda3\envs\match_prod_ingr\lib\unittest\mock.py:1442: in start
result = self.__enter__()
..\..\..\miniconda3\envs\match_prod_ingr\lib\unittest\mock.py:1307: in __enter__
original, local = self.get_original()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <unittest.mock._patch object at 0x0000017527C8A1C8>
def get_original(self):
target = self.getter()
name = self.attribute
original = DEFAULT
local = False
try:
original = target.__dict__[name]
except (AttributeError, KeyError):
original = getattr(target, name, DEFAULT)
else:
local = True
if name in _builtins and isinstance(target, ModuleType):
self.create = True
if not self.create and original is DEFAULT:
raise AttributeError(
> "%s does not have the attribute %r" % (target, name)
)
E AttributeError: <module 'src.api.matching.match_view' from 'C:\\Users\\zaply\\Desktop\\Zaply\\matching\\src\\api\\matching\\match_view.py'> does not have the attribute 'ingr_match_mult_search'
..\..\..\miniconda3\envs\match_prod_ingr\lib\unittest\mock.py:1281: AttributeError
=============================================================================================== short test summary info ================================================================================================
FAILED tests/test_src/test_00_api.py::test_match_view_post_retorno_correto - AttributeError: <module 'src.api.matching.match_view' from 'C:\\Users\\zaply\\Desktop\\Zaply\\matching\\src\\api\\matching\\match_view.py...================================================================================================== 1 failed in 0.59s ===================================================================================================
4o嘗試測驗(運行但不模擬執行ingr_zing_match_mult_search()函式)
from src.api.matching import match_view
import pytest
import sys, os
def test_match_view_post_retorno_correto(mocker, client):
result_expected = {'sal a gosto': 594, '1 cebola picada': 44}
mocker.patch('src.api.matching.match_view.ingr_zing_match_mult_search',
return_value=[[], [], {'sal a gosto': 594, '1 cebola picada': 44}])
RESOURCE_URL = "/match"
resp = client.post(RESOURCE_URL, json=['sal a gosto', '1 cebola picada'])
assert resp.status_code == 200
assert result_expected in resp.get_data(as_text=True)
uj5u.com熱心網友回復:
我認為您需要將函式本身匯入到測驗檔案中。嘗試:
from src.api.matching.match_view import ingr_zing_match_mult_search
然后修補該功能:
mocker.patch('src.api.matching.match_view.ingr_zing_match_mult_search',
return_value=[[], [], {'sal a gosto': 594, '1 cebola picada': 44}])
請參閱此處了解更多資訊。
uj5u.com熱心網友回復:
經過許多。經過多次嘗試,我終于找到了解決方案(我將在這個答案的末尾給出解決方案)。基本上我設法運行測驗,我匯入了 index() 函式,并在 POST 方法中執行單元測驗。為此,我使用背景關系管理器激活了 test_request_context。所以我設法模擬了 de index() 中的結果(之前所有函式都經過了測驗)。然后測驗運行并覆寫所需的所有行。我真的不知道這是否是執行單元測驗的最佳方式,并且我相信這不是執行此操作的 Pythonic 方式,但可以作業并且很好(經過 4 天的嘗試)。如果有人閱讀了我的測驗并可以向我解釋一個更好的方法,或者我很樂意了解和學習的 Python 方法,所以請對評論和討論我的解決方案感到滿意。
test_00_api.py
from src.api.matching.match_view import index
import pandas as pd
import pytest
import sys, os
def test_match_view_post_retorno_correto(client, mocker):
from flask import Flask
app = Flask(__name__)
resume = pd.DataFrame()
results = pd.DataFrame()
resume['Raw_Ingred'] = ['sal a gosto', '1 cebola picada']
results['Raw_Ingred'] = ['sal a gosto', '1 cebola picada']
payload = {'sal a gosto': 594, '1 cebola picada': 44}
result_expected = {'sal a gosto': 594, '1 cebola picada': 44}
with app.test_request_context("/match",
method="POST",
json=['sal a gosto', '1 cebola picada']):
mocker.patch('src.api.matching.match_view.ingr_zing_match_mult_search',
return_value= [results, resume, payload])
mocker.patch('src.api.matching.match_view.dumpModel', return_value=None)
mocker.patch('src.api.matching.match_view.bulk_update_zingr_id',
return_value=[])
mocker.patch('src.api.matching.match_view.bulk_insert_ingredients_matching_table',
return_value=[])
result = index()
assert result == result_expected
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/515040.html
下一篇:模塊“DynamicTestModule”匯入的意外值“HttpTestingController”。請添加@NgModule注釋
