与Unites共舞的测试瓶

2024-03-28 21:15:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个flask应用程序,它使用flask dance进行用户身份验证。现在我想测试一些我已经启用了@login_required的视图。你知道吗

我想跟随烧瓶舞测试docs,但我无法让它工作。因为我只使用unittest而不是pytest。我也使用github,而不是像文档中那样使用google。那么sess['github_oauth_token']正确吗?原型样品测试可以如下所示:

def test_sample(self):
    with self.client as client:
        with client.session_transaction() as sess:
            sess['github_oauth_token'] = {
                'access_token': 'fake access token',
                'id_token': 'fake id token',
                'token_type': 'Bearer',
                'expires_in': '3600',
                'expires_at': self.time + 3600
            }

        response = client.post(url_for('core.get_sample'), data=self.fake_sample)

        self.assertRedirects(response, url_for('core.get_sample'))

assertRedirect失败,因为我被重定向到登录页http://localhost/login/github?next=%2Fsample%2F,而不是url_for('core.get_sample')。你知道吗

然后尝试通过遵循正式的flask登录名docs来简单地禁用它。你知道吗

It can be convenient to globally turn off authentication when unit testing. To enable this, if the application configuration variable LOGIN_DISABLED is set to True, this decorator will be ignored.

但这并不能很好地工作,测试仍然失败,因为以某种方式执行了login\u required。

所以我的问题是:

  • 因为我使用的是github而不是google,所以文档中的github_oauth_token是会话的正确键吗?你知道吗
  • 在使用Flask Dance时,如何使用unittest测试具有@login_requireddecorator的视图?你知道吗

编辑:LOGIN_DISABLED=True只要我在我的配置类中为app.config.from_object(config['testing'])定义它就可以工作,不起作用的是在我的设置方法中设置self.app.config['LOGIN_DISABLED'] = True。你知道吗


Tags: samplecoreselfgithubclienttokenurlflask
1条回答
网友
1楼 · 发布于 2024-03-28 21:15:48

即使您使用unittest框架而不是pytest进行测试,您仍然可以使用the Flask-Dance testing documentation中记录的模拟存储类。您只需要使用其他一些机制来用mock替换实际存储,而不是Pytest中的monkeypatchfixture。您可以轻松地使用^{}包,如下所示:

import unittest
from unittest.mock import patch
from flask_dance.consumer.storage import MemoryStorage
from my_app import create_app

class TestApp(unittest.TestCase):
    def setUp(self):
        self.app = create_app()
        self.client = self.app.test_client()

    def test_sample(self):
        github_bp = self.app.blueprints["github"]
        storage = MemoryStorage({"access_token": "fake-token"})
        with patch.object(github_bp, "storage", storage):
            with self.client as client:
                response = client.post(url_for('core.get_sample'), data=self.fake_sample)

        self.assertRedirects(response, url_for('core.get_sample'))

本例使用application factory pattern,但是如果需要,也可以从其他地方导入app对象并以这种方式使用它。你知道吗

相关问题 更多 >