Flask REST API测试报错:TypeError: 'list'对象不可调用
解决Flask测试中
TypeError: 'list' object is not callable错误 错误核心原因
你遇到的错误是因为错误地将Flask响应的json属性当作方法调用。在Flask 1.0及以后版本中,response.json是一个属性,会直接返回解析后的JSON数据(此处为列表),不需要加括号()。如果写成response.json(),就相当于试图调用一个列表对象,自然触发'list' object is not callable的错误。
具体修复步骤
- 修正
json属性的调用方式
把代码中错误的写法:
response_data = response.json()[0]
改为:
response_data = response.json[0]
修复测试方法的缩进问题
你的test_get方法没有缩进在Tests类内部,导致unittest框架无法识别这个测试方法,测试不会执行。需要将方法缩进至类的作用域内。移除重复的测试客户端初始化
setUp方法中已经创建了self.app作为测试客户端,测试方法里无需重复创建tester,直接复用self.app即可。
修正后的完整代码
import unittest from app import app import json class Tests(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['DEBUG'] = False self.app = app.test_client() def test_get(self): response = self.app.get('/product', content_type='application/json') response_data = response.json[0] self.assertEqual(response.status_code, 200) self.assertEqual(response_data['category_id'], 1) self.assertEqual(response_data['description'], 'Nice Pants') self.assertEqual(response_data['product_image'], 'Image') if __name__ == "__main__": unittest.main()
额外说明
你提到在其他文件中该语法可行,大概率是因为那个文件使用的是旧版本Flask(0.12及以前),当时response.json()是正确的方法调用。新版本Flask已将其改为属性,因此测试代码需要适配新版本写法。
内容的提问来源于stack exchange,提问作者Jorge
相关产品推荐
相关产品推荐

