0

我有一个进行 API 调用的函数,我想response将该 API 调用的返回值 () 设为{"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功能?它使用 key 正确访问字典message,并且在 pytest 之外工作。

4

1 回答 1

1

你需要返回一个字典而不是一个字符串,所以mocker.patch('includes.abc.functions.ABC.test_connection', return_value='{"message":"NoPong"}')应该变成:mocker.patch('includes.abc.functions.ABC.test_connection', return_value={"message":"NoPong"})

没有引号。

于 2021-09-09T10:12:16.703 回答