将测试客户端数据转换为JSON [英] Convert test client data to JSON

查看:198
本文介绍了将测试客户端数据转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个应用程序,我想做一些测试。我需要将来自测试客户端的响应数据转换为JSON。



应用程序:

  tasks = [
{
'id':1,
'title':u'Buy groceries',
'description':u'Milk,奶酪,比萨,水果,Tylenol',
'完成':False
},
{
'id':2,
'title':u'Learn Python',
'description':u'需要在网上找到一个好的Python教程',
'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 task]})

if __name__ =='__main__':
app.run (debug = True)

测试:

  class MyTestCase(unittest.TestCase):
def setUp(self):
myapp.app.confi g ['TESTING'] = True
self.app = myapp.app.test_client()
$ b $ 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()

当我尝试转换响应.data 到JSON,我得到以下错误:

  TypeError:JSON对象必须是str ,而不是'字节'

如何解决这个错误并获取JSON数据?

解决方案

您需要获取响应数据作为文本,但默认是字节。响应对象提供了 get_data 来控制这个。

  data = json.loads(response.get_data(as_text = True))


I'm building an app and I want to make some tests. I need to convert the response data from the test client to JSON.

The app:

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)

The tests:

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()

When I try to convert response.data to JSON, I get the following error:

TypeError: the JSON object must be str, not 'bytes'

How can I fix this error and get the JSON data?

解决方案

You need to get the response data as text, but the default is bytes. The response object provides the method get_data to control this.

data = json.loads(response.get_data(as_text=True))

这篇关于将测试客户端数据转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆