def test_explode_in_initializer(self): engine = engines.testing_engine() def broken_initialize(connection): connection.execute("select fake_stuff from _fake_table") engine.dialect.initialize = broken_initialize # raises a DBAPIError, not an AttributeError assert_raises(exc.DBAPIError, engine.connect) # dispose connections so we get a new one on # next go engine.dispose() p1 = engine.pool def is_disconnect(e, conn, cursor): return True engine.dialect.is_disconnect = is_disconnect # invalidate() also doesn't screw up assert_raises(exc.DBAPIError, engine.connect) # pool was recreated assert engine.pool is not p1
def test_deleted_flag(self): users, User = self.tables.users, self.classes.User mapper(User, users) sess = sessionmaker()() u1 = User(name='u1') sess.add(u1) sess.commit() sess.delete(u1) sess.flush() assert u1 not in sess assert_raises(sa.exc.InvalidRequestError, sess.add, u1) sess.rollback() assert u1 in sess sess.delete(u1) sess.commit() assert u1 not in sess assert_raises(sa.exc.InvalidRequestError, sess.add, u1) make_transient(u1) sess.add(u1) sess.commit() eq_(sess.query(User).count(), 1)
def test_clauseelement(self): metadata = MetaData() table = Table('test_table', metadata, Column('foo', Integer)) metadata.create_all(bind=testing.db) try: for elem in [ table.select, lambda **kwargs: sa.func.current_timestamp(**kwargs).select(), # func.current_timestamp().select, lambda **kwargs:text("select * from test_table", **kwargs) ]: for bind in ( testing.db, testing.db.connect() ): try: e = elem(bind=bind) assert e.bind is bind e.execute().close() finally: if isinstance(bind, engine.Connection): bind.close() e = elem() assert e.bind is None assert_raises( exc.UnboundExecutionError, e.execute ) finally: if isinstance(bind, engine.Connection): bind.close() metadata.drop_all(bind=testing.db)
def test_mapped_managerattr(self): t = Table('t', MetaData(), Column('id', Integer, primary_key=True), Column(instrumentation.ClassManager.MANAGER_ATTR, Integer)) class T(object): pass assert_raises(KeyError, mapper, T, t)
def test_notcallable(self): class Point(object): pass table = self.point_map(Point) alias = aliased(Point) assert_raises(TypeError, alias)
def test_existing_plus_useexisting_raises(self): meta2 = self._useexisting_fixture() assert_raises( exc.ArgumentError, Table, 'users', meta2, useexisting=True, extend_existing=True )
def test_literal_interpretation(self): t = table('test', column('col1')) assert_raises(exc.ArgumentError, case, [("x", "y")]) self.assert_compile(case([("x", "y")], value=t.c.col1), "CASE test.col1 WHEN :param_1 THEN :param_2 END") self.assert_compile(case([(t.c.col1==7, "y")], else_="z"), "CASE WHEN (test.col1 = :col1_1) THEN :param_1 ELSE :param_2 END")
def test_noninherited_warning(self): A, B, b_table, a_table, Dest, dest_table = (self.classes.A, self.classes.B, self.tables.b_table, self.tables.a_table, self.classes.Dest, self.tables.dest_table) mapper(A, a_table, properties={'some_dest': relationship(Dest)}) mapper(B, b_table, inherits=A, concrete=True) mapper(Dest, dest_table) b = B() dest = Dest() assert_raises(AttributeError, setattr, b, 'some_dest', dest) clear_mappers() mapper(A, a_table, properties={'a_id': a_table.c.id}) mapper(B, b_table, inherits=A, concrete=True) mapper(Dest, dest_table) b = B() assert_raises(AttributeError, setattr, b, 'a_id', 3) clear_mappers() mapper(A, a_table, properties={'a_id': a_table.c.id}) mapper(B, b_table, inherits=A, concrete=True) mapper(Dest, dest_table)
def test_clauseelement(self): metadata = MetaData() table = Table('test_table', metadata, Column('foo', Integer)) metadata.create_all(bind=testing.db) try: for elem in [ table.select, lambda **kwargs: sa.func.current_timestamp(**kwargs). select(), # func.current_timestamp().select, lambda **kwargs: text("select * from test_table", **kwargs) ]: for bind in (testing.db, testing.db.connect()): try: e = elem(bind=bind) assert e.bind is bind e.execute().close() finally: if isinstance(bind, engine.Connection): bind.close() e = elem() assert e.bind is None assert_raises(exc.UnboundExecutionError, e.execute) finally: if isinstance(bind, engine.Connection): bind.close() metadata.drop_all(bind=testing.db)
def test_accounting_commit_fails_delete(self): User = self.classes.User sess = create_session(autocommit=True) fail = False def fail_fn(*arg, **kw): if fail: raise Exception("commit fails") event.listen(sess, "after_flush_postexec", fail_fn) u1 = User(name='ed') sess.add(u1) sess.flush() sess.delete(u1) fail = True assert_raises( Exception, sess.flush ) fail = False assert u1 in sess assert u1 not in sess.deleted sess.delete(u1) sess.flush() assert u1 not in sess eq_( sess.query(User.name).order_by(User.name).all(), [] )
def test_join_from_columns_or_subclass_six(self): sess = create_session() if self.select_type == '': # this now raises, due to [ticket:1892]. Manager.person_id # is now the "person_id" column on Manager. SQL is incorrect. assert_raises( sa_exc.DBAPIError, sess.query(Person.name).join( paperwork, Manager.person_id == paperwork.c.person_id).order_by( Person.name).all) elif self.select_type == 'Unions': # with the union, not something anyone would really be using # here, it joins to the full result set. This is 0.6's # behavior and is more or less wrong. expected = [(u'dilbert', ), (u'dilbert', ), (u'dogbert', ), (u'dogbert', ), (u'pointy haired boss', ), (u'vlad', ), (u'wally', ), (u'wally', )] eq_( sess.query(Person.name).join( paperwork, Manager.person_id == paperwork.c.person_id).order_by( Person.name).all(), expected) else: # when a join is present and managers.person_id is available, # you get the managers. expected = [(u'dogbert', ), (u'dogbert', ), (u'pointy haired boss', )] eq_( sess.query(Person.name).join( paperwork, Manager.person_id == paperwork.c.person_id).order_by( Person.name).all(), expected)
def test_rollback_recover(self): users, User = self.tables.users, self.classes.User mapper(User, users) session = sessionmaker()() u1, u2, u3= \ User(name='u1'),\ User(name='u2'),\ User(name='u3') session.add_all([u1, u2, u3]) session.commit() session.delete(u2) u4 = User(name='u2') session.add(u4) session.flush() u5 = User(name='u3') session.add(u5) assert_raises(orm_exc.FlushError, session.flush) assert u5 not in session assert u2 not in session.deleted session.rollback()
def test_string_dates_passed_raise(self): assert_raises( exc.StatementError, testing.db.execute, select([1]).where(bindparam("date", type_=Date)), date=str(datetime.date(2007, 10, 30)), )
def test_deleted_flag(self): users, User = self.tables.users, self.classes.User mapper(User, users) sess = sessionmaker()() u1 = User(name="u1") sess.add(u1) sess.commit() sess.delete(u1) sess.flush() assert u1 not in sess assert_raises(sa.exc.InvalidRequestError, sess.add, u1) sess.rollback() assert u1 in sess sess.delete(u1) sess.commit() assert u1 not in sess assert_raises(sa.exc.InvalidRequestError, sess.add, u1) make_transient(u1) sess.add(u1) sess.commit() eq_(sess.query(User).count(), 1)
def test_pk_violation_with_savepoint(self): User, Address = self.classes.User, self.classes.Address s = self.session() a1 = Address(email_address='foo') u1 = User(id=1, name='ed', addresses=[a1]) s.add(u1) s.commit() a2 = Address(email_address='bar') u2 = User(id=1, name='jack', addresses=[a2]) u1.name = 'edward' a1.email_address = 'foober' s.begin_nested() s.add(u2) assert_raises(sa_exc.FlushError, s.commit) assert_raises(sa_exc.InvalidRequestError, s.commit) s.rollback() assert u2 not in s assert a2 not in s assert u1 in s assert a1 in s s.commit() eq_( s.query(User).all(), [User(id=1, name='edward', addresses=[Address(email_address='foober')])] )
def test_accounting_commit_fails_delete(self): User = self.classes.User sess = create_session(autocommit=True) fail = False def fail_fn(*arg, **kw): if fail: raise Exception("commit fails") event.listen(sess, "after_flush_postexec", fail_fn) u1 = User(name='ed') sess.add(u1) sess.flush() sess.delete(u1) fail = True assert_raises(Exception, sess.flush) fail = False assert u1 in sess assert u1 not in sess.deleted sess.delete(u1) sess.flush() assert u1 not in sess eq_(sess.query(User.name).order_by(User.name).all(), [])
def test_versioncheck_for_update(self): """query.with_lockmode performs a 'version check' on an already loaded instance""" Foo = self.classes.Foo s1 = self._fixture() f1s1 = Foo(value='f1 value') s1.add(f1s1) s1.commit() s2 = create_session(autocommit=False) f1s2 = s2.query(Foo).get(f1s1.id) s2.refresh(f1s2, lockmode='update') f1s2.value='f1 new value' assert_raises( exc.DBAPIError, s1.refresh, f1s1, lockmode='update_nowait' ) s1.rollback() s2.commit() s1.refresh(f1s1, lockmode='update_nowait') assert f1s1.version_id == f1s2.version_id
def test_retval_flag(self): canary = [] def tracker(name): def go(conn, *args, **kw): canary.append(name) return go def execute(conn, clauseelement, multiparams, params): canary.append('execute') return clauseelement, multiparams, params def cursor_execute(conn, cursor, statement, parameters, context, executemany): canary.append('cursor_execute') return statement, parameters engine = engines.testing_engine() assert_raises( tsa.exc.ArgumentError, event.listen, engine, "begin", tracker("begin"), retval=True ) event.listen(engine, "before_execute", execute, retval=True) event.listen(engine, "before_cursor_execute", cursor_execute, retval=True) engine.execute(select([1])) eq_( canary, ['execute', 'cursor_execute'] )
def test_can_use_session_in_outer_rollback_hook(self): User, users = self.classes.User, self.tables.users mapper(User, users) sess = Session() assertions = [] @event.listens_for(sess, "after_soft_rollback") def do_something(session, previous_transaction): if session.is_active: assertions.append('name' not in u.__dict__) assertions.append(u.name == 'u1') u = User(name='u1', id=1) sess.add(u) sess.commit() u2 = User(name='u1', id=1) sess.add(u2) assert_raises( sa.orm.exc.FlushError, sess.commit ) sess.rollback() eq_(assertions, [True, True])
def test_rollback_hook(self): User, users = self.classes.User, self.tables.users sess, canary = self._listener_fixture() mapper(User, users) u = User(name="u1", id=1) sess.add(u) sess.commit() u2 = User(name="u1", id=1) sess.add(u2) assert_raises(sa.orm.exc.FlushError, sess.commit) sess.rollback() eq_( canary, [ "after_attach", "before_commit", "before_flush", "after_begin", "after_flush", "after_flush_postexec", "after_commit", "after_attach", "before_commit", "before_flush", "after_begin", "after_rollback", "after_soft_rollback", "after_soft_rollback", ], )
def test_pk_violation_with_savepoint(self): User, Address = self.classes.User, self.classes.Address s = self.session() a1 = Address(email_address='foo') u1 = User(id=1, name='ed', addresses=[a1]) s.add(u1) s.commit() a2 = Address(email_address='bar') u2 = User(id=1, name='jack', addresses=[a2]) u1.name = 'edward' a1.email_address = 'foober' s.begin_nested() s.add(u2) assert_raises(sa_exc.FlushError, s.commit) assert_raises(sa_exc.InvalidRequestError, s.commit) s.rollback() assert u2 not in s assert a2 not in s assert u1 in s assert a1 in s s.commit() eq_( s.query(User).all(), [ User(id=1, name='edward', addresses=[Address(email_address='foober')]) ])
def test_too_long_idx_name(self): dialect = testing.db.dialect.__class__() for max_ident, max_index in [(22, None), (256, 22)]: dialect.max_identifier_length = max_ident dialect.max_index_name_length = max_index for tname, cname, exp in [ ('sometable', 'this_name_is_too_long', 'ix_sometable_t_09aa'), ('sometable', 'this_name_alsois_long', 'ix_sometable_t_3cf1'), ]: t1 = Table(tname, MetaData(), Column(cname, Integer, index=True), ) ix1 = list(t1.indexes)[0] self.assert_compile( schema.CreateIndex(ix1), "CREATE INDEX %s " "ON %s (%s)" % (exp, tname, cname), dialect=dialect ) dialect.max_identifier_length = 22 dialect.max_index_name_length = None t1 = Table('t', MetaData(), Column('c', Integer)) assert_raises( exc.IdentifierError, schema.CreateIndex(Index( "this_other_name_is_too_long_for_what_were_doing", t1.c.c)).compile, dialect=dialect )
def test_precolumns(self): dialect = self.__dialect__ def gen(distinct=None, prefixes=None): kw = {} if distinct is not None: kw['distinct'] = distinct if prefixes is not None: kw['prefixes'] = prefixes return str(select(['q'], **kw).compile(dialect=dialect)) eq_(gen(None), 'SELECT q') eq_(gen(True), 'SELECT DISTINCT q') assert_raises( exc.SADeprecationWarning, gen, 'DISTINCT' ) eq_(gen(prefixes=['ALL']), 'SELECT ALL q') eq_(gen(prefixes=['DISTINCTROW']), 'SELECT DISTINCTROW q') # Interaction with CUBRID prefix extensions eq_( gen(None, ['straight_join']), 'SELECT straight_join q') eq_( gen(False, ['HIGH_PRIORITY', 'SQL_SMALL_RESULT', 'ALL']), 'SELECT HIGH_PRIORITY SQL_SMALL_RESULT ALL q') eq_( gen(True, ['high_priority', sql.text('sql_cache')]), 'SELECT high_priority sql_cache DISTINCT q')
def test_empty_insert_pk3(self): assert_raises( exc.DBAPIError, self._test_empty_insert, Table('c', MetaData(testing.db), Column('x', Integer, primary_key=True), Column('y', Integer, DefaultClause('123'), primary_key=True)))
def test_invalid_options(self): assert_raises(exc.ArgumentError, select().execution_options, compiled_cache={}) assert_raises(exc.ArgumentError, select().execution_options, isolation_level='READ_COMMITTED')
def test_raise_index_nonexistent_name(self): m = MetaData() # the KeyError isn't ideal here, a nicer message # perhaps assert_raises( KeyError, Table, 't', m, Column('x', Integer), Index("foo", "q") )
def test_ad_hoc_schema_equiv_fk(self): m = MetaData() t1 = Table('t1', m, Column('x', Integer), schema="foo") t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')), schema="foo") assert_raises( exc.NoReferencedTableError, lambda: t2.c.x.references(t1.c.x) )
def test_default_schema_metadata_fk_alt_local_raises(self): m = MetaData(schema="foo") t1 = Table('t1', m, Column('x', Integer), schema="bar") t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x'))) assert_raises( exc.NoReferencedTableError, lambda: t2.c.x.references(t1.c.x) )
def test_dont_persist_alias(self): db = sqlsoup.SqlSoup(engine) MappedBooks = db.books b = db.books._table s = select([b.c.published_year, func.count("*").label("n")], from_obj=[b], group_by=[b.c.published_year]) s = s.alias("years_with_count") years_with_count = db.map(s, primary_key=[s.c.published_year]) assert_raises(exc.InvalidRequestError, years_with_count.insert, published_year="2007", n=1)
def test_indirect(self): def listen(x, y): pass event.listen("one", "event_one", listen) eq_(list(self.Target().dispatch.event_one), [listen]) assert_raises(exc.InvalidRequestError, event.listen, listen, "event_one", self.Target)
def test_pending_raises(self): users, User = self.tables.users, self.classes.User # this was the opposite in 0.4, but the reasoning there seemed off. # expiring a pending instance makes no sense, so should raise mapper(User, users) sess = create_session() u = User(id=15) sess.add(u) assert_raises(sa_exc.InvalidRequestError, sess.expire, u, ["name"])
def test_no_session(self): users, User = self.tables.users, self.classes.User mapper(User, users) sess = create_session() u = sess.query(User).get(7) sess.expire(u, attribute_names=["name"]) sess.expunge(u) assert_raises(orm_exc.DetachedInstanceError, getattr, u, "name")
def test_connect_multiple(self): dbapi = MockDBAPI() p = pool.AssertionPool(creator = lambda: dbapi.connect('foo.db')) c1 = p.connect() c1.close() c2 = p.connect() c2.close() c3 = p.connect() assert_raises(AssertionError, p.connect)
def test_no_session(self): users, User = self.tables.users, self.classes.User mapper(User, users) sess = create_session() u = sess.query(User).get(7) sess.expire(u, attribute_names=['name']) sess.expunge(u) assert_raises(orm_exc.DetachedInstanceError, getattr, u, 'name')
def test_pending_raises(self): users, User = self.tables.users, self.classes.User # this was the opposite in 0.4, but the reasoning there seemed off. # expiring a pending instance makes no sense, so should raise mapper(User, users) sess = create_session() u = User(id=15) sess.add(u) assert_raises(sa_exc.InvalidRequestError, sess.expire, u, ['name'])
def test_raise_clauseelement_not_a_column(self): m = MetaData() t2 = Table('t2', m, Column('x', Integer)) class SomeClass(object): def __clause_element__(self): return t2 assert_raises( exc.ArgumentError, Index, "foo", SomeClass() )
def test_metadata_tables_immutable(self): metadata = MetaData() t1 = Table('t1', metadata, Column('x', Integer)) assert 't1' in metadata.tables assert_raises( TypeError, lambda: metadata.tables.pop('t1') )
def test_connect_multiple(self): dbapi = MockDBAPI() p = pool.AssertionPool(creator=lambda: dbapi.connect('foo.db')) c1 = p.connect() c1.close() c2 = p.connect() c2.close() c3 = p.connect() assert_raises(AssertionError, p.connect)
def test_uselist_false_warning(self): """test that multiple rows received by a uselist=False raises a warning.""" User, users, orders, Order = (self.classes.User, self.tables.users, self.tables.orders, self.classes.Order) mapper(User, users, properties={"order": relationship(Order, uselist=False)}) mapper(Order, orders) s = create_session() u1 = s.query(User).filter(User.id == 7).one() assert_raises(sa.exc.SAWarning, getattr, u1, "order")
def test_two_metadata_join_raises(self): m = MetaData() m2 = MetaData() t1 = Table('t1', m, Column('id', Integer), Column('id2', Integer)) t2 = Table('t2', m, Column('id', Integer, ForeignKey('t1.id'))) t3 = Table('t3', m2, Column('id', Integer, ForeignKey('t1.id2'))) s = select([t2, t3], use_labels=True) assert_raises(exc.NoReferencedTableError, s.join, t1)
def test_wraps_connect_in_dbapi(self): # sqlite uses SingletonThreadPool which doesnt have max_overflow assert_raises(TypeError, create_engine, 'sqlite://', max_overflow=5, module=mock_sqlite_dbapi) e = create_engine('sqlite://', connect_args={'use_unicode' : True}, convert_unicode=True) try: e.connect() except tsa.exc.DBAPIError, de: assert not de.connection_invalidated
def test_kw_plus_opt_sig(self): cls, canary = self._kw_only_fixture() assert_raises( TypeError, cls, "a", "b", "c" ) assert_raises( TypeError, cls, "a", "b", c="c" )
def test_append_listener(self): metadata, table, bind = self.metadata, self.table, self.bind fn = lambda *a: None table.append_ddl_listener('before-create', fn) assert_raises(exc.InvalidRequestError, table.append_ddl_listener, 'blah', fn) metadata.append_ddl_listener('before-create', fn) assert_raises(exc.InvalidRequestError, metadata.append_ddl_listener, 'blah', fn)
def test_ensure_is_disconnect_gets_connection(self): def is_disconnect(e, conn, cursor): # connection is still present assert conn.connection is not None # the error usually occurs on connection.cursor(), # though MySQLdb we get a non-working cursor. # assert cursor is None engine.dialect.is_disconnect = is_disconnect conn = engine.connect() engine.test_shutdown() assert_raises(tsa.exc.DBAPIError, conn.execute, select([1]))
def _inactive_flushed_session_fixture(self): users, User = self.tables.users, self.classes.User mapper(User, users) sess = Session() u1 = User(id=1, name='u1') sess.add(u1) sess.commit() sess.add(User(id=1, name='u2')) assert_raises(orm_exc.FlushError, sess.flush) return sess, u1
def test_uselist_false_warning(self): """test that multiple rows received by a uselist=False raises a warning.""" User, users, orders, Order = (self.classes.User, self.tables.users, self.tables.orders, self.classes.Order) mapper(User, users, properties={'order': relationship(Order, uselist=False)}) mapper(Order, orders) s = create_session() u1 = s.query(User).filter(User.id == 7).one() assert_raises(sa.exc.SAWarning, getattr, u1, 'order')
def test_dont_persist_alias(self): db = sqlsoup.SqlSoup(engine) MappedBooks = db.books b = db.books._table s = select([b.c.published_year, func.count('*').label('n')], from_obj=[b], group_by=[b.c.published_year]) s = s.alias('years_with_count') years_with_count = db.map(s, primary_key=[s.c.published_year]) assert_raises(exc.InvalidRequestError, years_with_count.insert, published_year='2007', n=1)
def test_no_instance_key(self): Engineer = self.classes.Engineer # same as test_no_instance_key, but the PK columns # are absent. ensure an error is raised. sess = create_session() e1 = sess.query(Engineer).get(2) sess.expire(e1, attribute_names=['name', 'person_id']) sess.expunge(e1) attributes.instance_state(e1).key = None assert 'name' not in e1.__dict__ sess.add(e1) assert_raises(sa_exc.InvalidRequestError, getattr, e1, 'name')
def test_too_long_name_disallowed(self): m = MetaData(testing.db) t1 = Table("this_name_is_too_long_for_what_were_doing_in_this_test", m, Column('foo', Integer)) assert_raises(exceptions.IdentifierError, m.create_all) assert_raises(exceptions.IdentifierError, m.drop_all) assert_raises(exceptions.IdentifierError, t1.create) assert_raises(exceptions.IdentifierError, t1.drop)
def test_no_instance_key_no_pk(self): users, User = self.tables.users, self.classes.User # same as test_no_instance_key, but the PK columns # are absent. ensure an error is raised. mapper(User, users) sess = create_session() u = sess.query(User).get(7) sess.expire(u, attribute_names=['name', 'id']) sess.expunge(u) attributes.instance_state(u).key = None assert 'name' not in u.__dict__ sess.add(u) assert_raises(sa_exc.InvalidRequestError, getattr, u, 'name')
def test_wraps_connect_in_dbapi(self): # sqlite uses SingletonThreadPool which doesnt have max_overflow assert_raises(TypeError, create_engine, 'sqlite://', max_overflow=5, module=mock_sqlite_dbapi) e = create_engine('sqlite://', connect_args={'use_unicode': True}, convert_unicode=True) try: e.connect() except tsa.exc.DBAPIError, de: assert not de.connection_invalidated