2016-04-22 74 views
1

我正在尝试编写一个简单的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) 

应用程序/ 初始化的.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

回答

1

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

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

我建议你反转依赖关系。相反,views.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对象。

+0

如果我将使用蓝图,在我的情况下注册create_app函数中的蓝图可能会更好? – Stright

+0

是的,蓝图是处理烧瓶路线的最佳方式 – iurisilvio

+0

非常感谢! – Stright