问题描述
我正在尝试测试返回字典的函数。我收到错误 AttributeError:'dict'对象没有属性'content_type'。如何测试响应是否为字典?
def response_get(url):
try:
response = requests.get(url)
except requests.exceptions.RequestException as e:
raise SystemExit(e)
data = response.json()
return data
def test_response_get(self):
response = response_get('https://ghibliapi.herokuapp.com/films/58611129-2dbc-4a81-a72f-77ddfc1b1b49')
self.assertEqual(response.content_type,'application/dict')
解决方法
您已经在返回字典,并且字典上没有content_type
。
相反,您可以使用isinstance
和assertTrue
。
import requests
import unittest
def response_get(url):
try:
response = requests.get(url)
except requests.exceptions.RequestException as e:
raise SystemExit(e)
data = response.json()
return data
class SimpleTest(unittest.TestCase):
def test_response_get(self):
response = response_get('https://ghibliapi.herokuapp.com/films/58611129-2dbc-4a81-a72f-77ddfc1b1b49')
self.assertTrue(isinstance(response,dict))
if __name__ == '__main__':
unittest.main()
输出:
.
----------------------------------------------------------------------
Ran 1 test in 0.966s
OK