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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With