Django's test client returns a test Response object which includes the template context variables that were used to render the template. https://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.Response.context
How can I get access to template context variables while testing in Flask?
Example view:
@pgt.route('/myview')
def myview():
context = {
'var1': 'value 1',
'var2': 'value 2',
'var3': 'value 3',
}
return render_template('mytemplate.html', **context)
Example test:
class MyViewTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app()
self.client = self.app.test_client()
def test_get_success(self):
response = self.client.get('/pgt/myview')
# I don't want to do this
self.assertIn('value 1', response.data)
# I want to do something like this
self.assertEqual(response.template_context['var1'], 'value 1')
Thanks to @andrewwatts I used (a version of) Flask-Testing
from flask.ext.testing import TestCase
class MyViewTestCase(TestCase):
def create_app(self):
# This method is required by flask.ext.testing.TestCase. It is called
# before setUp().
return create_app()
def test_get_success(self):
response = self.client.get('/pgt/myview')
self.assertEqual(self.get_context_variable('var1'), 'value 1')
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