【问题标题】:Hot to unit test when content_type is dictionary当 content_type 是字典时,单元测试很热门
【发布时间】:2020-08-16 19:31:11
【问题描述】:

我正在尝试测试返回字典的函数。我收到错误 AttributeError: 'dict' object has no attribute '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')

【问题讨论】:

    标签: python unit-testing python-unittest


    【解决方案1】:

    你已经返回了一个字典并且字典上没有content_type。 相反,您可以使用isinstanceassertTrue

    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
    

    【讨论】:

    • 谢谢你,这就是我要找的东西!
    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多