测试Flask render_template()上下文

Sha*_*uli 25 python flask

新手烧瓶问题.

我有一个看起来像这样的Flask路线:

@app.route('/')                                                                 
def home():                                                                                                                  
    return render_template(                                                     
        'home.html',                                                            
        greeting:"hello"                                       
    )                                                                           
Run Code Online (Sandbox Code Playgroud)

如何测试'home.html'模板是否已呈现,以及render_template()上下文是否greeting使用特定值定义了变量?

这些应该(并且可能是)很容易测试,但我真的不确定如何使用Flask和unittest来做到这一点.

Jar*_*rus 15

您可以使用烧瓶测试提供的assert_template_used方法.TestCase

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")
Run Code Online (Sandbox Code Playgroud)

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

  • 作品!只需要这样导入:“fromflask_testingimportTestCase” (2认同)
  • [flask-testing 未维护](https://github.com/jarus/flask-testing/issues/134) (2认同)

ste*_*uss 5

我的建议是查看Flask 文档进行测试

使用文档作为指南,您应该能够设置一个可以检查响应内容的测试用例。

import unittest
import yourappname

class MyAppTestCase(unittest.TestCase):
    def setUp(self):
        self.app = yourappname.app.test_client()

    def test_greeting(self):
        rv = self.app.get('/')
        self.assertIn('hello', rv.data)
Run Code Online (Sandbox Code Playgroud)

yourappname您的应用程序/项目的名称在哪里。

  • 谢谢,斯蒂芬穆斯。我查看了用于测试的 Flask 文档,结果是空的。您的解决方案测试*响应*。我想测试的是 *request*,特别是传递给 `render_template()` 的值。我可以使用 `test_request_context()` 然后访问 `flask.request`,但这并没有让我更接近于我想要的测试请求。 (3认同)

til*_*cog 5

Flask官方文档建议您使用template_rendered信号 (自版本0.6起可用)对模板以及用于渲染它的变量进行单元测试。

例如,这是一个帮助程序上下文管理器,可以在单元测试中使用它来确定呈现了哪些模板以及将哪些变量传递给了模板:

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)
Run Code Online (Sandbox Code Playgroud)

现在,可以轻松地将其与测试客户端配对:

with captured_templates(app) as templates:
    rv = app.test_client().get('/')
    assert rv.status_code == 200
    assert len(templates) == 1
    template, context = templates[0]
    assert template.name == 'index.html'
    assert len(context['items']) == 10
Run Code Online (Sandbox Code Playgroud)