下面分析下这个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 git@github.com: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()