对象已附加到会话

时间:2017-10-16 13:21:11

标签: python session sqlalchemy

我正在尝试为使用它自己的数据库连接的Flask应用程序中的模块编写单元测试。

模块打开它的连接:

engine = create_engine(SQLALCHEMY_DATABASE_URI)
Session = sessionmaker(bind=engine)
session = Session()

然后我在整个模块中使用session

我的单元测试在conftest.py上有一个夹具来创建一个新会话:

@pytest.yield_fixture(scope='module')
def test_session(app):
    """
    Creates a new database session for a test. Note you must use this fixture
    if your test connects to db.

    Here we not only support commit calls but also rollback calls in tests,
    :coolguy:.
    """
    connection = db.engine.connect()
    transaction = connection.begin()

    options = dict(bind=connection, binds={})
    db_session = db.create_scoped_session(options=options)

    db_session.begin_nested()

    # session is actually a scoped_session
    # for the `after_transaction_end` event, we need a session instance to
    # listen for, hence the `session()` call
    @sqlalchemy.event.listens_for(db_session(), 'after_transaction_end')
    def restart_savepoint(sess, trans):
        if trans.nested and not trans._parent.nested:
            db_session.expire_all()
            db_session.begin_nested()

    db.session = db_session

    yield db_session

    db_session.remove()
    transaction.rollback()
    connection.close()

在我的测试中我这样做:

def test_schedule_orders_by_last_update(test_session, create_test_user):
    vendor = test_session.query(Vendors).filter(Vendors.name == 'Melie Bianco').first()
    amazon = AmazonRequests(vendor)
    amazon.schedule_orders_by_last_update()
    result = test_session.query(AmazonReportRequests).filter(AmazonReportRequests.vendor == vendor).all()
    assert len(result) == 1
    assert result.vendor.name == vendor.name

我的问题是,当我运行测试时,它总是以下列错误结束:

self = <sqlalchemy.orm.session.Session object at 0x1104fab50>, state = <sqlalchemy.orm.state.InstanceState object at 0x110863f10>, obj = <AmazonReportRequests None>

    def _before_attach(self, state, obj):
        if state.session_id == self.hash_key:
            return False

        if state.session_id and state.session_id in _sessions:
            raise sa_exc.InvalidRequestError(
                "Object '%s' is already attached to session '%s' "
                "(this is '%s')" % (state_str(state),
>                                   state.session_id, self.hash_key))
E           InvalidRequestError: Object '<AmazonReportRequests at 0x110863e90>' is already attached to session '2' (this is '1')

查询是否只是从数据库中检索行并忽略其他会话?

0 个答案:

没有答案