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

时间:2016-10-02 22:13:38

标签: python flask

在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"

我该怎么做?

2 个答案:

答案 0 :(得分:5)

可以使用signals完成此操作。我将在这里重现代码snippit:

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)

答案 1 :(得分:0)

最好的方法是使用类似的东西:

self.assertTrue('Hello bar!' in r.body)

foo.html

<div>Hello {{ foo }}!</div>

当然我不知道你的html的结构,所以上面这个例子只是一个原型。