def test_owner_database_pairs(self, identifier, expected_schema,
                                  expected_owner, use_stmt):
        dialect = mssql.dialect()

        schema, owner = base._owner_plus_db(dialect, identifier)

        eq_(owner, expected_owner)
        eq_(schema, expected_schema)

        mock_connection = mock.Mock(
            dialect=dialect,
            scalar=mock.Mock(return_value="Some  Database"),
        )
        mock_lambda = mock.Mock()
        base._switch_db(schema, mock_connection, mock_lambda, "x", y="bar")
        if schema is None:
            eq_(mock_connection.mock_calls, [])
        else:
            eq_(
                mock_connection.mock_calls,
                [
                    mock.call.scalar("select db_name()"),
                    mock.call.execute(use_stmt),
                    mock.call.execute("use [Some  Database]"),
                ],
            )
        eq_(mock_lambda.mock_calls, [mock.call("x", y="bar")])
    def _join_fixture_inh_selfref_w_entity(self, **kw):
        fake_logger = mock.Mock(info=lambda *arg, **kw: None)
        prop = mock.Mock(parent=mock.Mock(),
                         mapper=mock.Mock(),
                         logger=fake_logger)
        local_selectable = self.base.join(self.sub)
        remote_selectable = self.base.join(self.sub_w_sub_rel)

        # note this test requires that "parentmapper" annotation is
        # present in the columns ahead of time

        sub_w_sub_rel__sub_id = self.sub_w_sub_rel.c.sub_id._annotate(
            {"parentmapper": prop.mapper})
        sub__id = self.sub.c.id._annotate({"parentmapper": prop.parent})
        sub_w_sub_rel__flag = self.base.c.flag._annotate(
            {"parentmapper": prop.mapper})
        return relationships.JoinCondition(
            local_selectable,
            remote_selectable,
            local_selectable,
            remote_selectable,
            primaryjoin=and_(
                sub_w_sub_rel__sub_id == sub__id,
                sub_w_sub_rel__flag == True,  # noqa
            ),
            prop=prop,
        )
Esempio n. 3
0
 def fake_isolation_level(connection):
     connection = mock.Mock(
         cursor=mock.Mock(
             return_value=mock.Mock(
                 fetchone=mock.Mock(return_value=None)
             )
         )
     )
     return real_isolation_level(connection)
Esempio n. 4
0
    def test_max_ident_122_11compat(self):
        dialect = self._dialect((12, 2, 0))

        conn = mock.Mock(execute=mock.Mock(return_value=mock.Mock(
            scalar=lambda: "11.0.0")))
        dialect.initialize(conn)
        eq_(dialect.server_version_info, (12, 2, 0))
        eq_(dialect._get_effective_compat_server_version_info(conn),
            (11, 0, 0))
        eq_(dialect.max_identifier_length, 30)
Esempio n. 5
0
 def cx_Oracle(self):
     return mock.Mock(
         NUMBER=self.cx_Oracle_NUMBER,
         STRING=self.cx_Oracle_STRING,
         FIXED_CHAR=self.cx_Oracle_FIXED_CHAR,
         CLOB=self.cx_Oracle_CLOB,
         NCLOB=self.cx_Oracle_NCLOB,
         version="7.0.1",
         __future__=mock.Mock(),
     )
Esempio n. 6
0
    def test_bulk_save_mappings_preserve_order(self):
        (User, ) = self.classes("User")

        s = Session()

        # commit some object into db
        user1 = User(name="i1")
        user2 = User(name="i2")
        s.add(user1)
        s.add(user2)
        s.commit()

        # make some changes
        user1.name = "u1"
        user3 = User(name="i3")
        s.add(user3)
        user2.name = "u2"

        objects = [user1, user3, user2]

        from sqlalchemy_1_3 import inspect

        def _bulk_save_mappings(
            mapper,
            mappings,
            isupdate,
            isstates,
            return_defaults,
            update_changed_only,
            render_nulls,
        ):
            mock_method(list(mappings), isupdate)

        mock_method = mock.Mock()
        with mock.patch.object(s, "_bulk_save_mappings", _bulk_save_mappings):
            s.bulk_save_objects(objects)
            eq_(
                mock_method.mock_calls,
                [
                    mock.call([inspect(user1)], True),
                    mock.call([inspect(user3)], False),
                    mock.call([inspect(user2)], True),
                ],
            )

        mock_method = mock.Mock()
        with mock.patch.object(s, "_bulk_save_mappings", _bulk_save_mappings):
            s.bulk_save_objects(objects, preserve_order=False)
            eq_(
                mock_method.mock_calls,
                [
                    mock.call([inspect(user3)], False),
                    mock.call([inspect(user1), inspect(user2)], True),
                ],
            )
    def test_owner_database_pairs_dont_use_for_same_db(self):
        dialect = mssql.dialect()

        identifier = "my_db.some_schema"
        schema, owner = base._owner_plus_db(dialect, identifier)

        mock_connection = mock.Mock(dialect=dialect,
                                    scalar=mock.Mock(return_value="my_db"))
        mock_lambda = mock.Mock()
        base._switch_db(schema, mock_connection, mock_lambda, "x", y="bar")
        eq_(mock_connection.mock_calls, [mock.call.scalar("select db_name()")])
        eq_(mock_lambda.mock_calls, [mock.call("x", y="bar")])
Esempio n. 8
0
    def test_max_ident_122(self):
        dialect = self._dialect((12, 2, 0))

        conn = mock.Mock(execute=mock.Mock(return_value=mock.Mock(
            scalar=lambda: "12.2.0")))
        with self._expect_max_ident_warning():
            dialect.initialize(conn)
        eq_(dialect.server_version_info, (12, 2, 0))
        eq_(dialect._get_effective_compat_server_version_info(conn),
            (12, 2, 0))
        eq_(
            dialect.max_identifier_length,
            oracle.OracleDialect.max_identifier_length,
        )
Esempio n. 9
0
    def test_encoding_errors_cx_oracle_py3k(
        self,
        cx_Oracle,
        cx_oracle_type,
    ):
        ignore_dialect = cx_oracle.dialect(dbapi=cx_Oracle,
                                           encoding_errors="ignore")

        ignore_outputhandler = (
            ignore_dialect._generate_connection_outputtype_handler())

        cursor = mock.Mock()
        ignore_outputhandler(cursor, "foo", cx_oracle_type, None, None, None)

        eq_(
            cursor.mock_calls,
            [
                mock.call.var(
                    mock.ANY,
                    None,
                    cursor.arraysize,
                    encodingErrors="ignore",
                )
            ],
        )
Esempio n. 10
0
 def test_invalidate_dont_call_finalizer(self):
     conn = self.db.connect()
     finalizer = mock.Mock()
     conn.connection._connection_record.finalize_callback.append(finalizer)
     conn.invalidate()
     assert conn.invalidated
     eq_(finalizer.call_count, 0)
Esempio n. 11
0
    def test_correct_for_mysql_bugs_88718_96365(self):
        dialect = mysql.dialect()

        for casing, (fkeys, ischema) in [
            (0, self._bug_88718_96365_casing_0()),
            (1, self._bug_88718_96365_casing_1()),
            (2, self._bug_88718_96365_casing_2()),
        ]:
            dialect._casing = casing
            dialect.default_schema_name = "Test"
            connection = mock.Mock(dialect=dialect,
                                   execute=lambda stmt, **params: ischema)
            dialect._correct_for_mysql_bugs_88718_96365(fkeys, connection)
            eq_(
                fkeys,
                [
                    {
                        "name": "FK_PlaylistTTrackId",
                        "constrained_columns": ["TTrackID"],
                        "referred_schema": "Test_Schema",
                        "referred_table": "Track",
                        "referred_columns": ["TrackID"],
                        "options": {},
                    },
                    {
                        "name": "FK_PlaylistTrackId",
                        "constrained_columns": ["TrackID"],
                        "referred_schema": None,
                        "referred_table": "Track",
                        "referred_columns": ["TrackID"],
                        "options": {},
                    },
                ],
            )
Esempio n. 12
0
    def test_metadata_drop_both(self):
        metadata, bind = self.metadata, self.bind
        canary = mock.Mock()

        event.listen(metadata, "before_drop", canary.before_drop)
        event.listen(metadata, "after_drop", canary.after_drop)

        metadata.create_all(bind)
        metadata.drop_all(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_drop(
                    metadata,
                    self.bind,
                    checkfirst=False,
                    tables=list(metadata.tables.values()),
                    _ddl_runner=mock.ANY,
                ),
                mock.call.after_drop(
                    metadata,
                    self.bind,
                    checkfirst=False,
                    tables=list(metadata.tables.values()),
                    _ddl_runner=mock.ANY,
                ),
            ],
        )
Esempio n. 13
0
    def test_table_create_both(self):
        table, bind = self.table, self.bind
        canary = mock.Mock()
        event.listen(table, "before_create", canary.before_create)
        event.listen(table, "after_create", canary.after_create)

        table.create(bind)
        table.drop(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_create(
                    table,
                    self.bind,
                    checkfirst=False,
                    _ddl_runner=mock.ANY,
                    _is_metadata_operation=mock.ANY,
                ),
                mock.call.after_create(
                    table,
                    self.bind,
                    checkfirst=False,
                    _ddl_runner=mock.ANY,
                    _is_metadata_operation=mock.ANY,
                ),
            ],
        )
Esempio n. 14
0
    def _test_baked_lazy_loading_relationship_flag(self, flag):
        User, Address = self._o2m_fixture(bake_queries=flag)

        sess = Session()
        u1 = sess.query(User).first()

        from sqlalchemy_1_3.orm import Query

        canary = mock.Mock()

        # I would think Mock can do this but apparently
        # it cannot (wrap / autospec don't work together)
        real_compile_context = Query._compile_context

        def _my_compile_context(*arg, **kw):
            if arg[0].column_descriptions[0]["entity"] is Address:
                canary()
            return real_compile_context(*arg, **kw)

        with mock.patch.object(Query, "_compile_context", _my_compile_context):
            u1.addresses

            sess.expire(u1)
            u1.addresses

        if flag:
            eq_(canary.call_count, 1)
        else:
            eq_(canary.call_count, 2)
Esempio n. 15
0
    def test_parameters(self, exec_type, usemethod, connection):
        collect = mock.Mock()

        @self._fixture
        def fn(context):
            collect(context.get_current_parameters())

        table = self.tables.some_table
        if exec_type in ("multivalues", "executemany"):
            parameters = [{"y": "h1"}, {"y": "h2"}]
        else:
            parameters = [{"y": "hello"}]

        if exec_type == "multivalues":
            stmt, params = table.insert().values(parameters), {}
        else:
            stmt, params = table.insert(), parameters

        connection.execute(stmt, params)
        eq_(
            collect.mock_calls,
            [mock.call({
                "y": param["y"],
                "x": None
            }) for param in parameters],
        )
Esempio n. 16
0
    def test_max_ident_122_11compat_vparam_cant_parse(self):
        dialect = self._dialect((12, 2, 0))

        def c122():
            return "12.thisiscrap.0"

        conn = mock.Mock(execute=mock.Mock(return_value=mock.Mock(
            scalar=c122)))
        with self._expect_max_ident_warning():
            dialect.initialize(conn)
        eq_(dialect.server_version_info, (12, 2, 0))
        eq_(dialect._get_effective_compat_server_version_info(conn),
            (12, 2, 0))
        eq_(
            dialect.max_identifier_length,
            oracle.OracleDialect.max_identifier_length,
        )
    def test_custom_bind(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User,
        )

        mapper(
            User,
            users,
            properties=dict(addresses=relationship(
                mapper(Address, addresses),
                lazy="select",
                primaryjoin=and_(
                    users.c.id == addresses.c.user_id,
                    users.c.name == bindparam("name"),
                ),
            )),
        )

        canary = mock.Mock()

        class MyOption(MapperOption):
            propagate_to_loaders = True

            def __init__(self, crit):
                self.crit = crit

            def process_query_conditionally(self, query):
                """process query during a lazyload"""
                canary()
                query._params = query._params.union(dict(name=self.crit))

        s = Session()
        ed = s.query(User).options(MyOption("ed")).filter_by(name="ed").one()
        eq_(
            ed.addresses,
            [
                Address(id=2, user_id=8),
                Address(id=3, user_id=8),
                Address(id=4, user_id=8),
            ],
        )
        eq_(canary.mock_calls, [mock.call()])

        fred = (s.query(User).options(
            MyOption("ed")).filter_by(name="fred").one())
        eq_(fred.addresses, [])  # fred is missing
        eq_(canary.mock_calls, [mock.call(), mock.call()])

        # the lazy query was not cached; the option is re-applied to the
        # Fred object due to populate_existing()
        fred = (s.query(User).populate_existing().options(
            MyOption("fred")).filter_by(name="fred").one())
        eq_(fred.addresses, [Address(id=5, user_id=9)])  # fred is there

        eq_(canary.mock_calls, [mock.call(), mock.call(), mock.call()])
Esempio n. 18
0
    def test_max_ident_122_11compat_vparam_raises(self):
        dialect = self._dialect((12, 2, 0))

        def c122():
            raise exc.DBAPIError("statement", None, "no such table", None,
                                 None)

        conn = mock.Mock(execute=mock.Mock(return_value=mock.Mock(
            scalar=c122)))
        with self._expect_max_ident_warning():
            dialect.initialize(conn)
        eq_(dialect.server_version_info, (12, 2, 0))
        eq_(dialect._get_effective_compat_server_version_info(conn),
            (12, 2, 0))
        eq_(
            dialect.max_identifier_length,
            oracle.OracleDialect.max_identifier_length,
        )
    def test_default_schema_name_not_interpreted_as_tokenized(self):
        dialect = mssql.dialect()
        dialect.server_version_info = base.MS_2014_VERSION

        mock_connection = mock.Mock(scalar=lambda sql: "Jonah.The.Whale")
        schema_name = dialect._get_default_schema_name(mock_connection)
        eq_(schema_name, "Jonah.The.Whale")
        eq_(
            base._owner_plus_db(dialect, schema_name),
            (None, "Jonah.The.Whale"),
        )
Esempio n. 20
0
    def test_ident_length_in_13_is_30(self):
        from sqlalchemy_1_3 import __version__

        m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", __version__)
        version = tuple(int(x) for x in m.group(1, 2, 3) if x is not None)
        if version >= (1, 4):
            length = 128
        else:
            length = 30

        eq_(oracle.OracleDialect.max_identifier_length, length)

        dialect = self._dialect((12, 2, 0))
        conn = mock.Mock(execute=mock.Mock(return_value=mock.Mock(
            scalar=lambda: "12.2.0")))
        with self._expect_max_ident_warning():
            dialect.initialize(conn)
        eq_(dialect.server_version_info, (12, 2, 0))
        eq_(dialect._get_effective_compat_server_version_info(conn),
            (12, 2, 0))
        eq_(dialect.max_identifier_length, length)
Esempio n. 21
0
    def test_serial_integer(self):
        class BITD(TypeDecorator):
            impl = Integer

            def load_dialect_impl(self, dialect):
                if dialect.name == "postgresql":
                    return BigInteger()
                else:
                    return Integer()

        for version, type_, expected in [
            (None, Integer, "SERIAL"),
            (None, BigInteger, "BIGSERIAL"),
            ((9, 1), SmallInteger, "SMALLINT"),
            ((9, 2), SmallInteger, "SMALLSERIAL"),
            (None, postgresql.INTEGER, "SERIAL"),
            (None, postgresql.BIGINT, "BIGSERIAL"),
            (
                None,
                Integer().with_variant(BigInteger(), "postgresql"),
                "BIGSERIAL",
            ),
            (
                None,
                Integer().with_variant(postgresql.BIGINT, "postgresql"),
                "BIGSERIAL",
            ),
            (
                (9, 2),
                Integer().with_variant(SmallInteger, "postgresql"),
                "SMALLSERIAL",
            ),
            (None, BITD(), "BIGSERIAL"),
        ]:
            m = MetaData()

            t = Table("t", m, Column("c", type_, primary_key=True))

            if version:
                dialect = postgresql.dialect()
                dialect._get_server_version_info = mock.Mock(
                    return_value=version
                )
                dialect.initialize(testing.db.connect())
            else:
                dialect = testing.db.dialect

            ddl_compiler = dialect.ddl_compiler(dialect, schema.CreateTable(t))
            eq_(
                ddl_compiler.get_column_specification(t.c.c),
                "c %s NOT NULL" % expected,
            )
Esempio n. 22
0
    def test_metadata_table_isolation(self):
        metadata, table = self.metadata, self.table
        table_canary = mock.Mock()
        metadata_canary = mock.Mock()

        event.listen(table, "before_create", table_canary.before_create)

        event.listen(metadata, "before_create", metadata_canary.before_create)
        self.table.create(self.bind)
        eq_(
            table_canary.mock_calls,
            [
                mock.call.before_create(
                    table,
                    self.bind,
                    checkfirst=False,
                    _ddl_runner=mock.ANY,
                    _is_metadata_operation=mock.ANY,
                )
            ],
        )
        eq_(metadata_canary.mock_calls, [])
Esempio n. 23
0
    def test_older_cx_oracle_warning(self, cx_Oracle, cx_oracle_type):
        cx_Oracle.version = "6.3"

        ignore_dialect = cx_oracle.dialect(dbapi=cx_Oracle,
                                           encoding_errors="ignore")
        ignore_outputhandler = (
            ignore_dialect._generate_connection_outputtype_handler())

        cursor = mock.Mock()

        with testing.expect_warnings(
                r"cx_oracle version \(6, 3\) does not support encodingErrors"):
            ignore_outputhandler(cursor, "foo", cx_oracle_type, None, None,
                                 None)
Esempio n. 24
0
    def test_no_encoding_errors_sqla_py2k(
        self,
        cx_Oracle,
        cx_oracle_type,
    ):
        plain_dialect = cx_oracle.dialect(dbapi=cx_Oracle)

        plain_outputhandler = (
            plain_dialect._generate_connection_outputtype_handler())

        cursor = mock.Mock()
        plain_outputhandler(cursor, "foo", cx_oracle_type, None, None, None)
        outconverter = cursor.mock_calls[0][2]["outconverter"]
        self._assert_errorhandler(outconverter, False)
Esempio n. 25
0
    def test_modified_event(self):
        canary = mock.Mock()
        event.listen(Foo.data, "modified", canary)

        f1 = Foo(data={"a": "b"})
        f1.data["a"] = "c"

        eq_(
            canary.mock_calls,
            [
                mock.call(
                    f1, attributes.Event(Foo.data.impl,
                                         attributes.OP_MODIFIED))
            ],
        )
Esempio n. 26
0
    def test_is_disconnect(
        self, arg0, message, exc_cls_name, dialect_name, is_disconnect
    ):
        class Error(Exception):
            pass

        dbapi = mock.Mock()
        dbapi.Error = Error
        dbapi.ProgrammingError = type("ProgrammingError", (Error,), {})
        dbapi.OperationalError = type("OperationalError", (Error,), {})
        dbapi.InterfaceError = type("InterfaceError", (Error,), {})
        dbapi.InternalError = type("InternalError", (Error,), {})

        dialect = getattr(mysql, dialect_name).dialect(dbapi=dbapi)

        error = getattr(dbapi, exc_cls_name)(arg0, message)
        eq_(dialect.is_disconnect(error, None, None), is_disconnect)
Esempio n. 27
0
    def test_spoiled_half_w_params(self):
        User = self.classes.User

        canary = mock.Mock()

        def fn1(s):
            canary.fn1()
            return s.query(User.id, User.name).order_by(User.id)

        def fn2(q):
            canary.fn2()
            return q.filter(User.id == bindparam("id"))

        def fn3(q):
            canary.fn3()
            return q

        bq = self.bakery(fn1)

        bq += fn2

        for x in range(3):
            bq = self.bakery(fn1)

            bq += fn2

            sess = Session(autocommit=True)
            eq_(
                bq.spoil().add_criteria(fn3)(sess).params(id=7).all(),
                [(7, "jack")],
            )

        eq_(
            canary.mock_calls,
            [
                mock.call.fn1(),
                mock.call.fn2(),
                mock.call.fn3(),
                mock.call.fn3(),
                mock.call.fn3(),
            ],
        )
Esempio n. 28
0
    def test_table_drop_after(self):
        table, bind = self.table, self.bind
        canary = mock.Mock()
        event.listen(table, "after_drop", canary.after_drop)

        table.create(bind)
        canary.state = "skipped"
        table.drop(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.after_drop(
                    table,
                    self.bind,
                    checkfirst=False,
                    _ddl_runner=mock.ANY,
                    _is_metadata_operation=mock.ANY,
                )
            ],
        )
Esempio n. 29
0
    def test_metadata_create_before(self):
        metadata, bind = self.metadata, self.bind
        canary = mock.Mock()
        event.listen(metadata, "before_create", canary.before_create)

        metadata.create_all(bind)
        metadata.drop_all(bind)
        eq_(
            canary.mock_calls,
            [
                mock.call.before_create(
                    # checkfirst is False because of the MockConnection
                    # used in the current testing strategy.
                    metadata,
                    self.bind,
                    checkfirst=False,
                    tables=list(metadata.tables.values()),
                    _ddl_runner=mock.ANY,
                )
            ],
        )
Esempio n. 30
0
    def modify_query_fixture(self):
        def set_event(bake_ok):

            event.listen(
                Query,
                "before_compile",
                _modify_query,
                retval=True,
                bake_ok=bake_ok,
            )
            return m1

        m1 = mock.Mock()

        def _modify_query(query):
            m1(query.column_descriptions[0]["entity"])
            query = query.enable_assertions(False).filter(
                literal_column("1") == 1)
            return query

        yield set_event
        event.remove(Query, "before_compile", _modify_query)