2016-04-22 73 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