I have the following code, that accepts a POST request and processes it.
index.py
@app.route('/route', methods=['POST'])
def route_post():
try:
data = request.get_data()
j = json.loads(data)
except Exception as e:
...
Basically, I want access to request.get_data() so I can change the value. I'm invoking the test as shown below, which is dead simple.
route_test.py:
def test_route():
assert(("Bad Request\r\n", 400) == route_post())
But doesn't allow me to set the value of request.get_data(). How can I do this?
Use the test client to post whatever data you need to the route. If data
is a string or bytes, Werkzeug sends the data directly, as bytes.
from flask import Flask, request
app = Flask(__name__, static_folder=None)
@app.route('/', methods=['POST'])
def index():
return request.get_data()
c = app.test_client()
r = c.post('/', data='Hello, World!')
print(r.data) # b'Hello, World!'
You can patch method get_data of the request object with a mock object that returns what you tell it to return. Something along the lines of:
from mock import patch
@patch('flask.Request.get_data')
def test_route_post(self, get_deta_mock):
get_deta_mock.return_value = '{"foo": "bar"}'
result = route_post()
assert result['foo'] == 'bar'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.