def test_noerr_transaction_opened_externally(self):
        a, b, c = self._opened_transaction_fixture()

        env_file_fixture("""
from sqlalchemy import engine_from_config, pool

def run_migrations_online():
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

    with connectable.connect() as connection:
        with connection.begin() as real_trans:
            context.configure(
                connection=connection,
                transactional_ddl=False,
                transaction_per_migration=False
            )

            with context.begin_transaction():
                context.run_migrations()

run_migrations_online()

""")

        command.stamp(self.cfg, c)
    def test_tag_None(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
assert context.get_tag_argument() is None
""")
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
    def test_destination_rev_pre_context(self):
        env_file_fixture("""
assert context.get_revision_argument() == '%s'
""" % b)
        command.upgrade(self.cfg, b, sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (c, b), sql=True)
    def test_tag_cfg_arg(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', tag='there')
assert context.get_tag_argument() == 'there'
""")
        command.upgrade(self.cfg, b, sql=True, tag='hi')
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True, tag='hi')
Example #5
0
    def _setup_env_file(self):
        env_file_fixture(
            r"""

from sqlalchemy import MetaData, engine_from_config
target_metadata = MetaData()

engine = engine_from_config(
    config.get_section(config.config_ini_section),
    prefix='sqlalchemy.')

connection = engine.connect()

context.configure(
    connection=connection, target_metadata=target_metadata
)

try:
    with context.begin_transaction():
        config.stdout.write(u"environment included OK\n")
        context.run_migrations()
finally:
    connection.close()

"""
        )
Example #6
0
    def _env_fixture(self, version_table_pk=True):
        env_file_fixture(
            """

from sqlalchemy import MetaData, engine_from_config
target_metadata = MetaData()

engine = engine_from_config(
    config.get_section(config.config_ini_section),
    prefix='sqlalchemy.')

connection = engine.connect()

context.configure(
    connection=connection, target_metadata=target_metadata,
    version_table_pk=%r
)

try:
    with context.begin_transaction():
        context.run_migrations()
finally:
    connection.close()

"""
            % (version_table_pk,)
        )
    def test_starting_rev_context_runs_abbreviated(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
context.run_migrations()
""")
        command.upgrade(self.cfg, "%s:%s" % (b[0:4], c), sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b[0:4], a), sql=True)
    def test_starting_rev_pre_context_abbreviated(self):
        env_file_fixture("""
assert context.get_starting_revision_argument() == '%s'
""" % b[0:4])
        command.upgrade(self.cfg, "%s:%s" % (b[0:4], c), sql=True)
        command.stamp(self.cfg, "%s:%s" % (b[0:4], c), sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b[0:4], a), sql=True)
    def test_tag_pre_context_None(self):
        env_file_fixture(
            """
assert context.get_tag_argument() is None
"""
        )
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
    def test_not_requires_connection(self):
        env_file_fixture(
            """
assert not context.requires_connection()
"""
        )
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
    def test_requires_connection(self):
        env_file_fixture(
            """
assert context.requires_connection()
"""
        )
        command.upgrade(self.cfg, a)
        command.downgrade(self.cfg, a)
    def test_starting_rev_pre_context(self):
        env_file_fixture(
            """
assert context.get_starting_revision_argument() == 'x'
"""
        )
        command.upgrade(self.cfg, "x:y", sql=True)
        command.downgrade(self.cfg, "x:y", sql=True)
    def test_head_rev_pre_context(self):
        env_file_fixture("""
assert context.get_head_revision() == '%s'
""" % c)
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.current(self.cfg)
    def test_destination_rev_post_context(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
assert context.get_revision_argument() == '%s'
""" % b)
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (c, b), sql=True)
        command.stamp(self.cfg, b, sql=True)
    def test_tag_pre_context(self):
        env_file_fixture(
            """
assert context.get_tag_argument() == 'hi'
"""
        )
        command.upgrade(self.cfg, b, sql=True, tag="hi")
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True, tag="hi")
    def test_starting_rev_pre_context_cmd_w_no_startrev(self):
        env_file_fixture("""
assert context.get_starting_revision_argument() == 'x'
""")
        assert_raises_message(
            util.CommandError,
            "No starting revision argument is available.",
            command.current, self.cfg)
    def test_destination_rev_context_runs_abbreviated(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
context.run_migrations()
""")
        command.upgrade(self.cfg, "%s:%s" % (a, b[0:4]), sql=True)
        command.stamp(self.cfg, b[0:4], sql=True)
        command.downgrade(self.cfg, "%s:%s" % (c, b[0:4]), sql=True)
    def test_upgrade_with_output_encoding(self):
        env_file_fixture("""
url = config.get_main_option('sqlalchemy.url')
context.configure(url=url, output_encoding='utf-8')
assert not context.requires_connection()
""")
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
    def test_destination_rev_pre_context_multihead(self):
        d, e, f = multi_heads_fixture(self.cfg, a, b, c)
        env_file_fixture(
            """
assert set(context.get_revision_argument()) == set(('%s', '%s', '%s', ))
"""
            % (f, e, c)
        )
        command.upgrade(self.cfg, "heads", sql=True)
    def test_starting_rev_post_context(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', starting_rev='x')
assert context.get_starting_revision_argument() == 'x'
""")
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.current(self.cfg)
        command.stamp(self.cfg, a)
    def test_head_rev_post_context(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
assert context.get_head_revision() == '%s'
""" % c)
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.current(self.cfg)
    def test_downgrade_wo_colon(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
""")
        assert_raises_message(
            util.CommandError,
            "downgrade with --sql requires <fromrev>:<torev>",
            command.downgrade,
            self.cfg, b, sql=True
        )
Example #23
0
    def test_downgrade_wo_colon(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite')
""")
        assert_raises_message(
            util.CommandError,
            "downgrade with --sql requires <fromrev>:<torev>",
            command.downgrade,
            self.cfg,
            b,
            sql=True)
Example #24
0
    def test_destination_rev_post_context(self):
        env_file_fixture(
            """
context.configure(dialect_name='sqlite')
assert context.get_revision_argument() == '%s'
"""
            % b
        )
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (c, b), sql=True)
        command.stamp(self.cfg, b, sql=True)
Example #25
0
    def test_starting_rev_current_pre_context(self):
        env_file_fixture(
            """
assert context.get_starting_revision_argument() is None
"""
        )
        assert_raises_message(
            util.CommandError,
            "No starting revision argument is available.",
            command.current,
            self.cfg,
        )
Example #26
0
    def test_head_rev_pre_context(self):
        env_file_fixture(
            """
assert context.get_head_revision() == '%s'
assert context.get_head_revisions() == ('%s', )
"""
            % (c, c)
        )
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.current(self.cfg)
Example #27
0
    def test_head_rev_pre_context_multihead(self):
        d, e, f = multi_heads_fixture(self.cfg, a, b, c)
        env_file_fixture(
            """
assert set(context.get_head_revisions()) == set(('%s', '%s', '%s', ))
"""
            % (e, f, c)
        )
        command.upgrade(self.cfg, e, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (e, b), sql=True)
        command.stamp(self.cfg, c, sql=True)
        command.current(self.cfg)
Example #28
0
    def test_head_rev_post_context(self):
        env_file_fixture(
            """
context.configure(dialect_name='sqlite')
assert context.get_head_revision() == '%s'
assert context.get_head_revisions() == ('%s', )
"""
            % (c, c)
        )
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
        command.stamp(self.cfg, b, sql=True)
        command.current(self.cfg)
Example #29
0
    def _branched_connection_env():
        if config.requirements.sqlalchemy_14.enabled:
            connect_warning = (
                'r"The Connection.connect\\(\\) method is considered legacy"')
            close_warning = ('r"The .close\\(\\) method on a '
                             "so-called 'branched' connection\"")
        else:
            connect_warning = close_warning = ""

        env_file_fixture(
            textwrap.dedent(
                """\
            import alembic
            from alembic import context
            from sqlalchemy import engine_from_config, pool
            from sqlalchemy.testing import expect_warnings

            config = context.config

            target_metadata = None

            def run_migrations_online():
                connectable = engine_from_config(
                    config.get_section(config.config_ini_section),
                    prefix='sqlalchemy.',
                    poolclass=pool.NullPool)

                with connectable.connect() as conn:

                    with expect_warnings(%(connect_warning)s):
                        connection = conn.connect()
                    try:
                            context.configure(
                                connection=connection,
                                target_metadata=target_metadata,
                            )
                            with context.begin_transaction():
                                context.run_migrations()
                    finally:
                        with expect_warnings(%(close_warning)s):
                            connection.close()

            if context.is_offline_mode():
                assert False
            else:
                run_migrations_online()
            """ % {
                    "connect_warning": connect_warning,
                    "close_warning": close_warning,
                }))
    def test_tmpl_args_revision(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', template_args={"somearg":"somevalue"})
""")
        script_file_fixture("""
# somearg: ${somearg}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
""")

        command.revision(self.cfg, message="some rev")
        script = ScriptDirectory.from_config(self.cfg)

        rev = script.get_revision('head')
        with open(rev.path) as f:
            text = f.read()
        assert "somearg: somevalue" in text
    def test_tmpl_args_revision(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', template_args={"somearg":"somevalue"})
""")
        script_file_fixture("""
# somearg: ${somearg}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
""")

        command.revision(self.cfg, message="some rev")
        script = ScriptDirectory.from_config(self.cfg)

        rev = script.get_revision('head')
        with open(rev.path) as f:
            text = f.read()
        assert "somearg: somevalue" in text
    def test_bad_render(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', template_args={"somearg":"somevalue"})
""")
        script_file_fixture("""
    <% z = x + y %>
""")

        try:
            command.revision(self.cfg, message="some rev")
        except CommandError as ce:
            m = re.match(
                r"^Template rendering failed; see (.+?) "
                "for a template-oriented", str(ce))
            assert m, "Command error did not produce a file"
            contents = open(m.group(1)).read()
            os.remove(m.group(1))
            assert "<% z = x + y %>" in contents
Example #33
0
    def _env_file_fixture():
        env_file_fixture(
            textwrap.dedent(
                """\
            import alembic
            from alembic import context
            from sqlalchemy import engine_from_config, pool

            config = context.config

            target_metadata = None

            def run_migrations_offline():
                url = config.get_main_option('sqlalchemy.url')
                context.configure(
                    url=url, target_metadata=target_metadata,
                    on_version_apply=alembic.mock_event_listener,
                    literal_binds=True)

                with context.begin_transaction():
                    context.run_migrations()

            def run_migrations_online():
                connectable = engine_from_config(
                    config.get_section(config.config_ini_section),
                    prefix='sqlalchemy.',
                    poolclass=pool.NullPool)
                with connectable.connect() as connection:
                    context.configure(
                        connection=connection,
                        on_version_apply=alembic.mock_event_listener,
                        target_metadata=target_metadata,
                    )
                    with context.begin_transaction():
                        context.run_migrations()

            if context.is_offline_mode():
                run_migrations_offline()
            else:
                run_migrations_online()
            """
            )
        )
Example #34
0
    def _env_file_fixture():
        env_file_fixture(
            textwrap.dedent(
                """\
            import alembic
            from alembic import context
            from sqlalchemy import engine_from_config, pool

            config = context.config

            target_metadata = None

            def run_migrations_offline():
                url = config.get_main_option('sqlalchemy.url')
                context.configure(
                    url=url, target_metadata=target_metadata,
                    on_version_apply=alembic.mock_event_listener,
                    literal_binds=True)

                with context.begin_transaction():
                    context.run_migrations()

            def run_migrations_online():
                connectable = engine_from_config(
                    config.get_section(config.config_ini_section),
                    prefix='sqlalchemy.',
                    poolclass=pool.NullPool)
                with connectable.connect() as connection:
                    context.configure(
                        connection=connection,
                        on_version_apply=alembic.mock_event_listener,
                        target_metadata=target_metadata,
                    )
                    with context.begin_transaction():
                        context.run_migrations()

            if context.is_offline_mode():
                run_migrations_offline()
            else:
                run_migrations_online()
            """
            )
        )
    def test_bad_render(self):
        env_file_fixture("""
context.configure(dialect_name='sqlite', template_args={"somearg":"somevalue"})
""")
        script_file_fixture("""
    <% z = x + y %>
""")

        try:
            command.revision(self.cfg, message="some rev")
        except CommandError as ce:
            m = re.match(
                r"^Template rendering failed; see (.+?) "
                "for a template-oriented",
                str(ce)
            )
            assert m, "Command error did not produce a file"
            contents = open(m.group(1)).read()
            os.remove(m.group(1))
            assert "<% z = x + y %>" in contents
Example #36
0
    def _env_fixture(self):
        env_file_fixture("""

from sqlalchemy import MetaData, engine_from_config
target_metadata = MetaData()

engine = engine_from_config(
    config.get_section(config.config_ini_section),
    prefix='sqlalchemy.')

connection = engine.connect()

context.configure(connection=connection, target_metadata=target_metadata)

try:
    with context.begin_transaction():
        context.run_migrations()
finally:
    connection.close()

""")
Example #37
0
    def test_tag_pre_context(self):
        env_file_fixture("""
assert context.get_tag_argument() == 'hi'
""")
        command.upgrade(self.cfg, b, sql=True, tag='hi')
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True, tag='hi')
Example #38
0
    def test_tag_pre_context_None(self):
        env_file_fixture("""
assert context.get_tag_argument() is None
""")
        command.upgrade(self.cfg, b, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
Example #39
0
    def test_not_requires_connection(self):
        env_file_fixture("""
assert not context.requires_connection()
""")
        command.upgrade(self.cfg, a, sql=True)
        command.downgrade(self.cfg, "%s:%s" % (b, a), sql=True)
Example #40
0
def env():
    r"""Create an environment in which to run this test.

    Creates the environment directory using alembic.testing utilities, and
    additionally creates a revision map and scripts.

    Expressed visually, the map looks like this::

        A
        |
        B
        |
        C
        | \
        D  D0
        |  |  \
        E  E0  E1
        | /   / |
        F   F1  F2
        | /   / |
        G   G2  G3
        |   |  / |
        |   |  | G4
        |  /  / /
        | / / /
        ||/ /
        H--

    Note that ``H`` alone has a "depends_on", namely ``G4``.

    Uses class scope to create different environments for different backends.
    """
    env = staging_env()
    env_file_fixture(_env_content)
    _write_config_file(_cfg_content % (_get_staging_directory(),
                                       sqla_test_config.db_url))
    revs = env._revs = {}

    def gen(rev, head=None, **kw):
        if head:
            kw['head'] = [env._revs[h].revision for h in head.split()]
        revid = '__'.join((rev, util.rev_id()))
        env._revs[rev] = env.generate_revision(revid, rev, splice=True, **kw)

    gen('A')
    gen('B')
    gen('C')
    gen('D')
    gen('D0', 'C')
    gen('E', 'D')
    gen('E0', 'D0')
    gen('E1', 'D0')
    gen('F', 'E E0')
    gen('F1', 'E1')
    gen('F2', 'E1')
    gen('G', 'F F1')
    gen('G2', 'F2')
    gen('G3', 'F2')
    gen('G4', 'G3')
    gen('H', 'G G2', depends_on='G4')

    revids = env._revids = {k: v.revision for k, v in revs.items()}
    env.R = type('R', (object,), revids)
    yield env
Example #41
0
    def test_requires_connection(self):
        env_file_fixture("""
assert context.requires_connection()
""")
        command.upgrade(self.cfg, a)
        command.downgrade(self.cfg, a)
Example #42
0
    def test_starting_rev_pre_context(self):
        env_file_fixture("""
assert context.get_starting_revision_argument() == 'x'
""")
        command.upgrade(self.cfg, "x:y", sql=True)
        command.downgrade(self.cfg, "x:y", sql=True)
Example #43
0
    def test_destination_rev_pre_context_multihead(self):
        d, e, f = multi_heads_fixture(self.cfg, a, b, c)
        env_file_fixture("""
assert set(context.get_revision_argument()) == set(('%s', '%s', '%s', ))
""" % (f, e, c))
        command.upgrade(self.cfg, 'heads', sql=True)