烧瓶测试 - 为什么测试失败

Flask-testing - why the test does fail

我正在尝试为一个简单的 Flask 应用程序编写测试。项目结构如下:

app/
    static/
    templates/
    forms.py
    models.py
    views.py
migrations/
config.py
manage.py
tests.py

tests.py

import unittest
from app import create_app, db
from flask import current_app
from flask.ext.testing import TestCase

class AppTestCase(TestCase):
    def create_app(self):
        return create_app('test_config')

    def setUp(self):
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_hello(self):
        response = self.client.get('/')
        self.assert_200(response)

app/init.py

# app/__init__.py

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from config import config

db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    return app

app = create_app('default')

from . import views

当我启动测试时,test_hello 失败,因为 response.status_code 是 404。请告诉我,我该如何解决?看来,该应用程序实例对 views.py 中的视图函数一无所知。如果需要完整代码,可以找到here

您的 views.py 文件在您的 __init__.py 文件中创建的 app 中安装路由。

您必须将这些路由绑定到您在 create_app 测试方法中创建的应用程序。

我建议你反转依赖关系。相反,views.py 导入您的代码,您可以从 __init__.py 或测试文件中导入和调用 init_app

# views.py
def init_app(app):
    app.add_url_rule('/', 'index', index)
    # repeat to each route

你可以做得更好,使用 Blueprint

def init_app(app):
    app.register_blueprint(blueprint)

这样,您的测试文件只需导入此 init_app 并将蓝图绑定到测试 app 对象。