1

这是我的测试文件:

from flask import Flask
from flask.ext.testing import TestCase


class TestInitViews(TestCase):

    render_templates = False

    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        return app

    def test_root_route(self):
        self.client.get('/')
        self.assert_template_used('index.html')

这是完整的堆栈跟踪:

$ nosetests tests/api/client/test_init_views.py
F
======================================================================
FAIL: test_root_route (tests.api.client.test_init_views.TestInitViews)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/dmonsewicz/dev/autoresponders/tests/api/client/test_init_views.py", line 17, in test_root_route
    self.assert_template_used('index.html')
  File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/flask_testing.py", line 120, in assertTemplateUsed
    raise AssertionError("template %s not used" % name)
AssertionError: template index.html not used

----------------------------------------------------------------------
Ran 1 test in 0.012s

FAILED (failures=1)

我是 Python 的新手,似乎无法弄清楚这一点。我要做的就是编写一个简单的测试来命中/(根路由)端点,并且asserts使用的模板实际上是index.html

尝试使用LiveServerTestCase

from flask import Flask
from flask.ext.testing import LiveServerTestCase


class TestInitViews(LiveServerTestCase):

    render_templates = False

    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        app.config['LIVESERVER_PORT'] = 6765

        return app

    def setUp(self):
        self.app = self.app.test_client()

    def test_root_route(self):
        res = self.app.get('/')

        print(res)

        self.assert_template_used('index.html')

我正在使用Flask-Testing版本0.4,由于某种原因LiveServerTestCase,我的导入中不存在

工作代码

from flask import Flask
from flask.ext.testing import TestCase
from api.client import blueprint


class TestInitViews(TestCase):

    render_templates = False

    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True

        app.register_blueprint(blueprint)

        return app

    def test_root_route(self):
        res = self.client.get('/')
        self.assert_template_used('index.html')
4

1 回答 1

1

您必须运行 pip install blinker 并确保您的烧瓶版本大于 0.6。

看起来您省略了设置 app.config['TESTING'] = True

我能够运行以下测试来验证断言是否为真:

#!/usr/bin/python

import unittest
from flask import Flask
from flask.ext.testing import TestCase
from flask import render_template


class MyTest(TestCase):

  def create_app(self):
    app = Flask(__name__)
    app.config['TESTING'] = True

    @app.route('/')
    def hello_world():
      return render_template('index.html')
    return app

  def test_root_route(self):
    self.client.get('/')
    self.assert_template_used('index.html')

if __name__ == '__main__':
  unittest.main()
于 2014-06-14T02:05:53.350 回答