ben*_*-hx 9 python testing json flask
我正在构建一个应用程序,我想做一些测试.我需要将响应数据从测试客户端转换为JSON.
该应用程序:
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
app = Flask(__name__, static_url_path="")
@app.route('/myapp/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': [task for task in tasks]})
if __name__ == '__main__':
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
测试:
class MyTestCase(unittest.TestCase):
def setUp(self):
myapp.app.config['TESTING'] = True
self.app = myapp.app.test_client()
def test_empty_url(self):
response = self.app.get('/myapp/api/v1.0/tasks')
resp = json.loads(response.data)
print(resp)
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
当我尝试转换response.data
为JSON时,我收到以下错误:
TypeError: the JSON object must be str, not 'bytes'
Run Code Online (Sandbox Code Playgroud)
如何修复此错误并获取JSON数据?
dav*_*ism 26
您需要将响应数据作为文本获取,但默认值为字节.响应对象提供了get_json
控制它的方法.
data = response.get_json()
Run Code Online (Sandbox Code Playgroud)
Flask 1.0(尚未发布)将该json.loads
方法添加到响应对象,类似于请求对象.
data = json.loads(response.get_data(as_text=True))
Run Code Online (Sandbox Code Playgroud)