Checking flash messages in flask application nose tests Checking flash messages in flask application nose tests flask flask

Checking flash messages in flask application nose tests


The method of testing flashes with session['_flashes'] didn't work for me, because session object simply doesn't have '_flashes' attribute in my case:

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

KeyError: '_flashes'

It might be because most recent version of flask and other packages I use with Python 3.6.4 may work differently, I honestly don't know...

What worked for me is a simple and straightforward:

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

In my case the flash message was 'Invalid user name or password'.

I think it's also easier to read. Hope it helps those who encountered a similar issue


Here's a sample test that asserts an expected flash message is present. It is based on the method 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)

Note: session['_flashes'] will be a list of tuples. Something like this:

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