Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking flash messages in flask application nose tests

On different input values posted to a url of my flask application, it flashes different messages, e.g. 'no data entered', 'invalid input', 'no record found', '3 records found'.

Can someone guide how can I write a nose test to check if the proper flash message is displayed? I guess the flash messages first goto the session ... how can we check session variables in nose-tests?

Thanks

like image 498
user2436428 Avatar asked Apr 08 '15 07:04

user2436428


People also ask

How do I show flash messages in flask?

The flash() method is used to generate informative messages in the flask. It creates a message in one view and renders it to a template view function called next. In other words, the flash() method of the flask module passes the message to the next request which is an HTML template.

How do you test a flask application?

If an application has automated tests, you can safely make changes and instantly know if anything breaks. Flask provides a way to test your application by exposing the Werkzeug test Client and handling the context locals for you.

Which of the following functions can be used to display a temporary message in the response in flask?

If the two names are different, the flash() function is invoked with a message to be displayed on the next response sent back to the client.


1 Answers

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': '[email protected]',
        '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

like image 198
Leo Skhrnkv Avatar answered Sep 30 '22 07:09

Leo Skhrnkv