gpt4 book ai didi

python - pytest Flask-SQLAlchemy session 中的完整性错误

转载 作者:行者123 更新时间:2023-12-04 16:46:23 25 4
gpt4 key购买 nike

我正在将 Flask 应用程序的测试从 unittest 移植到 pytest。对于需要数据库的测试,我添加了一个返回数据库 session 的装置

DB 是一个运行 PostgreSQL 数据库的 SQLAlchemy 对象

import pytest
from app import create_app, db
from app.models import Project, Client

@pytest.fixture(scope='function')
def db_session():
app = create_app('testing')

app_context = app.app_context()
app_context.push()

db.create_all()

yield db.session

db.session.remove()
db.drop_all()
app_context.pop()

def test_getJson_withOneProjectSet_returnsBasicClientJson(db_session):
testClient = Client()
db_session.add(testClient)

testProject = Project()
db_session.add(testProject)

testClient.projects.append(testProject)

db_session.commit()

clientJson = testClient.getJson()

assert len(clientJson['projects']) == 1


def test_getJson_withThreeProjectsSet_returnsBasicClientJson(db_session):
testClient = Client()
db_session.add(testClient)

testProject1 = Project()
db_session.add(testProject1)

testProject2 = Project()
db_session.add(testProject2)

testProject3 = Project()
db_session.add(testProject3)

testClient.projects.append(testProject1)
testClient.projects.append(testProject2)
testClient.projects.append(testProject3)

db_session.commit()

clientJson = testClient.getJson()

assert len(clientJson['projects']) == 3

运行测试时,第一个通过,但第二个返回完整性错误: sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) duplicate key value violates unique constraint "project_code_key"

显然,在完成测试功能后,数据库没有被清理

该 fixture 是来自工作单元测试设置/拆卸功能的端口,它没有完整性错误问题:
# 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()

最佳答案

尝试将 scope="module"而不是 function,scope module 意味着将此数据库用于所有测试,然后将其删除

关于python - pytest Flask-SQLAlchemy session 中的完整性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com