[英]Best way to handle flask POST unit test
I have the following code, that accepts a POST request and processes it. 我有以下代码,该代码接受POST请求并对其进行处理。
index.py 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. 基本上,我想访问request.get_data()以便更改值。 I'm invoking the test as shown below, which is dead simple.
我正在调用如下所示的测试,这很简单。
route_test.py: 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(). 但是不允许我设置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. 如果
data
是字符串或字节,Werkzeug将数据直接作为字节发送。
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. 您可以使用模拟对象来修补请求对象的get_data方法,该模拟对象将返回您告诉其返回的内容。 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.