Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send requests with JSON in unit tests

I have code within a Flask application that uses JSONs in the request, and I can get the JSON object like so:

Request = request.get_json() 

This has been working fine, however I am trying to create unit tests using Python's unittest module and I'm having difficulty finding a way to send a JSON with the request.

response=self.app.post('/test_function',                         data=json.dumps(dict(foo = 'bar'))) 

This gives me:

>>> request.get_data() '{"foo": "bar"}' >>> request.get_json() None 

Flask seems to have a JSON argument where you can set json=dict(foo='bar') within the post request, but I don't know how to do that with the unittest module.

like image 518
Sepehr Nazari Avatar asked Mar 03 '15 16:03

Sepehr Nazari


People also ask

How do I use JSON requests?

To post a JSON to the server using Python Requests Library, call the requests. post() method and pass the target URL as the first parameter and the JSON data with the json= parameter. The json= parameter takes a dictionary and automatically converts it to a JSON string.

How do I request a response in JSON?

To request JSON from a URL, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our client is expecting JSON.

What is the type of requests JSON ()?

json() The json() method of the Request interface reads the request body and returns it as a promise that resolves with the result of parsing the body text as JSON .


1 Answers

Changing the post to

response=self.app.post('/test_function',                         data=json.dumps(dict(foo='bar')),                        content_type='application/json') 

fixed it.

Thanks to user3012759.

like image 143
Sepehr Nazari Avatar answered Oct 18 '22 18:10

Sepehr Nazari