在烧瓶应用程序鼻子测试中检查闪存消息

use*_*428 5 python nose nosetests flask flash-message

在发布到我的 Flask 应用程序 url 的不同输入值上,它会闪烁不同的消息,例如“未输入数据”、“无效输入”、“未找到记录”、“找到 3 条记录”。

有人可以指导我如何编写鼻子测试以检查是否显示了正确的闪光信息?我猜闪存消息首先进入会话......我们如何在鼻子测试中检查会话变量?

谢谢

Leo*_*nkv 5

使用 session['_flashes'] 测试 flashes 的方法对我不起作用,因为 session 对象在我的情况下根本没有 '_flashes' 属性:

with client.session_transaction() as session:
    flash_message = dict(session['_flashes']).get('warning')
Run Code Online (Sandbox Code Playgroud)

KeyError: '_flashes'

这可能是因为我在 Python 3.6.4 中使用的最新版本的 Flask 和其他软件包的工作方式可能有所不同,老实说,我不知道......

对我有用的是一个简单明了的:

def test_flash(self):
    # attempt login with wrong credentials
    response = self.client.post('/authenticate/', data={
        'email': 'bla@gmail.com',
        'password': '1234'
    }, follow_redirects=True)
    self.assertTrue(re.search('Invalid username or password',
                    response.get_data(as_text=True)))
Run Code Online (Sandbox Code Playgroud)

在我的情况下,Flash 消息是“无效的用户名或密码”。

我认为它也更容易阅读。希望对遇到类似问题的朋友有所帮助


kle*_*ell 4

下面是一个示例测试,断言存在预期的闪现消息。它基于此处描述的方法:

def test_should_flash_warning_message_when_no_record_found(self):
    # Arrange
    client = app.test_client()

    # Assume
    url = '/records/'
    expected_flash_message = 'no record found'

    # Act
    response = client.get(url)
    with client.session_transaction() as session:
        flash_message = dict(session['_flashes']).get('warning')

    # Assert
    self.assertEqual(response.status_code, 200, response.data)
    self.assertIsNotNone(flash_message, session['_flashes'])
    self.assertEqual(flash_message, expected_flash_message)
Run Code Online (Sandbox Code Playgroud)

注意:session['_flashes']将是元组列表。像这样的东西:

[(u'warning', u'no records'), (u'foo', u'Another flash message.')]
Run Code Online (Sandbox Code Playgroud)