Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test template context variables with Flask

Tags:

python

flask

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')
like image 635
saltycrane Avatar asked May 21 '12 23:05

saltycrane


1 Answers

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')
like image 91
saltycrane Avatar answered Nov 02 '22 05:11

saltycrane