微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决对进行 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 举报,一经查实,本站将立刻删除。