简体   繁体   English

如何使用 Flask test_client 设置请求参数?

[英]How to set request args with Flask test_client?

I have to test out a certain view that gets certain information from request.args .我必须测试从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 .我能想到的唯一替代方法是手动设置request.args

I can do that with the test_request_context() , eg:我可以用test_request_context()做到这一点,例如:

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.但我不知道如何以这种方式操作请求参数。

I have tried this:我试过这个:

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

but this does not set request.args .但这不会设置request.args

Pass the query_string argument to c.get , which can either be a dict , a MultiDict , or an already encoded string.通过query_string参数c.get ,它可以是一个dict ,一个MultiDict ,或已编码的字符串。

with app.test_client() as c:
    r = c.get('/', query_string={'name': 'davidism'})

The test client request methods pass their arguments to Werkzeug's EnvironBuilder , which is where this is documented. 测试客户端请求方法将它们的参数传递给 Werkzeug 的EnvironBuilder ,这是记录的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM