11

Django 的测试客户端返回一个测试响应对象,其中包括用于呈现模板的模板上下文变量。https://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.Response.context

在 Flask 中测试时如何访问模板上下文变量?

示例视图:

@pgt.route('/myview')
def myview():
    context = {
        'var1': 'value 1',
        'var2': 'value 2',
        'var3': 'value 3',
    }
    return render_template('mytemplate.html', **context)

示例测试:

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

2 回答 2

24

感谢@andrewwatts,我使用了(一个版本的)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')
于 2012-05-22T02:18:22.287 回答
-1

根据这些有限的信息,我建议将生成上下文的代码分解为一个单独的单元并直接对其进行测试。映射上面的示例:

def get_context():
    context = {
        'var1': 'value 1',
        'var2': 'value 2',
        'var3': 'value 3',
    }
    return context

@pgt.route('/myview')
def myview():
    return render_template('mytemplate.html', **get_context())
于 2012-05-21T23:20:01.180 回答