【发布时间】:2011-11-17 16:37:20
【问题描述】:
我想伪造请求参数以进行单元测试。如何在 Flask 中实现这一点?
【问题讨论】:
标签: python unit-testing flask
我想伪造请求参数以进行单元测试。如何在 Flask 中实现这一点?
【问题讨论】:
标签: python unit-testing flask
如果您更喜欢使用test_request_context:
import unittest
from myapp import extract_query_params
testapp = flask.Flask(__name__)
class TestFoo(unittest.TestCase):
def test_happy(self):
with testapp.test_request_context('?limit=1&offset=2'):
limit, offset = extract_query_params(['limit', 'offset'])
self.assertEquals(limit, 1)
self.assertEquals(offset, 2)
【讨论】:
with testapp.test_request_context(headers=h): 可用于传递 headers 而无需提及任何 url,这将使用 default-url 模拟请求我>
我需要一个简单的单元测试请求,这是一个简单的解决方案:
from flask import Request
r = Request({})
【讨论】:
您可以使用以下内容:
self.app.post('/path-to-request', data=dict(var1='data1', var2='data2', ...))
self.app.get('/path-to-request', query_string=dict(arg1='data1', arg2='data2', ...))
Flask 的当前开发版本还包括对testing JSON APIs 的支持:
from flask import request, jsonify
@app.route('/jsonapi')
def auth():
json_data = request.get_json()
attribute = json_data['attr']
return jsonify(resp=generate_response(attribute))
with app.test_client() as c:
rv = c.post('/jsonapi', json={
'attr': 'value', 'other': 'data'
})
json_data = rv.get_json()
assert generate_response(email, json_data['resp'])
【讨论】:
?param1=value&param2=value2 -- 或者它也可以接收字典?
这是一个完整的单元测试代码示例
testapp = app.test_client()
class Test_test(unittest.TestCase):
def test_user_registration_bad_password_short(self):
response = self.register(name='pat',
email='me@mail.com',
password='Flask',
password2='Flask')
self.assertEqual(response.status_code, 200)
self.assertIn(b'password should be 8 or more characters long',
response.data)
def register(self, name, email, password, password2):
return testapp.post(
'/register',
data=dict(username=name,
email=email,
password=password,
password2=password2),
follow_redirects=True
)
【讨论】:
在测试用于登录的帖子表单数据时,我仍然遇到此问题。
def login(self, username, password):
return self.app.post('/', data='Client_id=' + username +'&Password=' + password,
follow_redirects=True,content_type='application/x-www-form-urlencoded')
我发现这是这样的。
铬: 开发者模式 --> 文档 --> 请求的 HTML 文档 --> 标题选项卡 --> 表单数据 --> 查看源代码
【讨论】:
urllib.urlencode(form_data_dict) 或 urllib.parse.encode 对于从字典中创建 data 很有用。
发布:
self.app.post('/endpoint', data=params)
获取:
self.app.get('/endpoint', query_string=params)
【讨论】: