如何在 Flask 中伪造 request.POST 和 GET 参数进行单元测试?

发布于 2024-12-04 11:03:08 字数 44 浏览 1 评论 0原文

我想伪造请求参数以进行单元测试。我怎样才能在 Flask 中实现这一目标?

I would like to fake request parameters for unit testing. How can I achieve this in Flask?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

单挑你×的.吻 2024-12-11 11:03:09

如果您更喜欢使用 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)

If you prefer to use 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)
银河中√捞星星 2024-12-11 11:03:09

我需要一个简单的单元测试请求,这是一个简单的解决方案:

from flask import Request
r = Request({})

I needed an simple request for unit testing, and this was an easy solution:

from flask import Request
r = Request({})
冰魂雪魄 2024-12-11 11:03:09

在测试用于登录的帖子表单数据时,我仍然遇到了这个问题,这对我有用。

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 文档 -->标题选项卡 -->表单数据-->查看源代码

I still had issue with this when testing post form data for logging in this worked for me.

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')

I found this is out this way.

Chrome:
Developer mode --> Doc --> HTML doc that was requested --> Headers Tab --> Form data --> view source

情泪▽动烟 2024-12-11 11:03:09

这是单元测试的完整代码示例

testapp = app.test_client()

class Test_test(unittest.TestCase):
    def test_user_registration_bad_password_short(self):
        response = self.register(name='pat',
                                 email='[email protected]', 
                                 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
        )

here is a complete code example of a unit test

testapp = app.test_client()

class Test_test(unittest.TestCase):
    def test_user_registration_bad_password_short(self):
        response = self.register(name='pat',
                                 email='[email protected]', 
                                 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
        )
哭了丶谁疼 2024-12-11 11:03:08

您是否阅读过有关测试的 Flask 文档

您可以使用以下内容:

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 的当前开发版本还支持测试 JSON API< /a>:

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'])

Did you read Flask docs about testing?

You can use following:

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', ...))

Current development version of Flask also includes support for 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'])
愁杀 2024-12-11 11:03:08

发布:

self.app.post('/endpoint', data=params)

获取:

self.app.get('/endpoint', query_string=params)

POST:

self.app.post('/endpoint', data=params)

GET:

self.app.get('/endpoint', query_string=params)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文