本文介绍了测试Flask render_template()上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条烧瓶路线,如下所示:

I have a Flask route that looks like this:

@app.route('/')
def home():
    return render_template(
        'home.html',
        greeting:"hello"
    )

如何测试是否渲染了'home.html'模板,并且render_template()上下文定义了具有特定值的greeting变量?

How do I test that the 'home.html' template was rendered, and that the render_template() context defined the greeting variable with a particular value?

这些应该(很可能)很容易测试,但是我真的不确定如何使用Flask和unittest进行测试.

These should be (and probably are) pretty easy to test, but I'm really not sure how to do this with Flask and unittest.

推荐答案

您可以使用TestCase的assert_template_used方法. rel ="noreferrer">烧瓶测试.

You can use the assert_template_used method of TestCase provided by flask-testing.

from flask.ext.testing import TestCase

class MyTest(TestCase):

    def create_app(self):
        return myflaskapp

    def test_greeting(self):
        self.app.get('/')
        self.assert_template_used('hello.html')
        self.assert_context("greeting", "hello")

方法create_app必须提供烧瓶应用程序.

The method create_app must provide your flask app.

这篇关于测试Flask render_template()上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:36