簡體   English   中英

如何使用 pytest 模擬異步 function

[英]How I can mock an async function with pytest

我需要測試一個帶有異步 function 的 function,但我不知道如何模擬異步 function。

匹配_ingr_zingr.py

def first_table(ingredient_raw, ingredient_extracted, ingredient_processed):
    ingredient_body, table_rows_I = [], []
    for idx, ing_extr in enumerate(ingredient_extracted):

        ingr_extr = " ".join(list(set(ing_extr.split())))

        ext_ing_st = stemization(ingredient_extracted[idx])

        try:
            # # ======== MULTI-SEARCH
            ingredient_body = format_for_batch_search(ingr_extr, ingredient_raw[idx], ext_ing_st)
            res = asyncio.run(batch_search_v2(ingredient_body))
            
        except BaseException:
            res = 'Não retornou nada do Banco de Dados'
            continue

        result_search_clean, score, zingr_id = eliminate_duplicates_search(res) 

        for l in range(len(result_search_clean)):

            proc_zing = text_normalization(result_search_clean[l])

            table_rows_I.append({'Raw_Ingred': ingredient_raw[idx],
                                 'Zapl_Ingre': result_search_clean[l],
                                 'Proc_Ingre': ingredient_processed[idx],
                                 'Extr_Ingre': ingredient_extracted[idx],
                                 'Score_Elas': score[l],
                                 'Ext_Ing_St': ext_ing_st,
                                 'Proc_Zingr': proc_zing,
                                 'Stem_Zingr': stemization(proc_zing),
                                 'Zingred_id': zingr_id[l]})
    return table_rows_I

上面代碼中要模擬的行是 asyncio.run(batch_search_v2(ingredient_body)) 。 為了測試 function first_table() 我寫了下面的測試:

test_matching_ingr_zingr.py

@pytest.mark.asyncio
def test_first_table_entrada_correta(mocker):
    ingredient_raw = ['Colher de açaí 2colher(es) de sopa']
    ingredient_extracted = ('acai',)
    ingredient_processed = ('colher acai  colheres sopa',)
    result_expected = table_rows_result

    # mock mocking uma função assincrona (asynchronous function)

    mocker.patch('src.services.matching_ingr_zingr.batch_search_v2', return_value=async_res)

    # mocker.patch('src.services.matching_ingr_zingr.batch_search_v2', return_value=async_res)
    result = first_table(ingredient_raw, ingredient_extracted, ingredient_processed)

    

    assert result == result_expected

變量 table_rows_result 從另一個文件導入以進行測試。 誰能幫我學習如何模擬這個異步 function,我想測試 first_table() 但我不想通過 batch_search_v2() 異步 function 訪問數據庫。

async_res 的結構是一個長度為 3 的元組列表:

async_res = [('polpa de açaí', 9.626554, 2779),
             ('açaí', 8.914546, 1764),
             ('sopa de cebola', 8.442016, 388405)]

如所述

@pytest.mark.asyncio
def test_first_table_entrada_correta(mocker):
    async_res = [('polpa de açaí', 9.626554, 2779),
        ('açaí', 8.914546, 1764),
        ('sopa de cebola', 8.442016, 388405)]
    with mock.patch(asyncio.run) as mock_async:
        mock_async.configure_mock(return_value=async_res)
        ingredient_raw = ['Colher de açaí 2colher(es) de sopa']
        ingredient_extracted = ('acai',)
        ingredient_processed = ('colher acai  colheres sopa',)
        result_expected = table_rows_result

        result = first_table(ingredient_raw, ingredient_extracted, ingredient_processed)

        

        assert result == result_expected

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM