Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pytest SQLAlchemy会话中的完整性错误_Python_Postgresql_Flask_Flask Sqlalchemy_Pytest - Fatal编程技术网

Python pytest SQLAlchemy会话中的完整性错误

Python pytest SQLAlchemy会话中的完整性错误,python,postgresql,flask,flask-sqlalchemy,pytest,Python,Postgresql,Flask,Flask Sqlalchemy,Pytest,我正在将烧瓶应用程序的测试从unittest移植到pytest。对于需要数据库的测试,我添加了一个返回DB会话的fixture 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 = creat

我正在将烧瓶应用程序的测试从unittest移植到pytest。对于需要数据库的测试,我添加了一个返回DB会话的fixture

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)重复键值违反唯一约束“project\u code\u key”

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

夹具是来自工作unittest设置/拆卸功能的端口,该功能没有完整性错误问题:

# 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”而不是函数,scope module意味着在所有测试中使用此db,然后将其删除