新手烧瓶问题.
我有一个看起来像这样的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必须提供您的烧瓶应用程序.
我的建议是查看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官方文档建议您使用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)
| 归档时间: |
|
| 查看次数: |
8268 次 |
| 最近记录: |