Python sqlalchemy.testing.db() Examples

The following are 30 code examples of sqlalchemy.testing.db(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.testing , or try the search function .
Example #1
Source File: test_run_transaction.py    From sqlalchemy-cockroachdb with Apache License 2.0 6 votes vote down vote up
def test_run_transaction(self):
        def callback(barrier):
            Session = sessionmaker(testing.db)

            def txn_body(session):
                accounts = list(session.query(Account)
                                .filter(Account.acct.in_((1, 2)))
                                .order_by(Account.acct))
                barrier()
                if accounts[0].balance > accounts[1].balance:
                    accounts[0].balance -= 100
                    accounts[1].balance += 100
                else:
                    accounts[0].balance += 100
                    accounts[1].balance -= 100
            run_transaction(Session, txn_body)
        self.run_parallel_transactions(callback) 
Example #2
Source File: test_reflection.py    From planespotter with MIT License 6 votes vote down vote up
def test_get_table_names(self):
        tablenames = [
            t for t in inspect(testing.db).get_table_names()
            if t.lower() in ("t1", "t2")]

        eq_(tablenames[0].upper(), tablenames[0].lower())
        eq_(tablenames[1].upper(), tablenames[1].lower()) 
Example #3
Source File: test_json.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def setup_method(self, method):
        if not testing.db.dialect._has_native_json:
            return
        meta.create_all(testing.db)
        self.sessionmaker = sessionmaker(testing.db)
        session = self.sessionmaker()
        session.add(JSONModel(id=1,
                              jsonb_data={'a': 1},
                              json_data={'b': 2},
                              base_json_data={'c': 3}))
        session.add(JSONModel(id=2,
                              jsonb_data={'d': 4},
                              json_data={'e': 5},
                              base_json_data={'f': 6}))
        session.commit() 
Example #4
Source File: test_run_transaction.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def teardown_method(self, method):
        meta.drop_all(testing.db) 
Example #5
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_inspector_constructor_engine(self):
        with testing.expect_deprecated(
            r"The __init__\(\) method on Inspector is deprecated and will "
            r"be removed in a future release."
        ):
            i1 = reflection.Inspector(testing.db)

        is_(i1.bind, testing.db)
        self.check_usage(i1) 
Example #6
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_inspector_from_engine(self):
        with testing.expect_deprecated(
            r"The from_engine\(\) method on Inspector is deprecated and will "
            r"be removed in a future release."
        ):
            i1 = reflection.Inspector.from_engine(testing.db)

        is_(i1.bind, testing.db)
        self.check_usage(i1) 
Example #7
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_bind_close_conn(self):
        e = testing.db
        conn = e.connect()

        with testing.expect_deprecated_20(
            r"The Connection.connect\(\) function/method is considered",
            r"The .close\(\) method on a so-called 'branched' connection is "
            r"deprecated as of 1.4, as are 'branched' connections overall, "
            r"and will be removed in a future release.",
        ):
            with conn.connect() as c2:
                assert not c2.closed
        assert not conn.closed
        assert c2.closed 
Example #8
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_explicit_connectionless_execute(self):
        table = Table("t", self.metadata, Column("a", Integer))
        table.create(testing.db)

        stmt = table.insert().values(a=1)
        with testing.expect_deprecated_20(
            r"The Engine.execute\(\) function/method is considered legacy",
        ):
            testing.db.execute(stmt)

        stmt = select([table])
        with testing.expect_deprecated_20(
            r"The Engine.execute\(\) function/method is considered legacy",
        ):
            eq_(testing.db.execute(stmt).fetchall(), [(1,)]) 
Example #9
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_implicit_execute(self):
        table = Table("t", self.metadata, Column("a", Integer))
        table.create(testing.db)

        stmt = table.insert().values(a=1)
        with testing.expect_deprecated_20(
            r"The Executable.execute\(\) function/method is considered legacy",
        ):
            stmt.execute()

        stmt = select([table])
        with testing.expect_deprecated_20(
            r"The Executable.execute\(\) function/method is considered legacy",
        ):
            eq_(stmt.execute().fetchall(), [(1,)]) 
Example #10
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def setup_class(cls):
        metadata = MetaData()
        cls.users = Table(
            "query_users",
            metadata,
            Column("user_id", Integer, primary_key=True),
            Column("user_name", String(20)),
            test_needs_acid=True,
        )
        cls.users.create(testing.db) 
Example #11
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def teardown_class(cls):
        cls.users.drop(testing.db) 
Example #12
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_transaction_container(self):
        users = self.users

        def go(conn, table, data):
            for d in data:
                conn.execute(table.insert(), d)

        with testing.expect_deprecated(
            r"The Engine.transaction\(\) method is deprecated"
        ):
            testing.db.transaction(
                go, users, [dict(user_id=1, user_name="user1")]
            )

        with testing.db.connect() as conn:
            eq_(conn.execute(users.select()).fetchall(), [(1, "user1")])
        with testing.expect_deprecated(
            r"The Engine.transaction\(\) method is deprecated"
        ):
            assert_raises(
                tsa.exc.DBAPIError,
                testing.db.transaction,
                go,
                users,
                [
                    {"user_id": 2, "user_name": "user2"},
                    {"user_id": 1, "user_name": "user3"},
                ],
            )
        with testing.db.connect() as conn:
            eq_(conn.execute(users.select()).fetchall(), [(1, "user1")]) 
Example #13
Source File: plugin_base.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _do_skips(cls):
    reasons = []
    all_configs = _possible_configs_for_cls(cls, reasons)

    if getattr(cls, "__skip_if__", False):
        for c in getattr(cls, "__skip_if__"):
            if c():
                config.skip_test(
                    "'%s' skipped by %s" % (cls.__name__, c.__name__)
                )

    if not all_configs:
        msg = "'%s' unsupported on any DB implementation %s%s" % (
            cls.__name__,
            ", ".join(
                "'%s(%s)+%s'"
                % (
                    config_obj.db.name,
                    ".".join(
                        str(dig)
                        for dig in exclusions._server_version(config_obj.db)
                    ),
                    config_obj.db.driver,
                )
                for config_obj in config.Config.all_configs()
            ),
            ", ".join(reasons),
        )
        config.skip_test(msg)
    elif hasattr(cls, "__prefer_backends__"):
        non_preferred = set()
        spec = exclusions.db_spec(*util.to_list(cls.__prefer_backends__))
        for config_obj in all_configs:
            if not spec(config_obj):
                non_preferred.add(config_obj)
        if all_configs.difference(non_preferred):
            all_configs.difference_update(non_preferred)

    if config._current not in all_configs:
        _setup_config(all_configs.pop(), cls) 
Example #14
Source File: test_across_schema.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def test_get_columns_indexes_across_schema(self):
        if not testing.db.dialect._is_v2plus:
            return

        # get_columns and get_indexes use default db uri schema.
        # across schema table must use schema.table
        Table('users', self.meta, autoload=True, schema='public')
        Table('columns', self.meta, autoload=True, schema='information_schema') 
Example #15
Source File: test_across_schema.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def setup_method(self):
        if not testing.db.dialect._is_v2plus:
            return

        testing.db.execute("""CREATE TABLE IF NOT EXISTS users (
                                  name STRING PRIMARY KEY
                              )
                           """)
        self.meta = MetaData(testing.db, schema='public') 
Example #16
Source File: test_across_schema.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def teardown_method(self, method):
        if not testing.db.dialect._is_v2plus:
            return
        testing.db.execute("DROP TABLE IF EXISTS users") 
Example #17
Source File: test_json.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def teardown_method(self, method):
        if not testing.db.dialect._has_native_json:
            return
        meta.drop_all(testing.db) 
Example #18
Source File: test_across_schema.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def test_returning_clause(self):
        if not testing.db.dialect._is_v2plus:
            return

        # TODO(bdarnell): remove this when cockroachdb/cockroach#17008 is fixed.
        # across schema returning is schema.table.id but cockroachdb not support.
        table = Table('users', self.meta, autoload=True, schema='public')
        table.insert().values(dict(name='John')).returning(table.c.name).execute() 
Example #19
Source File: test_json.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def test_json(self):
        if not testing.db.dialect._has_native_json:
            return
        result = []
        query = select([json_table.c.jsonb_data,
                        json_table.c.json_data,
                        json_table.c.base_json_data])
        for row in testing.db.execute(query):
            result.append((row.jsonb_data, row.json_data, row.base_json_data))
        assert result == [({'a': 1}, {'b': 2}, {'c': 3}),
                          ({'d': 4}, {'e': 5}, {'f': 6})] 
Example #20
Source File: test_json.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def teardown_method(self, method):
        if not testing.db.dialect._has_native_json:
            return
        meta.drop_all(testing.db) 
Example #21
Source File: test_json.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def setup_method(self, method):
        if not testing.db.dialect._has_native_json:
            return
        meta.create_all(testing.db)
        testing.db.execute(
            json_table.insert(),
            [dict(id=1,
                  jsonb_data={'a': 1},
                  json_data={'b': 2},
                  base_json_data={'c': 3}),
             dict(id=2,
                  jsonb_data={'d': 4},
                  json_data={'e': 5},
                  base_json_data={'f': 6})]) 
Example #22
Source File: plugin_base.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def before_test(test, test_module_name, test_class, test_name):

    # like a nose id, e.g.:
    # "tests.aaa_profiling.test_compiler.CompileTest.test_update_whereclause"
    name = test_class.__name__

    suffix = "_%s_%s" % (config.db.name, config.db.driver)
    if name.endswith(suffix):
        name = name[0:-(len(suffix))]

    id_ = "%s.%s.%s" % (test_module_name, name, test_name)

    warnings.resetwarnings()
    profiling._current_test = id_ 
Example #23
Source File: plugin_base.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def stop_test_class(cls):
    #from sqlalchemy import inspect
    #assert not inspect(testing.db).get_table_names()
    engines.testing_reaper._stop_test_ctx()
    if not options.low_connections:
        assertions.global_cleanup_assertions()
    _restore_engine() 
Example #24
Source File: plugin_base.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def generate_sub_tests(cls, module):
    if getattr(cls, '__backend__', False):
        for cfg in _possible_configs_for_cls(cls):
            name = "%s_%s_%s" % (cls.__name__, cfg.db.name, cfg.db.driver)
            subcls = type(
                name,
                (cls, ),
                {
                    "__only_on__": ("%s+%s" % (cfg.db.name, cfg.db.driver)),
                }
            )
            setattr(module, name, subcls)
            yield subcls
    else:
        yield cls 
Example #25
Source File: plugin_base.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _engine_uri(options, file_config):
    from sqlalchemy.testing import engines, config
    from sqlalchemy import testing

    if options.dburi:
        db_urls = list(options.dburi)
    else:
        db_urls = []

    if options.db:
        for db_token in options.db:
            for db in re.split(r'[,\s]+', db_token):
                if db not in file_config.options('db'):
                    raise RuntimeError(
                        "Unknown URI specifier '%s'.  "
                        "Specify --dbs for known uris."
                        % db)
                else:
                    db_urls.append(file_config.get('db', db))

    if not db_urls:
        db_urls.append(file_config.get('db', 'default'))

    for db_url in db_urls:
        eng = engines.testing_engine(db_url, db_opts)
        eng.connect().close()
        config.Config.register(eng, db_opts, options, file_config, testing)

    config.db_opts = db_opts 
Example #26
Source File: test_reflection.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def test_get_default_schema_name(self):
        insp = inspect(testing.db)
        eq_(insp.default_schema_name, testing.db.dialect.default_schema_name) 
Example #27
Source File: test_reflection.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def test_get_schema_names(self):
        insp = inspect(testing.db)

        self.assert_('test_schema' in insp.get_schema_names()) 
Example #28
Source File: test_reflection.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def test_has_table(self):
        with config.db.begin() as conn:
            assert config.db.dialect.has_table(conn, "test_table")
            assert not config.db.dialect.has_table(conn, "nonexistent_table") 
Example #29
Source File: plugin_base.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def before_test(test, test_module_name, test_class, test_name):

    # like a nose id, e.g.:
    # "test.aaa_profiling.test_compiler.CompileTest.test_update_whereclause"
    name = test_class.__name__

    suffix = "_%s_%s" % (config.db.name, config.db.driver)
    if name.endswith(suffix):
        name = name[0:-(len(suffix))]

    id_ = "%s.%s.%s" % (test_module_name, name, test_name)

    profiling._current_test = id_ 
Example #30
Source File: test_reflection.py    From jbox with MIT License 5 votes vote down vote up
def test_has_table(self):
        with config.db.begin() as conn:
            assert config.db.dialect.has_table(conn, "test_table")
            assert not config.db.dialect.has_table(conn, "nonexistent_table")