【问题标题】:Test Flask Dance with unittest用 unittest 测试 Flask Dance
【发布时间】:2019-07-16 19:02:17
【问题描述】:

我编写了一个烧瓶应用程序,它使用烧瓶舞进行用户身份验证。现在我想测试一些已启用@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')

然后尝试简单地禁用它,按照官方烧瓶登录docs

可以方便的在unit的时候全局关闭认证 测试。要启用此功能,如果应用程序配置变量 LOGIN_DISABLED 设置为 True,此装饰器将被忽略。

但这也不起作用,测试仍然失败,因为 login_required 以某种方式执行。

所以我的问题是:

  • 因为我使用的是 github 而不是 google,因为文档中的 github_oauth_token 是会话的正确密钥吗?
  • 在使用 Flask Dance 时,如何使用 unittest 测试具有 @login_required 装饰器的视图?

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

【问题讨论】:

    标签: python flask oauth python-unittest


    【解决方案1】:

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

    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 对象并以这种方式使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-06
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多