用flask開發個人部落格(28)—— 利用unittest進行單元測試
下面分析下這個webapp的單元測試模組test,請先看下目前test下的檔案結構:
目前__init__.py檔案還是空,請檢視test_basic.py的程式碼:
import unittest from flask import current_app from app import create_app,db class BasicTestCase(unittest.TestCase): def setup(self): self.app=create_app('testing') self.app_context=self.app.app_context() self.app_context.push() db.create_all() def teardown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_app_exits(self): self.assertFalse(current_app is None) def test_app_is_testing(self): self.assertFalse(current_app.config['TESTING'])
我們定義了一個測試用例的類,繼承自unittest.TestCase類,當執行測試用例時,測試引擎會跑遍所有的我們定義的該測試用例類的成員函式,其中setup和teardown函式比較特殊,在執行測試用例之前測試引擎會呼叫setup函式來建立執行測試用例所需的配置環境,包括建立資料、利用工廠 函式建立程式例項等等,而teardown用來在執行完測試用例後回收資源。
接著我們看下manager.py中呼叫單元測試的程式碼:
@manager.command def test(): """Run the unit tests""" import unittest tests=unittest.TestLoader().discover('test') unittest.TextTestRunner(verbosity=2).run(tests)
這裡tests=unittest.TestLoader().discover('test')是建立了單元測試的例項,其中discover中我們傳入的引數是單元測試的模組名稱,也就是下圖中的test資料夾:
該方法會所有test中所有的單元測試類行,然後執行其全部的成員函式作為單元測試用例。緊接著unittest.TextTestRunner(verbosity=2).run(tests)用來執行該測試例項。我們將單元測試的執行命令用manager.command作為修飾器封裝成了一個manager的命令,可以用過下面的語句進行執行:
python manager.py test
得到如下的執行結果:
test_app_exits (test_basic.BasicTestCase) ... ok
test_app_is_testing (test_basic.BasicTestCase) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Github位置:
https://github.com/HymanLiuTS/flaskTs
克隆本專案:
git clone [email protected]:HymanLiuTS/flaskTs.git
獲取本文原始碼:
git checkout FL28
---------------------
出處:https://blog.csdn.net/hyman_c/article/details/52886805
#!/usr/bin/env python
import os
from app import create_app,db
from app.models import User,Role,create_roles,Post
from flask_script import Manager,Shell
from flask_migrate import Migrate,MigrateCommand
app=create_app(os.getenv('FLASK_CONFIG') or'default')
manager=Manager(app)
migrate=Migrate(app,db)
def make_shell_context():
return dict(app=app,db=db,User=User,Role=Role,Post=Post,create_roles=create_roles)
manager.add_command("shell",Shell(make_context=make_shell_context))
manager.add_command('db',MigrateCommand)
COV=None
if os.environ.get('COVERAGE'):
import coverage
COV=coverage.coverage(branch=True,include='app/*')
COV.start()
@manager.command
def test(coverage=False):
"""Run the unit tests"""
if coverage and not os.environ.get('COVERAGE'):
import sys
os.environ['COVERAGE']='1'
os.execvp(sys.executable,[sys.executable]+sys.argv)
import unittest
tests=unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if COV:
COV.stop()
COV.save()
print('Coverage:')
COV.report()
COV.erase()
@manager.command
def myprint():
print 'hello world'
if __name__=='__main__':
manager.run()