gpt4 book ai didi

python - 如何使用 Flask 测试模板上下文变量

转载 作者:太空狗 更新时间:2023-10-29 18:18:49 24 4
gpt4 key购买 nike

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

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

示例 View :

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

最佳答案

感谢@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')

关于python - 如何使用 Flask 测试模板上下文变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10693808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com