对进行 API 调用的函数的返回值进行 Pytest

问题描述

我有一个调用 API 的函数,我想将该 API 调用的返回值 (response) 设为 {"message":"nopong"},以便 ValueError提高。到目前为止,我已经

# root_folder/subfolder/includes/abc/functions.py

from abc import ABC   # 3rd party library

def _check_connection(conn_id):
    api_key = get_api_key(conn_id)  
    api_client = ABC(api_key=api_key)
    
    response = api_client.test_connection()
    print(response)
    
    if response['message'] != "pong":   
        raise ValueError("Failed connection to ABC")

---------------

# root_folder/tests/test_functions.py

import pytest
import sys
sys.path.insert(0,'../subfolder/')
from includes.abc.functions import _check_connection

def test_check_connection_raiseerror(mocker):
    with pytest.raises(ValueError) as execinfo:  
        mocker.patch('includes.abc.functions.ABC.test_connection',return_value='{"message":"nopong"}')
        _check_connection("conn_A")
    assert str(execinfo.value) == 'Failed connection to ABC'

我得到的 pytest 结果是

================================================== FAILURES ==================================================
______________________________________ test_check_connection_raiseerror ______________________________________

mocker = <pytest_mock.plugin.MockerFixture object at 0x7f85f30c7220>

    def test_check_connection_raiseerror(mocker):
        with pytest.raises(ValueError) as execinfo:
            mocker.patch('includes.abc.functions.ABC.test_connection',return_value='{"message":"nopong"}')
            
>           _check_connection("conn_A")

test_functions.py:73: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

conn_id = 'conn_A'

    def _check_connection(conn_id):
        api_key = get_api_key(conn_id)
        api_client = ABC(api_key=api_key)
    
        response = api_client.test_connection()
        print(response)
    
>       if response['message'] != "pong":
E    TypeError: string indices must be integers

../subfolder/includes/abc/functions.py:70: TypeError
-------------------------------------------- Captured stdout call --------------------------------------------
{"message":"nopong"}
========================================== short test summary info ===========================================
Failed test_functions.py::test_check_connection_raiseerror - TypeError: string indices must be integers

为什么 pytest 抱怨我的 _check_connection 函数?它使用键 message 正确访问字典,并且在 pytest 之外工作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)