在烧瓶应用鼻子测试中检查闪光信息

时间:2015-04-08 07:34:06

标签: python flask nose nosetests flash-message

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

有人可以指导我如何编写鼻子测试以检查是否显示正确的闪光信息?我想flash消息首先转到会话......我们如何在nose-tests中检查会话变量?

由于

2 个答案:

答案 0 :(得分:4)

这是一个示例测试,断言存在预期的Flash消息。它基于方法described here

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)

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

[(u'warning', u'no records'), (u'foo', u'Another flash message.')]

答案 1 :(得分:1)

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

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

KeyError: '_flashes

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

对我有用的是简单明了的事情:

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

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

我认为这也更容易阅读。希望它可以帮助那些遇到类似问题的人

相关问题