How to set request args with Flask test_client?


Question

I have to test out a certain view that gets certain information from 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.

I can do that with he 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.

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.

1
11
8/3/2016 3:26:19 PM

Accepted Answer

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

The test client request methods pass their arguments to Werkzeug's EnvironBuilder, which is where this is documented.

17
8/8/2019 3:15:41 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon