2014-04-30 64 views
2

我正在開發我的第一個Flask應用程序。這是我的項目,所以我專注於良好的實踐和設計,並花時間。我有點卡住測試 - 我在文檔和這裏找到了一些例子,但它們要麼不適用於我的應用程序,要麼似乎沒有Pythonic /設計良好。在Flask中建立測試數據庫

的代碼中的相關作品是:

# application module __init__.py 
def create_app(config): 
    app = Flask(__name__) 
    app.config.from_object('config.%s' % config.title()) 
    return app 

config = os.getenv('CONFIG', 'development') 
app = create_app(config) 
db = SQLAlchemy(app) 

# config.py 
class Testing(Base): 
    TESTING = True 
    SQLALCHEMY_DATABASE_URI = \ 
     'sqlite:///' + os.path.join(_basedir, 'testing.sqlite') 

# models.py 
class User(db.Model): 
    __tablename__ = 'user' 
    id = db.Column(db.Integer, primary_key=True) 
    username = db.Column(db.String(60), unique=True, nullable=False) 
    password_hash = db.Column(db.String(60), nullable=False) 

# testing.py 
class TestCase(unittest.TestCase): 

    def setUp(self): 
     self.app = create_app('testing') 
     # TODO: create connection to testing db 

    def tearDown(self): 
     # TODO: abort transaction 
     pass 

現在的問題是:如何實現setUptearDown這樣在我的測試中我可以用我的模型和連接做測試數據庫?如果我只是導入db,它會在開發數據庫上工作。

如果它有幫助,我不需要從頭創建測試數據庫,我使用Flask-Migrate,測試可以假設測試數據庫已初始化併爲空。

歡迎任何評論,如果我的設計有缺陷,我不介意重構。

回答

5

看起來像你應該只是能夠運行CONFIG=Testing python -m unittest discover,並擁有一切工作。唯一覺得你可能要改變的是,而不是調用你的測試create_app,只需從__init__.py導入:

# testing.py 
from . import config, db 

class TestCase(unittest.TestCase): 

    def setUp(self): 
     self.app = create_app(config) 
     # db is properly set up to use the testing config 
     # but any *changes* you make to the db object 
     # (e. g. monkey-patching) will persist between tests 
     db.create_all() 

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

爲例見here

+0

非常感謝,那不是我固定它的方式,而是你向我展示了最重要的方向。 –