Python 试验瓶与单元试验

Python 试验瓶与单元试验,python,flask,oauth,python-unittest,Python,Flask,Oauth,Python Unittest,我编写了一个flask应用程序,它使用flask dance进行用户身份验证。现在我想测试几个视图,我已经启用了@login\u required 我想跟随烧瓶舞蹈测试,但我无法让它工作。因为我只使用unittest,而不是pytest。我也使用github,而不是像文档中那样使用google。那么sess['github\u oauth\u token']正确吗?原型样本测试可能如下所示: def test_sample(self): with self.client as clien

我编写了一个flask应用程序,它使用flask dance进行用户身份验证。现在我想测试几个视图,我已经启用了
@login\u required

我想跟随烧瓶舞蹈测试,但我无法让它工作。因为我只使用unittest,而不是pytest。我也使用github,而不是像文档中那样使用google。那么sess['github\u oauth\u 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
而不是('core.get\u sample')的
url\u

然后尝试通过遵循正式登录来简单地禁用它

当设备运行时,可以方便地全局关闭身份验证 测试。要启用此功能,如果应用程序配置变量 LOGIN\u DISABLED设置为True,将忽略此装饰程序

但这也不起作用,测试仍然会失败,因为需要登录时不知何故执行了

因此,我的问题是:

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

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

即使您使用的是
unittest
框架而不是
pytest
,您仍然可以使用中记录的模拟存储类。您只需要使用一些其他机制来用mock替换真实存储,而不是Pytest中的
monkeypatch
fixture。您可以轻松地使用该软件包,如下所示:

导入单元测试
从unittest.mock导入修补程序
从flask_.consumer.storage导入内存存储
从我的应用导入创建应用
类TestApp(unittest.TestCase):
def设置(自):
self.app=create_app()
self.client=self.app.test_client()
def测试样本(自身):
github_bp=self.app.blueprints[“github”]
storage=MemoryStorage({“access\u token”:“fake token”})
使用patch.object(github_bp,“存储”,存储):
使用self.client作为客户端:
response=client.post(url\u代表('core.get\u sample'),data=self.fake\u sample)
self.assertRedirects(响应,url_for('core.get_sample'))
本例使用,但如果您愿意,也可以从其他地方导入
应用程序
对象并以这种方式使用