每次测试后,SQLAlchemy 数据库会话不会重置

问题描述 投票:0回答:1

我有这个 TestRunner 基类,主要遵循他们的示例

import unittest

from sqlalchemy import create_engine
from sqlalchemy.event import listens_for
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker

from compliance.takedowns.data.models import Base

engine = create_engine('sqlite:///:memory:')
SessionFactory = scoped_session(sessionmaker(bind=engine))
Base.metadata.create_all(engine)  # Initial schema setup


class TakedownsDBInternalTestRunner(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.engine = engine

    def setUp(self):
        self.connection = self.engine.connect()
        self.trans = self.connection.begin()
        self.session = SessionFactory

        self.nested = self.connection.begin_nested()

        @listens_for(self.session, "after_transaction_end")
        def end_savepoint(session, transaction):
            assert self.nested is not None
            if not self.nested.is_active:
                self.nested = self.connection.begin_nested()

    def tearDown(self):
        self.session.close()
        self.trans.rollback()
        self.connection.close()

但是我注意到我在测试之间遇到了引用完整性错误?

class RequestTests(TakedownsDBInternalTestRunner):
    def test_one(self):
        request = create_base_request()
        self.session.add(request)
        self.session.commit()

        result = self.session.query(Request).all()
        self.assertEqual(len(result), 1)

    def test_two(self):
        request = create_base_request()
        self.session.add(request)
        self.session.commit()

        result = self.session.query(Request).all()
        self.assertEqual(len(result), 2)

这是我得到的错误:

========================================================================================================= short test summary info =========================================================================================================
FAILED test_request.py::RequestTests::test_two - AssertionError: 1 != 2
FAILED test_request.py::RequestTests::test_one - AssertionError: 2 != 1
python sqlalchemy
1个回答
0
投票

我能想象到的唯一问题是从其他模块导入 Base。可能会在没有正确绑定的情况下创建多个会话,这可能会导致回滚故障。声明一个带有测试模型的新基地,以正确隔离测试环境。如果这解决了问题,我们可以调试其余部分

我们还可以探索像 model-bakery 这样的库,这可能会帮助我们隔离我们的模型,尽管我不确定

© www.soinside.com 2019 - 2024. All rights reserved.