Ejemplo n.º 1
0
    def test_skip_not_describable(self):
        @event.listens_for(self.metadata, "before_drop")
        def cleanup(*arg, **kw):
            with testing.db.connect() as conn:
                conn.execute("DROP TABLE IF EXISTS test_t1")
                conn.execute("DROP TABLE IF EXISTS test_t2")
                conn.execute("DROP VIEW IF EXISTS test_v")

        with testing.db.connect() as conn:
            conn.execute("CREATE TABLE test_t1 (id INTEGER)")
            conn.execute("CREATE TABLE test_t2 (id INTEGER)")
            conn.execute("CREATE VIEW test_v AS SELECT id FROM test_t1")
            conn.execute("DROP TABLE test_t1")

            m = MetaData()
            with expect_warnings(
                    "Skipping .* Table or view named .?test_v.? could not be "
                    "reflected: .* references invalid table"):
                m.reflect(views=True, bind=conn)
            eq_(m.tables["test_t2"].name, "test_t2")

            assert_raises_message(
                exc.UnreflectableTableError,
                "references invalid table",
                Table,
                "test_v",
                MetaData(),
                autoload_with=conn,
            )
    def test_varchar_raise(self):
        for type_ in (
                String,
                VARCHAR,
                String(),
                VARCHAR(),
                Unicode,
                Unicode(),
        ):
            type_ = sqltypes.to_instance(type_)
            assert_raises_message(
                exc.CompileError,
                "VARCHAR requires a length on dialect firebird",
                type_.compile,
                dialect=firebird.dialect(),
            )

            t1 = Table("sometable", MetaData(), Column("somecolumn", type_))
            assert_raises_message(
                exc.CompileError,
                r"\(in table 'sometable', column 'somecolumn'\)\: "
                r"(?:N)?VARCHAR requires a length on dialect firebird",
                schema.CreateTable(t1).compile,
                dialect=firebird.dialect(),
            )
Ejemplo n.º 3
0
    def test_fragment_ambiguous(self):
        base = weakref.WeakValueDictionary()
        f1 = MockClass(base, "foo.bar.Foo")
        f2 = MockClass(base, "foo.alt.Foo")
        f3 = MockClass(base, "bat.alt.Foo")
        clsregistry.add_class("Foo", f1)
        clsregistry.add_class("Foo", f2)
        clsregistry.add_class("Foo", f3)
        name_resolver, resolver = clsregistry._resolver(f1, MockProp())

        gc_collect()

        assert_raises_message(
            exc.InvalidRequestError,
            'Multiple classes found for path "alt.Foo" in the registry '
            "of this declarative base. Please use a fully "
            "module-qualified path.",
            resolver("alt.Foo"),
        )

        assert_raises_message(
            exc.InvalidRequestError,
            'Multiple classes found for path "alt.Foo" in the registry '
            "of this declarative base. Please use a fully "
            "module-qualified path.",
            name_resolver("alt.Foo"),
        )
Ejemplo n.º 4
0
    def test_bound_connection(self):
        users, User = self.tables.users, self.classes.User

        mapper(User, users)
        c = testing.db.connect()
        sess = create_session(bind=c)
        sess.begin()
        transaction = sess.transaction
        u = User(name="u1")
        sess.add(u)
        sess.flush()
        assert (transaction._connection_for_bind(testing.db, None) is
                transaction._connection_for_bind(c, None) is c)

        assert_raises_message(
            sa.exc.InvalidRequestError,
            "Session already has a Connection "
            "associated",
            transaction._connection_for_bind,
            testing.db.connect(),
            None,
        )
        transaction.rollback()
        assert len(sess.query(User).all()) == 0
        sess.close()
Ejemplo n.º 5
0
    def test_server_default_absent_value(self):
        metadata = MetaData()
        table = Table(
            "sometable",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("data", String),
            Column("foo", Integer, server_default=func.foobar()),
        )

        values = [
            {
                "id": 1,
                "data": "data1",
                "foo": "plainfoo"
            },
            {
                "id": 2,
                "data": "data2"
            },
            {
                "id": 3,
                "data": "data3",
                "foo": "otherfoo"
            },
        ]

        assert_raises_message(
            exc.CompileError,
            "INSERT value for column sometable.foo is explicitly rendered "
            "as a boundparameter in the VALUES clause; a Python-side value or "
            "SQL expression is required",
            table.insert().values(values).compile,
        )
Ejemplo n.º 6
0
    def test_resolve_dupe_by_name(self):
        base = weakref.WeakValueDictionary()
        f1 = MockClass(base, "foo.bar.Foo")
        f2 = MockClass(base, "foo.alt.Foo")
        clsregistry.add_class("Foo", f1)
        clsregistry.add_class("Foo", f2)

        gc_collect()

        name_resolver, resolver = clsregistry._resolver(f1, MockProp())
        resolver = resolver("Foo")
        assert_raises_message(
            exc.InvalidRequestError,
            'Multiple classes found for path "Foo" in the '
            "registry of this declarative base. Please use a "
            "fully module-qualified path.",
            resolver,
        )

        resolver = name_resolver("Foo")
        assert_raises_message(
            exc.InvalidRequestError,
            'Multiple classes found for path "Foo" in the '
            "registry of this declarative base. Please use a "
            "fully module-qualified path.",
            resolver,
        )
Ejemplo n.º 7
0
    def test_lobs_without_convert_many_rows(self):
        engine = testing_engine(
            options=dict(auto_convert_lobs=False, arraysize=1)
        )
        result = engine.execute(
            "select id, data, bindata from z_test order by id"
        )
        results = result.fetchall()

        def go():
            eq_(
                [
                    dict(
                        id=row["id"],
                        data=row["data"].read(),
                        bindata=row["bindata"].read(),
                    )
                    for row in results
                ],
                self.data,
            )

        # this comes from cx_Oracle because these are raw
        # cx_Oracle.Variable objects
        if testing.requires.oracle5x.enabled:
            assert_raises_message(
                testing.db.dialect.dbapi.ProgrammingError,
                "LOB variable no longer valid after subsequent fetch",
                go,
            )
        else:
            go()
Ejemplo n.º 8
0
    def test_module_reg_cleanout_race(self):
        """test the race condition that a class was gc'ed as we tried
        to look it up by module name."""

        base = weakref.WeakValueDictionary()
        f1 = MockClass(base, "foo.bar.Foo")
        clsregistry.add_class("Foo", f1)
        reg = base["_sa_module_registry"]

        mod_entry = reg["foo"]["bar"]
        name_resolver, resolver = clsregistry._resolver(f1, MockProp())
        f_resolver = resolver("foo")
        del mod_entry.contents["Foo"]
        assert_raises_message(
            AttributeError,
            "Module 'bar' has no mapped classes registered "
            "under the name 'Foo'",
            lambda: f_resolver().bar.Foo,
        )

        f_resolver = name_resolver("foo")
        assert_raises_message(
            AttributeError,
            "Module 'bar' has no mapped classes registered "
            "under the name 'Foo'",
            lambda: f_resolver().bar.Foo,
        )
Ejemplo n.º 9
0
    def test_dupe_classes_name_race(self):
        """test the race condition that the class was garbage "
        "collected while being resolved from a dupe class."""
        base = weakref.WeakValueDictionary()
        f1 = MockClass(base, "foo.bar.Foo")
        f2 = MockClass(base, "foo.alt.Foo")
        clsregistry.add_class("Foo", f1)
        clsregistry.add_class("Foo", f2)

        dupe_reg = base["Foo"]
        dupe_reg.contents = [lambda: None]
        name_resolver, resolver = clsregistry._resolver(f1, MockProp())
        f_resolver = resolver("Foo")
        assert_raises_message(
            exc.InvalidRequestError,
            r"When initializing mapper some_parent, expression "
            r"'Foo' failed to locate a name \('Foo'\).",
            f_resolver,
        )

        f_resolver = name_resolver("Foo")
        assert_raises_message(
            exc.InvalidRequestError,
            r"When initializing mapper some_parent, expression "
            r"'Foo' failed to locate a name \('Foo'\).",
            f_resolver,
        )
    def test_overlapping_attribute_error(self):
        place, Transition, place_input, Place, transition = (
            self.tables.place,
            self.classes.Transition,
            self.tables.place_input,
            self.classes.Place,
            self.tables.transition,
        )

        mapper(
            Place,
            place,
            properties={
                "transitions":
                relationship(Transition,
                             secondary=place_input,
                             backref="places")
            },
        )
        mapper(
            Transition,
            transition,
            properties={
                "places":
                relationship(Place,
                             secondary=place_input,
                             backref="transitions")
            },
        )
        assert_raises_message(
            sa.exc.ArgumentError,
            "property of that name exists",
            sa.orm.configure_mappers,
        )
Ejemplo n.º 11
0
 def test_with_transaction(self):
     conn = self.engine.connect()
     trans = conn.begin()
     eq_(conn.execute(select([1])).scalar(), 1)
     assert not conn.closed
     self.engine.test_shutdown()
     _assert_invalidated(conn.execute, select([1]))
     assert not conn.closed
     assert conn.invalidated
     assert trans.is_active
     assert_raises_message(
         tsa.exc.StatementError,
         "Can't reconnect until invalid transaction is rolled back",
         conn.execute,
         select([1]),
     )
     assert trans.is_active
     assert_raises_message(
         tsa.exc.InvalidRequestError,
         "Can't reconnect until invalid transaction is rolled back",
         trans.commit,
     )
     assert trans.is_active
     trans.rollback()
     assert not trans.is_active
     assert conn.invalidated
     eq_(conn.execute(select([1])).scalar(), 1)
     assert not conn.invalidated
Ejemplo n.º 12
0
    def test_invalidate_trans(self):
        conn = self.db.connect()
        trans = conn.begin()
        self.dbapi.shutdown()

        assert_raises(tsa.exc.DBAPIError, conn.execute, select([1]))

        eq_([c.close.mock_calls for c in self.dbapi.connections], [[call()]])
        assert not conn.closed
        assert conn.invalidated
        assert trans.is_active
        assert_raises_message(
            tsa.exc.StatementError,
            "Can't reconnect until invalid transaction is rolled back",
            conn.execute,
            select([1]),
        )
        assert trans.is_active

        assert_raises_message(
            tsa.exc.InvalidRequestError,
            "Can't reconnect until invalid transaction is rolled back",
            trans.commit,
        )

        assert trans.is_active
        trans.rollback()
        assert not trans.is_active
        conn.execute(select([1]))
        assert not conn.invalidated
        eq_(
            [c.close.mock_calls for c in self.dbapi.connections],
            [[call()], []],
        )
Ejemplo n.º 13
0
    def test_reconnect_on_reentrant_plus_closewresult(self):
        conn = self.db.connect(close_with_result=True)

        self.dbapi.shutdown("rollback")

        # raises error
        with expect_warnings(
                "An exception has occurred during handling .*"
                "something broke on execute but we didn't lose the connection",
                py2konly=True,
        ):
            assert_raises_message(
                tsa.exc.DBAPIError,
                "Lost the DB connection on rollback",
                conn.execute,
                select([1]),
            )

        assert conn.closed
        assert conn.invalidated

        assert_raises_message(
            tsa.exc.StatementError,
            "This Connection is closed",
            conn.execute,
            select([1]),
        )
Ejemplo n.º 14
0
 def test_unconsumed_names_kwargs(self):
     t = table("t", column("x"), column("y"))
     assert_raises_message(
         exc.CompileError,
         "Unconsumed column names: z",
         t.insert().values(x=5, z=5).compile,
     )
Ejemplo n.º 15
0
 def test_coerce_raise(self):
     assert_raises_message(
         ValueError,
         "Attribute 'data' does not accept objects of type",
         Foo,
         data=[1, 2, 3],
     )
Ejemplo n.º 16
0
    def test_columnadapter_anonymized(self):
        """test issue #3148

        Testing the anonymization applied from the ColumnAdapter.columns
        collection, typically as used in eager loading.

        """
        exprs = [
            table1.c.myid,
            table1.c.name.label("t1name"),
            func.foo("hoho").label("x"),
        ]

        ta = table1.alias()
        adapter = sql_util.ColumnAdapter(ta, anonymize_labels=True)

        s1 = (select([adapter.columns[expr] for expr in exprs
                      ]).apply_labels().order_by("myid", "t1name", "x"))

        assert_raises_message(
            exc.CompileError,
            r"Can't resolve label reference for ORDER BY / GROUP BY / "
            "DISTINCT etc. "
            "Textual SQL "
            "expression 't1name' should be explicitly "
            r"declared as text\('t1name'\)",
            s1.compile,
        )
Ejemplo n.º 17
0
    def test_conflicting_backref_subclass(self):
        meta = MetaData()

        a = Table("a", meta, Column("id", Integer, primary_key=True))
        b = Table(
            "b",
            meta,
            Column("id", Integer, primary_key=True),
            Column("a_id", Integer, ForeignKey("a.id")),
        )

        class A(object):
            pass

        class B(object):
            pass

        class C(B):
            pass

        mapper(
            A,
            a,
            properties={
                "b": relationship(B, backref="a"),
                "c": relationship(C, backref="a"),
            },
        )
        mapper(B, b)
        mapper(C, None, inherits=B)

        assert_raises_message(sa_exc.ArgumentError, "Error creating backref",
                              configure_mappers)
 def test_time_invalid_string(self):
     assert_raises_message(
         ValueError,
         "Couldn't parse time string: '5:a'",
         self.module.str_to_time,
         "5:a",
     )
 def test_time_no_string(self):
     assert_raises_message(
         ValueError,
         "Couldn't parse time string '2012' - value is not a string",
         self.module.str_to_time,
         2012,
     )
Ejemplo n.º 20
0
 def _test_cant_insert(self, tab):
     with testing.db.connect() as conn:
         assert_raises_message(
             sa.exc.DBAPIError,
             r".*Cannot insert an explicit value into a timestamp column.",
             conn.execute,
             tab.insert().values(data="ins", rv=b"000"),
         )
Ejemplo n.º 21
0
    def test_check_disconnect_no_cursor(self):
        conn = self.db.connect()
        result = conn.execute(select([1]))
        result.cursor.close()
        conn.close()

        assert_raises_message(tsa.exc.DBAPIError, "cursor closed", list,
                              result)
Ejemplo n.º 22
0
 def test_result_processor_invalid(self):
     mssql_date_type = _MSDate()
     result_processor = mssql_date_type.result_processor(None, None)
     assert_raises_message(
         ValueError,
         "could not parse 'abc' as a date value",
         result_processor,
         "abc",
     )
Ejemplo n.º 23
0
 def test_create_drop_err_metadata(self):
     metadata = MetaData()
     Table("test_table", metadata, Column("foo", Integer))
     for meth in [metadata.create_all, metadata.drop_all]:
         assert_raises_message(
             exc.UnboundExecutionError,
             "MetaData object is not bound to an Engine or Connection.",
             meth,
         )
Ejemplo n.º 24
0
 def test_missing_bind_kw(self):
     assert_raises_message(
         exc.ArgumentError,
         r"This text\(\) construct doesn't define "
         r"a bound parameter named 'bar'",
         text(":foo").bindparams,
         foo=5,
         bar=7,
     )
Ejemplo n.º 25
0
 def test_bindparam_quote_raise_on_expanding(self):
     assert_raises_message(
         exc.CompileError,
         "Can't use expanding feature with parameter name 'uid' on "
         "Oracle; it requires quoting which is not supported in this "
         "context",
         bindparam("uid", expanding=True).compile,
         dialect=cx_oracle.dialect(),
     )
Ejemplo n.º 26
0
 def test_missing_bind_posn(self):
     assert_raises_message(
         exc.ArgumentError,
         r"This text\(\) construct doesn't define "
         r"a bound parameter named 'bar'",
         text(":foo").bindparams,
         bindparam("foo", value=5),
         bindparam("bar", value=7),
     )
Ejemplo n.º 27
0
 def _assert_non_simple_warning(self, fn):
     assert_raises_message(
         exc.SAWarning,
         "Non-simple column elements in "
         "primary join condition for property "
         r"None - consider using remote\(\) "
         "annotations to mark the remote side.",
         fn,
     )
Ejemplo n.º 28
0
 def test_update_preserve_order_reqs_listtups(self):
     table1 = self.tables.mytable
     testing.assert_raises_message(
         ValueError,
         r"When preserve_parameter_order is True, values\(\) "
         r"only accepts a list of 2-tuples",
         table1.update(preserve_parameter_order=True).values,
         {"description": "foo", "name": "bar"},
     )
Ejemplo n.º 29
0
    def test_unconsumed_names_kwargs_w_keys(self):
        t = table("t", column("x"), column("y"))

        assert_raises_message(
            exc.CompileError,
            "Unconsumed column names: j",
            t.update().values(x=5, j=7).compile,
            column_keys=["j"],
        )
Ejemplo n.º 30
0
 def _test(self, fn, arg, offending_clause):
     assert_raises_message(
         exc.ArgumentError,
         r"Textual (?:SQL|column|SQL FROM) expression %(stmt)r should be "
         r"explicitly declared (?:with|as) text\(%(stmt)r\)" %
         {"stmt": util.ellipses_string(offending_clause)},
         fn,
         arg,
     )