Django的测试客户端返回一个测试Response对象,该对象包含用于呈现模板的模板上下文变量。 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')
答案 0 :(得分:22)
感谢@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')
答案 1 :(得分:-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())