Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set request args with Flask test_client?

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 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.

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.

like image 888
Saša Kalaba Avatar asked Aug 03 '16 15:08

Saša Kalaba


People also ask

What is request args in Flask?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method: get(key, default=None, type=None) Return the default value if the requested data doesn't exist.

What is Test_client in Flask?

The test client makes requests to the application without running a live server. Flask's client extends Werkzeug's client, see those docs for additional information. The client has methods that match the common HTTP request methods, such as client.

How do you write a unit test case in python Flask?

First create a file named test_app.py and make sure there isn't an __init__.py in your directory. Open your terminal and cd to your directory then run python3 app.py . If you are using windows then run python app.py instead. Hope this will help you solve your problem.

How can a request context be created in Flask Python?

Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.


1 Answers

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.

like image 154
davidism Avatar answered Oct 05 '22 13:10

davidism