如何为每个单元测试正确设置单个SQLAlchemy会话?

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

在使用WebTest测试我的Pyramid应用程序时,我无法在测试中创建/使用单独的Session,而不会收到有关已经存在的作用域会话的警告。

这是Pyramid应用程序的main()函数,它是数据库的配置位置。

# __init__.py of Pyramid application

from pyramid_sqlalchemy import init_sqlalchemy
from sqlalchemy import create_engine


def main(global_config, **settings):
    ...
    db_url = 'some-url'
    engine = create_engine(db_url)
    init_sqlalchemy(engine)  # Warning thrown here.

这是测试代码。

# test.py (Functional tests)

import transaction
from unittest import TestCase
from pyramid.paster import get_appsettings
from pyramid_sqlalchemy import init_sqlalchemy, Session
from sqlalchemy import create_engine
from webtest import TestApp

from app import main
from app.models.users import User


class BaseTestCase(TestCase):
    def base_set_up(self):
        # Create app using WebTest
        settings = get_appsettings('test.ini', name='main')
        app = main({}, **settings)
        self.test_app = TestApp(app)

        # Create session for tests.
        db_url = 'same-url-as-above'
        engine = create_engine(db_url)
        init_sqlalchemy(engine)
        # Note: I've tried both using pyramid_sqlalchemy approach here and 
        # creating a "plain, old" SQLAlchemy session here using sessionmaker.

    def base_tear_down(self):
        Session.remove()


class MyTests(BaseTestCase):
    def setUp(self):
        self.base_set_up()

        with transaction.manager:
            self.user = User('[email protected]', 'John', 'Smith')
            Session.add(self.user)
            Session.flush()

            Session.expunge_all()
        ...

    def tearDown(self):
        self.base_tear_down()

    def test_1(self):
        # This is a typical workflow on my tests.
        response = self.test_app.patch_json('/users/{0}'.format(self.user.id), {'email': '[email protected]')
        self.assertEqual(response.status_code, 200)

        user = Session.query(User).filter_by(id=self.user.id).first()
        self.assertEqual(user.email, '[email protected]')
    ...
    def test_8(self):
        ...

运行测试给我8次通过,7次警告,除了第一次测试之外的每个测试都给出以下警告:

来自Pyramid应用程序:__init__.py -> main -> init_sqlalchemy(engine):sqlalchemy.exc.SAWarning:至少有一个作用域会话已经存在。 configure()不会影响已创建的会话。

如果这是有用的,我相信我在这里看到同样的问题,除了我使用pyramid_sqlalchemy而不是创建我自己的DBSession。

https://github.com/Pylons/webtest/issues/5

python-3.x sqlalchemy pyramid webtest
1个回答
1
投票

回答我自己的问题:我不确定这是否是最好的方法,但是对我有用。

我没有尝试在我的测试中创建单独的会话,而是使用在应用程序中配置的pyramid_sqlalchemy会话工厂。据我所知,在测试和应用程序代码中调用Session返回相同的注册scoped_session。

我为测试创建单独会话的初衷是确认记录正在写入数据库,而不仅仅是在活动的SQLAlchemy会话中更新。通过这种新方法,我通过在测试中发布Session.expire_all()来避免这些“缓存”问题,我在测试事务和应用程序事务之间进行转换。

# test.py (Functional tests)

import transaction
from unittest import TestCase
from pyramid.paster import get_appsettings
from pyramid_sqlalchemy import Session
from webtest import TestApp

from app import main
from app.models.users import User


class BaseTestCase(TestCase):
    def base_set_up(self):
        # Create app using WebTest
        settings = get_appsettings('test.ini', name='main')
        app = main({}, **settings)
        self.test_app = TestApp(app)

        # Don't set up an additional session in the tests. Instead import
        # and use pyramid_sqlalchemy.Session, which is set up in the application.

    def base_tear_down(self):
        Session.remove()


class MyTests(BaseTestCase):
    def setUp(self):
        self.base_set_up()

        with transaction.manager:
            self.user = User('[email protected]', 'John', 'Smith')
            Session.add(self.user)
            Session.flush()

            Session.expunge_all()
            Session.expire_all()  # "Reset" your session.

    def tearDown(self):
        self.base_tear_down()
© www.soinside.com 2019 - 2024. All rights reserved.