【简说Python WEB】Flask应用的单元测试
tests/test_basics.py
import unittest
from flask import current_app
from app import create_app, db
class BasicsTestCase(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_exists(self):
self.assertFalse(current_app is None)
def test_app_is_testing(self):
self.assertTrue(current_app.config['TESTING'])
这里调用unitest
包,单元测试标准库。测试两个功能:
- 测试确保应用实例是否存在。
- 测试config配置文件是否正常。
主应用zsdblog.py
启动单元测试的命令
@app.cli.command()
@click.argument('test_names', nargs=-1)
def test(test_names):
"""Run the unit tests."""
import unittest
if test_names:
tests = unittest.TestLoader().loadTestsFromNames(test_names)
else:
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
为了报错,特定修改config.py
文件如下:
#..
class TestingConfig(Config):
TESTING = True
HOSTNAME = '172.30.200.252'
DATABASE = 'zsd'
USERNAME = 'zsd'
PASSWORD = 'zsd'
# DB_URI = 'mysql+pymysql://{}:{}@{}:3306/{}?charset=utf8mb4'.format(USERNAME, PASSWORD, HO
STNAME, DATABASE)
# SQLALCHEMY_DATABASE_URI = DB_URI
可以看到上述的TESTING
代表的tag标识。指定测试哪一个环境配置文件。
我这里特定注释掉DB_URI
和SQLALCHEMY_DATABASE_URI
,为了单元测试报错。如下:
启动测试:
(zsdpy1) $ flask test
test_app_exists (test_basics.BasicsTestCase) ... /home/zsd/venv/zsdpy1/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:814: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
ok
test_app_is_testing (test_basics.BasicsTestCase) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.024s
OK
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
报了这个错误,修改回上述config.py文件。测试正常,如下:
(zsdpy1) $ flask test
test_app_exists (test_basics.BasicsTestCase) ... ok
test_app_is_testing (test_basics.BasicsTestCase) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.122s
OK