python - 在集成测试 (Pytest) 和 Flask 应用程序之间创建不同的 SQLAlchemy 会话
问题描述
我有使用 flask-sqlalchemy lib 的烧瓶应用程序(RESTful API 后端)。集成测试使用带有固定装置的 Pytest,有些为测试目的创建记录。问题是,当测试预计会在数据库级别引发唯一约束失败的场景时,通过夹具为测试创建的记录都被回滚,导致其他测试失败并出现错误sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: my_table.field1
。
如何为测试创建不同的 SQLAlchemy 会话,以便测试记录可以提交到 DB 并且不受 Flask 请求生命周期内发生的错误的影响?
### globals.py ###
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
### app.py ###
from sqlalchemy.exc import IntegrityError
from .globals import db
def handle_unique_constraint(error):
return {"msg": "Duplicate"}, 409
def create_app(connection_string):
app = Flask(__name__)
app.register_error_handler(IntegrityError, handle_unique_constraint)
app.config['SQLALCHEMY_DATABASE_URI'] = connection_string
# register API blueprint ...
# e.g. create new user record, done like this:
#
# db.session.add(User(**{'email': path_param}))
# db.session.commit()
db.init_app(app)
return app
### conftest.py ###
from my_package.app import create_app
from my_package.globals import db as app_db
from my_package.models.user import User
@fixture(scope='session')
def app(request):
app = create_app('https://localhost')
app.debug = True
with app.app_context():
yield app
@fixture(scope='session')
def db(app):
app_db.create_all()
return app_db
@fixture(scope='session')
def client(app):
with app.test_client() as client:
yield client
@fixture(scope='function')
def test_user(db):
user = User(**{'email': generate_random()})
db.session.add(user)
db.session.commit()
db.session.refresh(user)
### test_user.py ###
# This test passses
def test_repeat_email(client, test_user):
resp = client.post('/users/emails/{}'.format(test_user.email))
assert resp.status_code == 409
# This test errors out during setting up test_user fixture
# with aforementioned error message
def test_good_email(client, test_user): # <- this
resp = client.post('/users/emails/{}'.format('unique@example.com'))
assert resp.status_code == 201
解决方案
您必须实现 asetUp
和 a tearDown
。
运行测试时,setUp
将在每个测试开始时运行。将tearDown
在每个结束时运行。
在setUp
你将:初始化数据库
在tearnDown
你将:关闭数据库连接,删除创建的项目......
在yield
它之前是setUp
零件,在它之后是tearDown
。
你应该有这样的东西:
@fixture(scope='session')
def app(request):
app = create_app('https://localhost')
app.debug = True
ctx = app.app_context()
ctx.push()
yield app
ctx.pop()
@fixture(scope='session')
def db(app):
app_db.create_all()
yield app_db
app_db.drop_all()
推荐阅读
- python - 在时间戳上连接两个不同的数据帧
- powershell - 从 [Reflection.Assembly]::Load() 加载的 DLL 导出 Powershell CMDlet
- javascript - 使用全局变量作为 mongodb 文档的计数器是否错误?
- python - 在运行“迁移”命令之前删除 Django 迁移文件?
- python - 将结果取决于先前结果的函数应用于 numpy 数组
- mysql - 选择任一列的值,但不能同时选择两者
- python - RegEx 不匹配没有换行符的回车
- web-applications - 是否有通过 bokeh serve --show 启动散景服务器的替代方法?
- google-sheets - 导入谷歌表格时如何让zapier每行添加1个字段
- c# - 返回的 Facebook 提要不包含用户名