gpt4 book ai didi

python - Flask 测试 - 如何检索传递给 Jinja 的变量?

转载 作者:太空狗 更新时间:2023-10-30 02:41:18 27 4
gpt4 key购买 nike

在 Flask 中,如何使用 render_template 测试返回到 Jinja 模板的变量?

@app.route('/foo/'):
def foo():
return render_template('foo.html', foo='bar')

在这个例子中,我想测试 foo 是否等于 "bar"

import unittest
from app import app

class TestFoo(unittest.TestCase):
def test_foo(self):
with app.test_client() as c:
r = c.get('/foo/')
# Prove that the foo variable is equal to "bar"

我该怎么做?

最佳答案

这可以使用 signals 来完成.我将在此处重现代码片段:

import unittest
from app import app
from flask import template_rendered
from contextlib import contextmanager

@contextmanager
def captured_templates(app):
recorded = []
def record(sender, template, context, **extra):
recorded.append((template, context))
template_rendered.connect(record, app)
try:
yield recorded
finally:
template_rendered.disconnect(record, app)

class TestFoo(unittest.TestCase):
def test_foo(self):
with app.test_client() as c:
with captured_templates(app) as templates:
r = c.get('/foo/')
template, context = templates[0]
self.assertEquals(context['foo'], 'bar')

这是另一种实现,它删除了 template 部分并将其转换为迭代器。

import unittest
from app import app
from flask import template_rendered
from contextlib import contextmanager

@contextmanager
def get_context_variables(app):
recorded = []
def record(sender, template, context, **extra):
recorded.append(context)
template_rendered.connect(record, app)
try:
yield iter(recorded)
finally:
template_rendered.disconnect(record, app)

class TestFoo(unittest.TestCase):
def test_foo(self):
with app.test_client() as c:
with get_context_variables(app) as contexts:
r = c.get('/foo/')
context = next(context)
self.assertEquals(context['foo'], 'bar')

r = c.get('/foo/?foo=bar')
context = next(context)
self.assertEquals(context['foo'], 'foo')

# This will raise a StopIteration exception because I haven't rendered
# and new templates
next(context)

关于python - Flask 测试 - 如何检索传递给 Jinja 的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822265/

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