在单元测试中模拟response.text

时间:2019-03-30 19:29:41

标签: python unit-testing

我正在尝试使用以下代码从API获得响应。我得到结果并将其打印为response.text。同样,我尝试编写单元测试。我可以使用JSON内容模拟API响应。但是运行单元测试时出现如下错误。

AttributeError: 'dict' object has no attribute 'text'

代码:

import requests
from requests.auth import HTTPBasicAuth
import json

def get_call():
   url = 'https://test/api/v1'
   username = 'NTdasj'
   pwd = '3214234'

   response = requests.get(url, auth=HTTPBasicAuth(username, pwd))
   data = json.loads(response.text)
   print(data)

试过的单元测试代码:

from get_api import get_call
from mock import patch
import os
import sys
import json
testdir = os.path.dirname(__file__)
sys.path.insert(0, os.path.abspath(os.path.join(testdir)))


resp = {
  "success": True,
  "message": "Data exist",
  "data": []
 }
response = json.dumps(resp)
newresponse = json.loads(response)

@patch('get_api.requests.get')
def test_get_call(get):
   get.side_effect = [newresponse]
   get_call()

1 个答案:

答案 0 :(得分:0)

您正在嘲笑requests.get来生成dict,而不是text属性是dict的JSON编码的对象。

get.return_value.text = response
相关问题