如何使用Flask test_client设置请求参数? [英] How to set request args with Flask test_client?
问题描述
我必须测试一个从 request.args
获取某些信息的视图.
I have to test out a certain view that gets certain information from request.args
.
我不能嘲笑它,因为视图中的很多东西都使用了request对象.我唯一想到的替代方法是手动设置 request.args
.
I can't mock this since a lot of stuff in the view uses the request object.
The only alternative I can think of is to manually set request.args
.
我可以使用 test_request_context()
来做到这一点,例如:
I can do that with the test_request_context()
, e.g:
with self.app.test_request_context() as req:
req.request.args = {'code': 'mocked access token'}
MyView()
现在,该视图内的请求将具有我设置的参数.但是,我需要调用我的视图,而不仅仅是初始化它,所以我使用以下方法:
Now the request inside this view will have the arguments that I've set. However I need to call my view, not just initialize it, so I use this:
with self.app.test_client() as c:
resp = c.get('/myview')
但是我不知道如何以这种方式操纵请求参数.
But I don't know how to manipulate the request arguments in this manner.
我已经尝试过了:
with self.app.test_client() as c:
with self.app.test_request_context() as req:
req.request.args = {'code': 'mocked access token'}
resp = c.get('/myview')
但这不会设置 request.args
.
推荐答案
将 query_string
参数传递给 c.get
,该参数可以是 dict
, MultiDict
或已编码的字符串.
Pass the query_string
argument to c.get
, which can either be a dict
, a MultiDict
, or an already encoded string.
with app.test_client() as c:
r = c.get('/', query_string={'name': 'davidism'})
测试客户端请求方法将其参数传递给Werkzeug的 EnvironBuilder
,在此进行记录.
The test client request methods pass their arguments to Werkzeug's EnvironBuilder
, which is where this is documented.
这篇关于如何使用Flask test_client设置请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!