Esempio n. 1
0
    def test_notcallable(self):
        class Point(object):
            pass
        table = self.point_map(Point)
        alias = aliased(Point)

        assert_raises(TypeError, alias)
 def test_bogus(self):
     assert_raises(exc.ArgumentError, Column, 'foo', name='bar')
     assert_raises(exc.ArgumentError,
                   Column,
                   'foo',
                   Integer,
                   type_=Integer())
Esempio n. 3
0
 def test_nonreflected_fk_raises(self):
     """test that a NoReferencedColumnError is raised when reflecting
     a table with an FK to another table which has not included the target
     column in its reflection.
     
     """
     meta = MetaData(testing.db)
     a1 = Table('a', meta,
         Column('x', sa.Integer, primary_key=True),
         Column('z', sa.Integer),
         test_needs_fk=True
     )
     b1 = Table('b', meta,
         Column('y', sa.Integer, sa.ForeignKey('a.x')),
         test_needs_fk=True
     )
     meta.create_all()
     try:
         m2 = MetaData(testing.db)
         a2 = Table('a', m2, include_columns=['z'], autoload=True)
         b2 = Table('b', m2, autoload=True)
         
         assert_raises(tsa.exc.NoReferencedColumnError, a2.join, b2)
     finally:
         meta.drop_all()
Esempio n. 4
0
    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):
            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
Esempio n. 5
0
    def test_basic(self):
        carrier = util.ExtensionCarrier()

        assert 'translate_row' not in carrier
        assert carrier.translate_row() is interfaces.EXT_CONTINUE
        assert 'translate_row' not in carrier

        assert_raises(AttributeError, lambda: carrier.snickysnack)

        class Partial(object):
            def __init__(self, marker):
                self.marker = marker
            def translate_row(self, row):
                return self.marker

        carrier.append(Partial('end'))
        assert 'translate_row' in carrier
        assert carrier.translate_row(None) == 'end'

        carrier.push(Partial('front'))
        assert carrier.translate_row(None) == 'front'

        assert 'populate_instance' not in carrier
        carrier.append(interfaces.MapperExtension)
        
        # Py3K
        #assert 'populate_instance' not in carrier
        # Py2K
        assert 'populate_instance' in carrier
        # end Py2K
        
        assert carrier.interface
        for m in carrier.interface:
            assert getattr(interfaces.MapperExtension, m)
Esempio n. 6
0
    def test_notcallable(self):
        class Point(object):
            pass
        table = self.point_map(Point)
        alias = aliased(Point)

        assert_raises(TypeError, alias)
Esempio n. 7
0
    def test_inheriting(self):
        mapper(A, a_table, properties={
                'some_dest': relationship(Dest,back_populates='many_a')
            })
        mapper(B, b_table, inherits=A, concrete=True,
               properties={
                    'some_dest': relationship(Dest, back_populates='many_b')
                })

        mapper(Dest, dest_table, properties={
                    'many_a': relationship(A,back_populates='some_dest'), 
                    'many_b': relationship(B,back_populates='some_dest')
                })
        sess = sessionmaker()()
        dest1 = Dest(name='c1')
        dest2 = Dest(name='c2')
        a1 = A(some_dest=dest1, aname='a1')
        a2 = A(some_dest=dest2, aname='a2')
        b1 = B(some_dest=dest1, bname='b1')
        b2 = B(some_dest=dest1, bname='b2')
        assert_raises(AttributeError, setattr, b1, 'aname', 'foo')
        assert_raises(AttributeError, getattr, A, 'bname')
        assert dest2.many_a == [a2]
        assert dest1.many_a == [a1]
        assert dest1.many_b == [b1, b2]
        sess.add_all([dest1, dest2])
        sess.commit()
        assert sess.query(Dest).filter(Dest.many_a.contains(a2)).one() is dest2
        assert dest2.many_a == [a2]
        assert dest1.many_a == [a1]
        assert dest1.many_b == [b1, b2]
        assert sess.query(B).filter(B.bname == 'b1').one() is b1
Esempio n. 8
0
    def test_basic(self):
        carrier = util.ExtensionCarrier()

        assert "translate_row" not in carrier
        assert carrier.translate_row() is interfaces.EXT_CONTINUE
        assert "translate_row" not in carrier

        assert_raises(AttributeError, lambda: carrier.snickysnack)

        class Partial(object):
            def __init__(self, marker):
                self.marker = marker

            def translate_row(self, row):
                return self.marker

        carrier.append(Partial("end"))
        assert "translate_row" in carrier
        assert carrier.translate_row(None) == "end"

        carrier.push(Partial("front"))
        assert carrier.translate_row(None) == "front"

        assert "populate_instance" not in carrier
        carrier.append(interfaces.MapperExtension)
        assert "populate_instance" in carrier

        assert carrier.interface
        for m in carrier.interface:
            assert getattr(interfaces.MapperExtension, m)
Esempio n. 9
0
 def test_length_deprecation(self):
     assert_raises(exc.SADeprecationWarning, Numeric, length=8)
     
     @testing.uses_deprecated(".*is deprecated for Numeric")
     def go():
         n = Numeric(length=12)
         assert n.scale == 12
     go()
     
     n = Numeric(scale=12)
     for dialect in engines.all_dialects():
         n2 = dialect.type_descriptor(n)
         eq_(n2.scale, 12, dialect.name)
         
         # test colspec generates successfully using 'scale'
         assert n2.get_col_spec()
         
         # test constructor of the dialect-specific type
         n3 = n2.__class__(scale=5)
         eq_(n3.scale, 5, dialect.name)
         
         @testing.uses_deprecated(".*is deprecated for Numeric")
         def go():
             n3 = n2.__class__(length=6)
             eq_(n3.scale, 6, dialect.name)
         go()
Esempio n. 10
0
 def test_deleted_flag(self):
     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)
Esempio n. 11
0
 def test_string_dates_raise(self):
     assert_raises(
         TypeError,
         testing.db.execute,
         select([1]).where(bindparam("date", type_=Date)),
         date=str(datetime.date(2007, 10, 30)),
     )
Esempio n. 12
0
    def test_length_deprecation(self):
        assert_raises(exc.SADeprecationWarning, Numeric, length=8)

        @testing.uses_deprecated(".*is deprecated for Numeric")
        def go():
            n = Numeric(length=12)
            assert n.scale == 12

        go()

        n = Numeric(scale=12)
        for dialect in engines.all_dialects():
            n2 = dialect.type_descriptor(n)
            eq_(n2.scale, 12, dialect.name)

            # test colspec generates successfully using 'scale'
            assert n2.get_col_spec()

            # test constructor of the dialect-specific type
            n3 = n2.__class__(scale=5)
            eq_(n3.scale, 5, dialect.name)

            @testing.uses_deprecated(".*is deprecated for Numeric")
            def go():
                n3 = n2.__class__(length=6)
                eq_(n3.scale, 6, dialect.name)

            go()
Esempio n. 13
0
    def test_versioncheck(self):
        """query.with_lockmode performs a 'version check' on an already loaded instance"""

        s1 = create_session(autocommit=False)

        mapper(Foo, version_table, version_id_col=version_table.c.version_id)
        f1s1 = Foo(value='f1 value')
        s1.add(f1s1)
        s1.commit()

        s2 = create_session(autocommit=False)
        f1s2 = s2.query(Foo).get(f1s1.id)
        f1s2.value = 'f1 new value'
        s2.commit()

        # load, version is wrong
        assert_raises(sa.orm.exc.ConcurrentModificationError,
                      s1.query(Foo).with_lockmode('read').get, f1s1.id)

        # reload it - this expires the old version first
        s1.refresh(f1s1, lockmode='read')

        # now assert version OK
        s1.query(Foo).with_lockmode('read').get(f1s1.id)

        # assert brand new load is OK too
        s1.close()
        s1.query(Foo).with_lockmode('read').get(f1s1.id)
Esempio n. 14
0
    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):
            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
Esempio n. 15
0
    def test_nonreflected_fk_raises(self):
        """test that a NoReferencedColumnError is raised when reflecting
        a table with an FK to another table which has not included the target
        column in its reflection.
        
        """
        meta = MetaData(testing.db)
        a1 = Table('a',
                   meta,
                   Column('x', sa.Integer, primary_key=True),
                   Column('z', sa.Integer),
                   test_needs_fk=True)
        b1 = Table('b',
                   meta,
                   Column('y', sa.Integer, sa.ForeignKey('a.x')),
                   test_needs_fk=True)
        meta.create_all()
        try:
            m2 = MetaData(testing.db)
            a2 = Table('a', m2, include_columns=['z'], autoload=True)
            b2 = Table('b', m2, autoload=True)

            assert_raises(tsa.exc.NoReferencedColumnError, a2.join, b2)
        finally:
            meta.drop_all()
Esempio n. 16
0
    def test_rollback_recover(self):
        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_mapped_managerattr(self):
        t = Table('t', MetaData(),
                  Column('id', Integer, primary_key=True),
                  Column(attributes.ClassManager.MANAGER_ATTR, Integer))

        class T(object): pass
        assert_raises(KeyError, mapper, T, t)
Esempio n. 18
0
    def test_pk_violation_with_savepoint(self):
        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()
        assert s.query(User).all() == [
            User(id=1,
                 name='edward',
                 addresses=[Address(email_address='foober')])
        ]
Esempio n. 19
0
    def test_single_parent_raise(self):

        sess = create_session()
        
        y = T2(data='T2a')
        x = T1(data='T1a', t2=y)
        assert_raises(sa_exc.InvalidRequestError, T1, data='T1b', t2=y)
Esempio n. 20
0
 def test_inheriting(self):
     mapper(A, a_table, properties={
             'some_dest': relationship(Dest,back_populates='many_a')
         })
     mapper(B, b_table, inherits=A, concrete=True,
            properties={
                 'some_dest': relationship(Dest, back_populates='many_b')
             })
                 
     mapper(Dest, dest_table, properties={
                 'many_a': relationship(A,back_populates='some_dest'), 
                 'many_b': relationship(B,back_populates='some_dest')
             })
     sess = sessionmaker()()
     dest1 = Dest(name='c1')
     dest2 = Dest(name='c2')
     a1 = A(some_dest=dest1, aname='a1')
     a2 = A(some_dest=dest2, aname='a2')
     b1 = B(some_dest=dest1, bname='b1')
     b2 = B(some_dest=dest1, bname='b2')
     assert_raises(AttributeError, setattr, b1, 'aname', 'foo')
     assert_raises(AttributeError, getattr, A, 'bname')
     assert dest2.many_a == [a2]
     assert dest1.many_a == [a1]
     assert dest1.many_b == [b1, b2]
     sess.add_all([dest1, dest2])
     sess.commit()
     assert sess.query(Dest).filter(Dest.many_a.contains(a2)).one() is dest2
     assert dest2.many_a == [a2]
     assert dest1.many_a == [a1]
     assert dest1.many_b == [b1, b2]
     assert sess.query(B).filter(B.bname == 'b1').one() is b1
Esempio n. 21
0
 def test_empty_insert_pk2(self):
     assert_raises(
         exc.DBAPIError,
         self._test_empty_insert,
         Table('b', MetaData(testing.db),
               Column('x', Integer, primary_key=True),
               Column('y', Integer, primary_key=True)))
Esempio n. 22
0
    def test_notsane_warning(self):
        # clear the warning module's ignores to force the SAWarning this
        # test relies on to be emitted (it may have already been ignored
        # forever by other VersioningTests)
        try:
            del __warningregistry__
        except NameError:
            pass

        save = testing.db.dialect.supports_sane_rowcount
        testing.db.dialect.supports_sane_rowcount = False
        try:
            mapper(Foo, version_table, 
                    version_id_col=version_table.c.version_id)

            s1 = create_session(autocommit=False)
            f1 = Foo(value='f1')
            f2 = Foo(value='f2')
            s1.add_all((f1, f2))
            s1.commit()

            f1.value='f1rev2'
            assert_raises(sa.exc.SAWarning, s1.commit)
        finally:
            testing.db.dialect.supports_sane_rowcount = save
Esempio n. 23
0
    def test_noninherited_warning(self):
        mapper(A, a_table, properties={
            'some_c':relation(C)
        })
        mapper(B, b_table,inherits=A, concrete=True)
        mapper(C, c_table)

        b = B()
        c = C()
        assert_raises(AttributeError, setattr, b, 'some_c', c)

        clear_mappers()
        mapper(A, a_table, properties={
            'a_id':a_table.c.id
        })
        mapper(B, b_table,inherits=A, concrete=True)
        mapper(C, c_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(C, c_table)
Esempio n. 24
0
 def test_double_fk_usage_raises(self):
     f = ForeignKey('b.id')
     
     assert_raises(exc.InvalidRequestError, Table, "a", metadata,
         Column('x', Integer, f),
         Column('y', Integer, f)
     )
Esempio n. 25
0
    def test_versioncheck(self):
        """query.with_lockmode performs a 'version check' on an already loaded instance"""

        s1 = create_session(autocommit=False)

        mapper(Foo, version_table, version_id_col=version_table.c.version_id)
        f1s1 = Foo(value='f1 value')
        s1.add(f1s1)
        s1.commit()

        s2 = create_session(autocommit=False)
        f1s2 = s2.query(Foo).get(f1s1.id)
        f1s2.value='f1 new value'
        s2.commit()

        # load, version is wrong
        assert_raises(
                sa.orm.exc.ConcurrentModificationError, 
                s1.query(Foo).with_lockmode('read').get, f1s1.id
            )

        # reload it - this expires the old version first
        s1.refresh(f1s1, lockmode='read')
        
        # now assert version OK
        s1.query(Foo).with_lockmode('read').get(f1s1.id)

        # assert brand new load is OK too
        s1.close()
        s1.query(Foo).with_lockmode('read').get(f1s1.id)
Esempio n. 26
0
    def test_unknown_types(self):
        meta = MetaData(testing.db)
        t = Table("test", meta,
            Column('foo', sa.DateTime))

        import sys
        dialect_module = sys.modules[testing.db.dialect.__module__]

        # we're relying on the presence of "ischema_names" in the
        # dialect module, else we can't test this.  we need to be able
        # to get the dialect to not be aware of some type so we temporarily
        # monkeypatch.  not sure what a better way for this could be,
        # except for an established dialect hook or dialect-specific tests
        if not hasattr(dialect_module, 'ischema_names'):
            return

        ischema_names = dialect_module.ischema_names
        t.create()
        dialect_module.ischema_names = {}
        try:
            m2 = MetaData(testing.db)
            assert_raises(tsa.exc.SAWarning, Table, "test", m2, autoload=True)

            @testing.emits_warning('Did not recognize type')
            def warns():
                m3 = MetaData(testing.db)
                t3 = Table("test", m3, autoload=True)
                assert t3.c.foo.type.__class__ == sa.types.NullType

        finally:
            dialect_module.ischema_names = ischema_names
            t.drop()
Esempio n. 27
0
    def test_noeq_deprecation(self):
        p1 = PickleType()

        assert_raises(DeprecationWarning, p1.compare_values,
                      pickleable.BarWithoutCompare(1, 2),
                      pickleable.BarWithoutCompare(1, 2))

        assert_raises(DeprecationWarning, p1.compare_values,
                      pickleable.OldSchoolWithoutCompare(1, 2),
                      pickleable.OldSchoolWithoutCompare(1, 2))

        @testing.uses_deprecated()
        def go():
            # test actual dumps comparison
            assert p1.compare_values(pickleable.BarWithoutCompare(1, 2),
                                     pickleable.BarWithoutCompare(1, 2))
            assert p1.compare_values(pickleable.OldSchoolWithoutCompare(1, 2),
                                     pickleable.OldSchoolWithoutCompare(1, 2))

        go()

        assert p1.compare_values({1: 2, 3: 4}, {3: 4, 1: 2})

        p2 = PickleType(mutable=False)
        assert not p2.compare_values(pickleable.BarWithoutCompare(1, 2),
                                     pickleable.BarWithoutCompare(1, 2))
        assert not p2.compare_values(pickleable.OldSchoolWithoutCompare(1, 2),
                                     pickleable.OldSchoolWithoutCompare(1, 2))
Esempio n. 28
0
    def test_rollback_recover(self):
        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()
Esempio n. 29
0
    def test_pk_violation(self):
        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.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
        assert u1.name == 'ed'
        assert a1.email_address == 'foo'
        u1.name = 'edward'
        a1.email_address = 'foober'
        s.commit()
        eq_(
            s.query(User).all(),
            [User(id=1, name='edward', addresses=[Address(email_address='foober')])]
        )
Esempio n. 30
0
    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)
Esempio n. 31
0
    def test_unknown_types(self):
        meta = MetaData(testing.db)
        t = Table("test", meta, Column('foo', sa.DateTime))

        import sys
        dialect_module = sys.modules[testing.db.dialect.__module__]

        # we're relying on the presence of "ischema_names" in the
        # dialect module, else we can't test this.  we need to be able
        # to get the dialect to not be aware of some type so we temporarily
        # monkeypatch.  not sure what a better way for this could be,
        # except for an established dialect hook or dialect-specific tests
        if not hasattr(dialect_module, 'ischema_names'):
            return

        ischema_names = dialect_module.ischema_names
        t.create()
        dialect_module.ischema_names = {}
        try:
            m2 = MetaData(testing.db)
            assert_raises(tsa.exc.SAWarning, Table, "test", m2, autoload=True)

            @testing.emits_warning('Did not recognize type')
            def warns():
                m3 = MetaData(testing.db)
                t3 = Table("test", m3, autoload=True)
                assert t3.c.foo.type.__class__ == sa.types.NullType

        finally:
            dialect_module.ischema_names = ischema_names
            t.drop()
Esempio n. 32
0
 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")
Esempio n. 33
0
    def test_noninherited_warning(self):
        mapper(A, a_table, properties={
            'some_c':relation(C)
        })
        mapper(B, b_table,inherits=A, concrete=True)
        mapper(C, c_table)

        b = B()
        c = C()
        assert_raises(AttributeError, setattr, b, 'some_c', c)

        clear_mappers()
        mapper(A, a_table, properties={
            'a_id':a_table.c.id
        })
        mapper(B, b_table,inherits=A, concrete=True)
        mapper(C, c_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(C, c_table)
Esempio n. 34
0
    def test_notsane_warning(self):
        # clear the warning module's ignores to force the SAWarning this
        # test relies on to be emitted (it may have already been ignored
        # forever by other VersioningTests)
        try:
            del __warningregistry__
        except NameError:
            pass

        save = testing.db.dialect.supports_sane_rowcount
        testing.db.dialect.supports_sane_rowcount = False
        try:
            mapper(Foo,
                   version_table,
                   version_id_col=version_table.c.version_id)

            s1 = create_session(autocommit=False)
            f1 = Foo(value='f1')
            f2 = Foo(value='f2')
            s1.add_all((f1, f2))
            s1.commit()

            f1.value = 'f1rev2'
            assert_raises(sa.exc.SAWarning, s1.commit)
        finally:
            testing.db.dialect.supports_sane_rowcount = save
Esempio n. 35
0
 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)))
Esempio n. 36
0
    def test_default_constructor_state_not_shared(self):
        scope = scoped_session(sa.orm.sessionmaker())

        class A(object):
            pass
        class B(object):
            def __init__(self):
                pass

        scope.mapper(A, table1)
        scope.mapper(B, table2)

        A(foo='bar')
        assert_raises(TypeError, B, foo='bar')

        scope = scoped_session(sa.orm.sessionmaker())

        class C(object):
            def __init__(self):
                pass
        class D(object):
            pass

        scope.mapper(C, table1)
        scope.mapper(D, table2)

        assert_raises(TypeError, C, foo='bar')
        D(foo='bar')
Esempio n. 37
0
    def test_basic(self):
        carrier = util.ExtensionCarrier()

        assert 'translate_row' not in carrier
        assert carrier.translate_row() is interfaces.EXT_CONTINUE
        assert 'translate_row' not in carrier

        assert_raises(AttributeError, lambda: carrier.snickysnack)

        class Partial(object):
            def __init__(self, marker):
                self.marker = marker

            def translate_row(self, row):
                return self.marker

        carrier.append(Partial('end'))
        assert 'translate_row' in carrier
        assert carrier.translate_row(None) == 'end'

        carrier.push(Partial('front'))
        assert carrier.translate_row(None) == 'front'

        assert 'populate_instance' not in carrier
        carrier.append(interfaces.MapperExtension)

        # Py3K
        #assert 'populate_instance' not in carrier
        # Py2K
        assert 'populate_instance' in carrier
        # end Py2K

        assert carrier.interface
        for m in carrier.interface:
            assert getattr(interfaces.MapperExtension, m)
Esempio n. 38
0
    def test_no_rowcount_on_selects_inserts(self):
        """assert that rowcount is only called on deletes and updates.

        This because cursor.rowcount can be expensive on some dialects
        such as Firebird.

        """

        engine = engines.testing_engine()
        metadata.bind = engine

        t = Table('t1', metadata, Column('data', String(10)))
        metadata.create_all()

        class BreakRowcountMixin(object):
            @property
            def rowcount(self):
                assert False

        execution_ctx_cls = engine.dialect.execution_ctx_cls
        engine.dialect.execution_ctx_cls = type(
            "FakeCtx", (BreakRowcountMixin, execution_ctx_cls), {})

        try:
            r = t.insert().execute({'data': 'd1'}, {'data': 'd2'},
                                   {'data': 'd3'})
            eq_(t.select().execute().fetchall(), [('d1', ), ('d2', ),
                                                  ('d3', )])
            assert_raises(AssertionError, t.update().execute, {'data': 'd4'})
            assert_raises(AssertionError, t.delete().execute)
        finally:
            engine.dialect.execution_ctx_cls = execution_ctx_cls
Esempio n. 39
0
    def test_child_row_switch_two(self):
        Session = sessionmaker()
        
        sess1 = Session()
        sess1.add(P(id=1, data='P version 1'))
        sess1.commit()
        sess1.close()
        
        p1 = sess1.query(P).first()

        sess2 = Session()
        p2 = sess2.query(P).first()
        
        sess1.delete(p1)
        sess1.commit()
        
        sess1.add(P(id='P1', data='P version 2'))
        sess1.commit()
        
        p2.data = 'P overwritten by concurrent tx'
        assert_raises(
            orm.exc.ConcurrentModificationError,
            sess2.commit
        )
        
        
        
        
        
Esempio n. 40
0
    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
        )
Esempio n. 41
0
    def test_default_constructor_state_not_shared(self):
        scope = scoped_session(sa.orm.sessionmaker())

        class A(object):
            pass

        class B(object):
            def __init__(self):
                pass

        scope.mapper(A, table1)
        scope.mapper(B, table2)

        A(foo='bar')
        assert_raises(TypeError, B, foo='bar')

        scope = scoped_session(sa.orm.sessionmaker())

        class C(object):
            def __init__(self):
                pass

        class D(object):
            pass

        scope.mapper(C, table1)
        scope.mapper(D, table2)

        assert_raises(TypeError, C, foo='bar')
        D(foo='bar')
Esempio n. 42
0
    def test_single_parent_backref(self):
        """test that setting m2m via a uselist=False backref bypasses the single_parent raise"""

        mapper(A,
               a,
               properties={
                   'bs':
                   relation(B,
                            secondary=atob,
                            cascade="all, delete-orphan",
                            single_parent=True,
                            backref=backref('a', uselist=False))
               })
        mapper(B, b)

        sess = create_session()
        b1 = B(data='b1')
        a1 = A(data='a1', bs=[b1])

        assert_raises(sa_exc.InvalidRequestError, A, data='a2', bs=[b1])

        a2 = A(data='a2')
        b1.a = a2
        assert b1 not in a1.bs
        assert b1 in a2.bs
Esempio n. 43
0
    def test_single_parent_raise(self):

        sess = create_session()

        y = T2(data='T2a')
        x = T1(data='T1a', t2=y)
        assert_raises(sa_exc.InvalidRequestError, T1, data='T1b', t2=y)
Esempio n. 44
0
 def test_pending_raises(self):
     # 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'])
Esempio n. 45
0
    def test_no_session(self):
        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')
Esempio n. 46
0
 def test_pending_raises(self):
     # 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'])
Esempio n. 47
0
    def test_mapped_managerattr(self):
        t = Table('t', MetaData(), Column('id', Integer, primary_key=True),
                  Column(attributes.ClassManager.MANAGER_ATTR, Integer))

        class T(object):
            pass

        assert_raises(KeyError, mapper, T, t)
Esempio n. 48
0
    def test_uselist_false_warning(self):
        """test that multiple rows received by a uselist=False raises a warning."""

        mapper(User, users, properties={"order": relation(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")
Esempio n. 49
0
    def test_no_session(self):
        mapper(User, users)
        sess = create_session()
        u = sess.query(User).get(7)

        sess.expire(u, attribute_names=['name'])
        sess.expunge(u)
        assert_raises(sa.exc.UnboundExecutionError, getattr, u, 'name')
Esempio n. 50
0
 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)))
Esempio n. 51
0
    def test_no_session(self):
        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')
Esempio n. 52
0
    def test_no_session(self):
        mapper(User, users)
        sess = create_session()
        u = sess.query(User).get(7)

        sess.expire(u, attribute_names=['name'])
        sess.expunge(u)
        assert_raises(sa.exc.UnboundExecutionError, getattr, u, 'name')
Esempio n. 53
0
    def test_needs_parent(self):
        """test the error raised when parent object is not bound."""

        mapper(User, users, properties={"addresses": relation(mapper(Address, addresses), lazy=True)})
        sess = create_session()
        q = sess.query(User)
        u = q.filter(users.c.id == 7).first()
        sess.expunge(u)
        assert_raises(orm_exc.DetachedInstanceError, getattr, u, "addresses")
Esempio n. 54
0
 def test_single_parent_raise(self):
     a1 = Address(email_address='some address')
     u1 = User(name='u1', address=a1)
     assert_raises(sa_exc.InvalidRequestError, Address,
                   email_address='asd', user=u1)
     a2 = Address(email_address='asd')
     u1.address = a2
     assert u1.address is not a1
     assert a1.user is None
Esempio n. 55
0
    def test_uselist_false_warning(self):
        """test that multiple rows received by a uselist=False raises a warning."""

        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')
Esempio n. 56
0
 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_oracle_has_no_on_update_cascade(self):
     bar = Table('bar', metadata, Column('id', Integer,
                 primary_key=True), Column('foo_id', Integer,
                 ForeignKey('foo.id', onupdate='CASCADE')))
     assert_raises(exc.SAWarning, bar.create)
     bat = Table('bat', metadata, Column('id', Integer,
                 primary_key=True), Column('foo_id', Integer),
                 ForeignKeyConstraint(['foo_id'], ['foo.id'],
                 onupdate='CASCADE'))
     assert_raises(exc.SAWarning, bat.create)
Esempio n. 58
0
    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(LookupError, table.append_ddl_listener, 'blah', fn)

        metadata.append_ddl_listener('before-create', fn)
        assert_raises(LookupError, metadata.append_ddl_listener, 'blah', fn)
    def test_uselist_false_warning(self):
        """test that multiple rows received by a 
        uselist=False raises a warning."""

        mapper(User,
               users,
               properties={'order': relationship(Order, uselist=False)})
        mapper(Order, orders)
        s = create_session()
        assert_raises(sa.exc.SAWarning,
                      s.query(User).options(subqueryload(User.order)).all)