コード例 #1
0
ファイル: test_autogenerate.py プロジェクト: Lifto/alembic
 def test_render_quoted_server_default(self):
     eq_(
         autogenerate._render_server_default(
             "nextval('group_to_perm_group_to_perm_id_seq'::regclass)",
                 self.autogen_context),
         '"nextval(\'group_to_perm_group_to_perm_id_seq\'::regclass)"'
     )
コード例 #2
0
    def test_render_custom(self):

        def render(type_, obj, context):
            if type_ == "foreign_key":
                return None
            if type_ == "column":
                if obj.name == "y":
                    return None
                else:
                    return "col(%s)" % obj.name
            return "render:%s" % type_

        autogen_context = {"opts": {
            'render_item': render,
            'alembic_module_prefix': 'sa.'
        }}

        t = Table('t', MetaData(),
                Column('x', Integer),
                Column('y', Integer),
                PrimaryKeyConstraint('x'),
                ForeignKeyConstraint(['x'], ['y'])
            )
        result = autogenerate._add_table(
                    t, autogen_context
                )
        eq_(
            result, """sa.create_table('t',
col(x),
render:primary_key\n)"""
        )
コード例 #3
0
ファイル: test_set.py プロジェクト: wiley17402/evil
    def test_globlookup(self):
        # Create temporary files equivalent to those used in test_strlookup
        tmp = mkdtemp()
        chars = ("a", "b", "c")
        for l1 in chars:
            os.mkdir(os.path.join(tmp, l1))
            for l2 in chars:
                os.mkdir(os.path.join(tmp, l1, l2))
                for l3 in chars:
                    f = os.path.join(tmp, l1, l2, l3)
                    with open(f, "w") as fh:
                        fh.write(f)

        # Test the lookup
        lookup = partial(globlookup, root=tmp)
        eq_(list(lookup("a/a/*")), ["a/a/a", "a/a/b", "a/a/c"])
        eq_(list(lookup("a/*/a")), ["a/a/a", "a/b/a", "a/c/a"])
        eq_(list(lookup("*/a/a")), ["a/a/a", "b/a/a", "c/a/a"])
        eq_(list(lookup("a/*")), [
            "a/a/a",
            "a/a/b",
            "a/a/c",
            "a/b/a",
            "a/b/b",
            "a/b/c",
            "a/c/a",
            "a/c/b",
            "a/c/c",
        ])

        # Test the lookup within set_evil
        eq_(set_evil("a/* = */a", lookup), set(["a/a/a", "a/b/a", "a/c/a"]))
コード例 #4
0
 def test_render_drop_table_w_schema(self):
     eq_(
         autogenerate._drop_table(
             Table("sometable", MetaData(), schema='foo'),
             self.autogen_context),
         "op.drop_table('sometable', schema='foo')"
     )
コード例 #5
0
 def test_render_add_column(self):
     eq_(
         autogenerate._add_column("foo",
                                  Column("x", Integer, server_default="5"),
                                  self.autogen_context),
         "op.add_column('foo', sa.Column('x', sa.Integer(), "
         "server_default='5', nullable=True))")
コード例 #6
0
ファイル: test_evil.py プロジェクト: icio/evil
 def test_set_evil_op_opposing(self):
     try:
         set_evil("a > < b", lambda t: set(), self.left_right_ops())
     except SyntaxError as e:
         eq_(e.args[0], "Operators cannot be beside one another if they "
                        "act on expressions facing one-another.")
         set_evil("a <> <> b", lambda t: set(), self.left_right_ops())
コード例 #7
0
    def test_option(self):
        self.cfg.set_main_option("file_template", "myfile_%%(slug)s")
        script = ScriptDirectory.from_config(self.cfg)
        a = util.rev_id()
        script.generate_revision(a, "some message", refresh=True)
        write_script(
            script,
            a,
            """
    revision = '%s'
    down_revision = None

    from alembic import op

    def upgrade():
        op.execute("CREATE TABLE foo(id integer)")

    def downgrade():
        op.execute("DROP TABLE foo")

    """
            % a,
        )

        script = ScriptDirectory.from_config(self.cfg)
        rev = script._get_rev(a)
        eq_(rev.revision, a)
        eq_(os.path.basename(rev.path), "myfile_some_message.py")
コード例 #8
0
    def test_render_nothing(self):
        context = MigrationContext.configure(
            connection=self.bind.connect(),
            opts={
                'compare_type': True,
                'compare_server_default': True,
                'target_metadata': self.m1,
                'upgrade_token': "upgrades",
                'downgrade_token': "downgrades",
                'alembic_module_prefix': 'op.',
                'sqlalchemy_module_prefix': 'sa.',
            }
        )
        template_args = {}
        autogenerate._produce_migration_diffs(context, template_args, set(),
                include_symbol=lambda name, schema: False
            )
        eq_(re.sub(r"u'", "'", template_args['upgrades']),
"""### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###""")
        eq_(re.sub(r"u'", "'", template_args['downgrades']),
"""### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###""")
コード例 #9
0
 def test_clear(self):
     db = sqlsoup.SQLSoup(engine)
     eq_(db.loans.count(), 1)
     _ = db.loans.insert(book_id=1, user_name='Bhargan Basepair')
     db.expunge_all()
     db.flush()
     eq_(db.loans.count(), 1)
コード例 #10
0
    def test_lookup_legacy(self):
        self.cfg.set_main_option("file_template", "%%(rev)s")
        script = ScriptDirectory.from_config(self.cfg)
        a = util.rev_id()
        script.generate_revision(a, None, refresh=True)
        write_script(
            script,
            a,
            """
    down_revision = None

    from alembic import op

    def upgrade():
        op.execute("CREATE TABLE foo(id integer)")

    def downgrade():
        op.execute("DROP TABLE foo")

    """,
        )

        script = ScriptDirectory.from_config(self.cfg)
        rev = script._get_rev(a)
        eq_(rev.revision, a)
        eq_(os.path.basename(rev.path), "%s.py" % a)
コード例 #11
0
 def test_relations(self):
     db = sqlsoup.SQLSoup(engine)
     db.users.relate('loans', db.loans)
     MappedLoans = db.loans
     MappedUsers = db.users
     eq_(
         db.users.get('Joe Student').loans, [
             MappedLoans(book_id=1,
                         user_name='Joe Student',
                         loan_date=datetime.datetime(2006, 7, 12, 0, 0))
         ])
     db.rollback()
     eq_(
         db.users.filter(~db.users.loans.any()).all(), [
             MappedUsers(name='Bhargan Basepair',
                         email='*****@*****.**',
                         password='******',
                         classname=None,
                         admin=1)
         ])
     db.rollback()
     del db._cache['users']
     db.users.relate('loans',
                     db.loans,
                     order_by=db.loans.loan_date,
                     cascade='all, delete-orphan')
コード例 #12
0
    def test_single_insert_round_trip(self):
        self.op.bulk_insert(self.t1, [{'data': "d1", "x": "x1"}])

        eq_(
            self.conn.execute("select id, data, x from foo").fetchall(), [
                (1, "d1", "x1"),
            ])
コード例 #13
0
ファイル: test_set.py プロジェクト: icio/evil
    def test_globlookup(self):
        # Create temporary files equivalent to those used in test_strlookup
        tmp = mkdtemp()
        chars = ("a", "b", "c")
        for l1 in chars:
            os.mkdir(os.path.join(tmp, l1))
            for l2 in chars:
                os.mkdir(os.path.join(tmp, l1, l2))
                for l3 in chars:
                    f = os.path.join(tmp, l1, l2, l3)
                    with open(f, "w") as fh:
                        fh.write(f)

        # Test the lookup
        lookup = partial(globlookup, root=tmp)
        eq_(list(lookup("a/a/*")), ["a/a/a", "a/a/b", "a/a/c"])
        eq_(list(lookup("a/*/a")), ["a/a/a", "a/b/a", "a/c/a"])
        eq_(list(lookup("*/a/a")), ["a/a/a", "b/a/a", "c/a/a"])
        eq_(list(lookup("a/*")), [
            "a/a/a", "a/a/b", "a/a/c",
            "a/b/a", "a/b/b", "a/b/c",
            "a/c/a", "a/c/b", "a/c/c",
            ])

        # Test the lookup within set_evil
        eq_(set_evil("a/* = */a", lookup), set(["a/a/a", "a/b/a", "a/c/a"]))
コード例 #14
0
ファイル: test_sqlsoup.py プロジェクト: kenwilcox/sqlsoup
 def test_clear(self):
     db = sqlsoup.SQLSoup(engine)
     eq_(db.loans.count(), 1)
     _ = db.loans.insert(book_id=1, user_name='Bhargan Basepair')
     db.expunge_all()
     db.flush()
     eq_(db.loans.count(), 1)
コード例 #15
0
 def test_args_propagate(self):
     config = _no_sql_testing_config()
     script = ScriptDirectory.from_config(config)
     template_args = {"x": "x1", "y": "y1", "z": "z1"}
     env = EnvironmentContext(config, script, template_args=template_args)
     env.configure(dialect_name="sqlite", template_args={"y": "y2", "q": "q1"})
     eq_(template_args, {"x": "x1", "y": "y2", "z": "z1", "q": "q1"})
コード例 #16
0
ファイル: test_config.py プロジェクト: Lifto/alembic
def test_standalone_op():
    eng, buf = capture_db()

    env = MigrationContext.configure(eng)
    op = Operations(env)

    op.alter_column("t", "c", nullable=True)
    eq_(buf, ['ALTER TABLE t ALTER COLUMN c DROP NOT NULL'])
コード例 #17
0
ファイル: test_autogenerate.py プロジェクト: Lifto/alembic
 def test_render_add_column(self):
     eq_(
         autogenerate._add_column(
                 "foo", Column("x", Integer, server_default="5"),
                     self.autogen_context),
         "op.add_column('foo', sa.Column('x', sa.Integer(), "
             "server_default='5', nullable=True))"
     )
コード例 #18
0
ファイル: test_config.py プロジェクト: Lifto/alembic
def test_config_no_file_section_option():
    cfg = config.Config()
    cfg.set_section_option("foo", "url", "postgresql://foo/bar")

    eq_(cfg.get_section_option("foo", "url"), "postgresql://foo/bar")

    cfg.set_section_option("foo", "echo", "True")
    eq_(cfg.get_section_option("foo", "echo"), "True")
コード例 #19
0
    def test_render_drop_column_w_schema(self):
        eq_(
            autogenerate._drop_column(
                    "foo", "bar", Column("x", Integer, server_default="5"),
                        self.autogen_context),

            "op.drop_column('bar', 'x', schema='foo')"
        )
コード例 #20
0
ファイル: test_xcpp.py プロジェクト: jmlopez-rod/excentury
def test_xcpp_matlab():
    """[XCPP-MATLAB]: """
    exec_cmd('excentury xc_test.xcpp to matlab --force')
    cmd = 'matlab -nodisplay -nosplash'
    run_cmd("%s < matlab/xc_test.m > /dev/null" % cmd, "", "")
    data = load_file('tmp.xc')
    eq_(data['x'], 4, "Failed...")
    eq_(data['y'], 27, "Failed...")
コード例 #21
0
ファイル: test_evil.py プロジェクト: icio/evil
 def test_set_evil_op_right_missing(self):
     try:
         set_evil("a >", lambda t: set(), self.left_right_ops())
     except SyntaxError as e:
         eq_(e.args[0], "Operators which act on expressions to their "
                        "right or both sides cannot be at the end of "
                        "an expression.")
         raise e
コード例 #22
0
ファイル: test_evil.py プロジェクト: icio/evil
 def test_set_evil_op_left_missing(self):
     try:
         set_evil("< b", lambda t: set(), self.left_right_ops())
     except TypeError as e:
         eq_(e.args[0], "Operators which act on expressions to their "
                        "left or both sides cannot be at the beginning "
                        "of an expression.")
         raise e
コード例 #23
0
ファイル: test_autogenerate.py プロジェクト: Lifto/alembic
    def test_render_drop_column(self):
        eq_(
            autogenerate._drop_column(
                    "foo", Column("x", Integer, server_default="5"),
                        self.autogen_context),

            "op.drop_column('foo', 'x')"
        )
コード例 #24
0
 def test_set_evil_op_opposing(self):
     try:
         set_evil("a > < b", lambda t: set(), self.left_right_ops())
     except SyntaxError as e:
         eq_(
             e.args[0], "Operators cannot be beside one another if they "
             "act on expressions facing one-another.")
         set_evil("a <> <> b", lambda t: set(), self.left_right_ops())
コード例 #25
0
ファイル: test_autogenerate.py プロジェクト: Lifto/alembic
    def test_render_diffs(self):
        """test a full render including indentation"""

        metadata = self.m2
        template_args = {}
        autogenerate._produce_migration_diffs(self.context, template_args, set())
        eq_(re.sub(r"u'", "'", template_args['upgrades']),
"""### commands auto generated by Alembic - please adjust! ###
    op.create_table('item',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('description', sa.String(length=100), nullable=True),
    sa.Column('order_id', sa.Integer(), nullable=True),
    sa.CheckConstraint('len(description) > 5'),
    sa.ForeignKeyConstraint(['order_id'], ['order.order_id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.drop_table('extra')
    op.add_column('address', sa.Column('street', sa.String(length=50), nullable=True))
    op.add_column('order', sa.Column('user_id', sa.Integer(), nullable=True))
    op.alter_column('order', 'amount',
               existing_type=sa.NUMERIC(precision=8, scale=2),
               type_=sa.Numeric(precision=10, scale=2),
               nullable=True,
               existing_server_default='0')
    op.drop_column('user', 'pw')
    op.alter_column('user', 'a1',
               existing_type=sa.TEXT(),
               server_default='x',
               existing_nullable=True)
    op.alter_column('user', 'name',
               existing_type=sa.VARCHAR(length=50),
               nullable=False)
    ### end Alembic commands ###""")
        eq_(re.sub(r"u'", "'", template_args['downgrades']),
"""### commands auto generated by Alembic - please adjust! ###
    op.alter_column('user', 'name',
               existing_type=sa.VARCHAR(length=50),
               nullable=True)
    op.alter_column('user', 'a1',
               existing_type=sa.TEXT(),
               server_default=None,
               existing_nullable=True)
    op.add_column('user', sa.Column('pw', sa.VARCHAR(length=50), nullable=True))
    op.alter_column('order', 'amount',
               existing_type=sa.Numeric(precision=10, scale=2),
               type_=sa.NUMERIC(precision=8, scale=2),
               nullable=False,
               existing_server_default='0')
    op.drop_column('order', 'user_id')
    op.drop_column('address', 'street')
    op.create_table('extra',
    sa.Column('x', sa.CHAR(), nullable=True),
    sa.Column('uid', sa.INTEGER(), nullable=True),
    sa.ForeignKeyConstraint(['uid'], ['user.id'], ),
    sa.PrimaryKeyConstraint()
    )
    op.drop_table('item')
    ### end Alembic commands ###""")
コード例 #26
0
 def test_set_evil_op_left_missing(self):
     try:
         set_evil("< b", lambda t: set(), self.left_right_ops())
     except TypeError as e:
         eq_(
             e.args[0], "Operators which act on expressions to their "
             "left or both sides cannot be at the beginning "
             "of an expression.")
         raise e
コード例 #27
0
ファイル: test_sqlsoup.py プロジェクト: kenwilcox/sqlsoup
 def test_order_by(self):
     db = sqlsoup.SQLSoup(engine)
     MappedUsers = db.users
     users = db.users.order_by(db.users.name).all()
     eq_(users, [MappedUsers(name='Bhargan Basepair',
         email='*****@*****.**', password='******',
         classname=None, admin=1), MappedUsers(name='Joe Student',
         email='*****@*****.**', password='******',
         classname=None, admin=0)])
コード例 #28
0
 def test_dont_barf_on_already_reflected(self):
     diffs = []
     from sqlalchemy.util import OrderedSet
     inspector = Inspector.from_engine(self.bind)
     autogenerate._compare_tables(OrderedSet(['extra', 'user']),
                                  OrderedSet(), inspector, MetaData(),
                                  diffs, self.autogen_context)
     eq_([(rec[0], rec[1].name) for rec in diffs],
         [('remove_table', 'extra'), ('remove_table', u'user')])
コード例 #29
0
 def test_set_evil_op_right_missing(self):
     try:
         set_evil("a >", lambda t: set(), self.left_right_ops())
     except SyntaxError as e:
         eq_(
             e.args[0], "Operators which act on expressions to their "
             "right or both sides cannot be at the end of "
             "an expression.")
         raise e
コード例 #30
0
ファイル: test_sqlsoup.py プロジェクト: kenwilcox/sqlsoup
 def test_cls_crud(self):
     db = sqlsoup.SQLSoup(engine)
     MappedUsers = db.users
     db.users.filter_by(name='Bhargan Basepair'
                        ).update(dict(name='Some New Name'))
     u1 = db.users.filter_by(name='Some New Name').one()
     eq_(u1, MappedUsers(name='Some New Name',
         email='*****@*****.**', password='******',
         classname=None, admin=1))
コード例 #31
0
ファイル: test_sqlsoup.py プロジェクト: kenwilcox/sqlsoup
 def test_map_table(self):
     db = sqlsoup.SQLSoup(engine)
     users = Table('users', db._metadata, autoload=True)
     MappedUsers = db.map(users)
     users = MappedUsers.order_by(db.users.name).all()
     eq_(users, [MappedUsers(name='Bhargan Basepair',
         email='*****@*****.**', password='******',
         classname=None, admin=1), MappedUsers(name='Joe Student',
         email='*****@*****.**', password='******',
         classname=None, admin=0)])
コード例 #32
0
 def test_args(self):
     script = ScriptDirectory(
         staging_directory,
         file_template="%(rev)s_%(slug)s_" "%(year)s_%(month)s_" "%(day)s_%(hour)s_" "%(minute)s_%(second)s",
     )
     create_date = datetime.datetime(2012, 7, 25, 15, 8, 5)
     eq_(
         script._rev_path("12345", "this is a message", create_date),
         "%s/versions/12345_this_is_a_" "message_2012_7_25_15_8_5.py" % staging_directory,
     )
コード例 #33
0
ファイル: test_sqlsoup.py プロジェクト: kenwilcox/sqlsoup
 def test_selectable(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])
     eq_(years_with_count.filter_by(published_year='1989').all(),
         [MappedBooks(published_year='1989', n=1)])
コード例 #34
0
 def test_render_col_with_server_default(self):
     c = Column('updated_at',
                TIMESTAMP(),
                server_default='TIMEZONE("utc", CURRENT_TIMESTAMP)',
                nullable=False)
     result = autogenerate._render_column(c, self.autogen_context)
     eq_(
         result, 'sa.Column(\'updated_at\', sa.TIMESTAMP(), '
         'server_default=\'TIMEZONE("utc", CURRENT_TIMESTAMP)\', '
         'nullable=False)')
コード例 #35
0
 def test_004_rev(self):
     script = env.generate_revision(abc, "this is a message", refresh=True)
     eq_(script.doc, "this is a message")
     eq_(script.revision, abc)
     eq_(script.down_revision, None)
     assert os.access(
         os.path.join(env.dir, 'versions', '%s_this_is_a_message.py' % abc), os.F_OK)
     assert callable(script.module.upgrade)
     eq_(env.get_heads(), [abc])
     eq_(env.get_base(), abc)
コード例 #36
0
def test_relative_downgrade_path():
    eq_(env._downgrade_revs("-1", c.revision), [
        (c.module.downgrade, c.revision, c.down_revision, c.doc),
    ])

    eq_(env._downgrade_revs("-3", e.revision), [
        (e.module.downgrade, e.revision, e.down_revision, e.doc),
        (d.module.downgrade, d.revision, d.down_revision, d.doc),
        (c.module.downgrade, c.revision, c.down_revision, c.doc),
    ])
コード例 #37
0
 def test_args(self):
     script = ScriptDirectory(staging_directory,
                              file_template="%(rev)s_%(slug)s_"
                              "%(year)s_%(month)s_"
                              "%(day)s_%(hour)s_"
                              "%(minute)s_%(second)s")
     create_date = datetime.datetime(2012, 7, 25, 15, 8, 5)
     eq_(
         script._rev_path("12345", "this is a message", create_date),
         "%s/versions/12345_this_is_a_"
         "message_2012_7_25_15_8_5.py" % staging_directory)
コード例 #38
0
 def test_004_rev(self):
     script = env.generate_revision(abc, "this is a message", refresh=True)
     eq_(script.doc, "this is a message")
     eq_(script.revision, abc)
     eq_(script.down_revision, None)
     assert os.access(
         os.path.join(env.dir, 'versions',
                      '%s_this_is_a_message.py' % abc), os.F_OK)
     assert callable(script.module.upgrade)
     eq_(env.get_heads(), [abc])
     eq_(env.get_base(), abc)
コード例 #39
0
    def test_single_insert_round_trip(self):
        self.op.bulk_insert(self.t1,
            [{'data':"d1", "x":"x1"}]
        )

        eq_(
            self.conn.execute("select id, data, x from foo").fetchall(),
            [
                (1, "d1", "x1"),
            ]
        )
コード例 #40
0
 def test_args_propagate(self):
     config = _no_sql_testing_config()
     script = ScriptDirectory.from_config(config)
     template_args = {"x": "x1", "y": "y1", "z": "z1"}
     env = EnvironmentContext(config, script, template_args=template_args)
     env.configure(dialect_name="sqlite",
                   template_args={
                       "y": "y2",
                       "q": "q1"
                   })
     eq_(template_args, {"x": "x1", "y": "y2", "z": "z1", "q": "q1"})
コード例 #41
0
 def test_expr_tokenizer(self):
     eq_(
         list(
             expr_tokenizer("^^ ^ (a, b + c)",
                            ["^", "^^", "(", ")", "+", "-", ","])),
         ["^^", "^", "(", "a", ",", "b", "+", "c", ")"])
     eq_(
         list(
             expr_tokenizer("^ ^ ^ (a, b + c)",
                            ["^", "^^", "(", ")", "+", "-", ","])),
         ["^", "^", "^", "(", "a", ",", "b", "+", "c", ")"])
コード例 #42
0
 def test_default_schema_omitted_upgrade(self):
     metadata = self.m2
     connection = self.context.bind
     diffs = []
     autogenerate._produce_net_changes(connection, metadata, diffs,
                                       self.autogen_context,
                                       include_symbol=lambda n, s: n == 't3',
                                       include_schemas=True
                                       )
     eq_(diffs[0][0], "add_table")
     eq_(diffs[0][1].schema, None)
コード例 #43
0
 def test_alt_schema_included_downgrade(self):
     metadata = self.m2
     connection = self.context.bind
     diffs = []
     autogenerate._produce_net_changes(connection, metadata, diffs,
                                       self.autogen_context,
                                       include_symbol=lambda n, s: n == 't2',
                                       include_schemas=True
                                       )
     eq_(diffs[0][0], "remove_table")
     eq_(diffs[0][1].schema, self.test_schema_name)
コード例 #44
0
ファイル: test_autogenerate.py プロジェクト: Lifto/alembic
 def test_dont_barf_on_already_reflected(self):
     diffs = []
     from sqlalchemy.util import OrderedSet
     inspector = Inspector.from_engine(self.bind)
     autogenerate._compare_tables(
         OrderedSet(['extra', 'user']), OrderedSet(), inspector,
             MetaData(), diffs, self.autogen_context
     )
     eq_(
         [(rec[0], rec[1].name) for rec in diffs],
         [('remove_table', 'extra'), ('remove_table', u'user')]
     )
コード例 #45
0
def test_upgrade_path():

    eq_(env._upgrade_revs(e.revision, c.revision), [
        (d.module.upgrade, c.revision, d.revision, d.doc),
        (e.module.upgrade, d.revision, e.revision, e.doc),
    ])

    eq_(env._upgrade_revs(c.revision, None), [
        (a.module.upgrade, None, a.revision, a.doc),
        (b.module.upgrade, a.revision, b.revision, b.doc),
        (c.module.upgrade, b.revision, c.revision, c.doc),
    ])
コード例 #46
0
def test_downgrade_path():

    eq_(env._downgrade_revs(c.revision, e.revision), [
        (e.module.downgrade, e.revision, e.down_revision, e.doc),
        (d.module.downgrade, d.revision, d.down_revision, d.doc),
    ])

    eq_(env._downgrade_revs(None, c.revision), [
        (c.module.downgrade, c.revision, c.down_revision, c.doc),
        (b.module.downgrade, b.revision, b.down_revision, b.doc),
        (a.module.downgrade, a.revision, a.down_revision, a.doc),
    ])
コード例 #47
0
    def test_006_from_clean_env(self):
        # test the environment so far with a
        # new ScriptDirectory instance.

        env = staging_env(create=False)
        abc_rev = env._revision_map[abc]
        def_rev = env._revision_map[def_]
        eq_(abc_rev.nextrev, set([def_]))
        eq_(abc_rev.revision, abc)
        eq_(def_rev.down_revision, abc)
        eq_(env.get_heads(), [def_])
        eq_(env.get_base(), abc)
コード例 #48
0
 def test_selectable(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])
     eq_(
         years_with_count.filter_by(published_year='1989').all(),
         [MappedBooks(published_year='1989', n=1)])
コード例 #49
0
 def test_inline_percent(self):
     # TODO: here's the issue, you need to escape this.
     tab = table('tab', column('col'))
     self.op.execute(
         tab.update().where(
             tab.c.col.like(self.op.inline_literal('%.%'))
         ).values(col=self.op.inline_literal('new data')),
         execution_options={'no_parameters':True}
     )
     eq_(
         self.conn.execute("select count(*) from tab where col='new data'").scalar(),
         1,
     )
コード例 #50
0
 def test_cls_crud(self):
     db = sqlsoup.SQLSoup(engine)
     MappedUsers = db.users
     db.users.filter_by(name='Bhargan Basepair').update(
         dict(name='Some New Name'))
     u1 = db.users.filter_by(name='Some New Name').one()
     eq_(
         u1,
         MappedUsers(name='Some New Name',
                     email='*****@*****.**',
                     password='******',
                     classname=None,
                     admin=1))
コード例 #51
0
    def test_op(self):
        def myop(l, r):
            pass

        eq_(op("+", myop), ("+", myop, OP_BOTH))
        eq_(op("+", myop, right=True), ("+", myop, OP_RIGHT))
        eq_(op("+", myop, left=True), ("+", myop, OP_LEFT))
        eq_(op("+", myop, left=True, right=True), ("+", myop, OP_BOTH))
コード例 #52
0
 def test_boolean_gen_upgrade(self):
     template_args = {}
     autogenerate._produce_migration_diffs(
         self.context,
         template_args,
         set(),
         include_symbol=lambda name: name == 'sometable')
     eq_(
         re.sub(r"u'", "'", template_args['upgrades']),
         "### commands auto generated by Alembic - please adjust! ###\n"
         "    op.create_table('sometable',\n"
         "    sa.Column('id', sa.Integer(), nullable=False),\n"
         "    sa.Column('value', sa.Boolean(), nullable=True),\n"
         "    sa.PrimaryKeyConstraint('id')\n    )\n"
         "    ### end Alembic commands ###")
コード例 #53
0
 def test_005_nextrev(self):
     script = env.generate_revision(
         def_, "this is the next rev", refresh=True)
     assert os.access(
         os.path.join(
             env.dir, 'versions',
             '%s_this_is_the_next_rev.py' % def_), os.F_OK)
     eq_(script.revision, def_)
     eq_(script.down_revision, abc)
     eq_(env._revision_map[abc].nextrev, set([def_]))
     assert script.module.down_revision == abc
     assert callable(script.module.upgrade)
     assert callable(script.module.downgrade)
     eq_(env.get_heads(), [def_])
     eq_(env.get_base(), abc)
コード例 #54
0
 def test_mapped_join(self):
     db = sqlsoup.SQLSoup(engine)
     join1 = MappedJoin = db.join(db.users, db.loans, isouter=True)
     mj = join1.filter_by(name='Joe Student').all()
     eq_(mj, [
         MappedJoin(
             name='Joe Student',
             email='*****@*****.**',
             password='******',
             classname=None,
             admin=0,
             book_id=1,
             user_name='Joe Student',
             loan_date=datetime.datetime(2006, 7, 12, 0, 0),
         )
     ])
     db.rollback()
     join2 = MappedJoin = db.join(join1, db.books)
     mj = join2.all()
     eq_(mj, [
         MappedJoin(
             name='Joe Student',
             email='*****@*****.**',
             password='******',
             classname=None,
             admin=0,
             book_id=1,
             user_name='Joe Student',
             loan_date=datetime.datetime(2006, 7, 12, 0, 0),
             id=1,
             title='Mustards I Have Known',
             published_year='1989',
             authors='Jones',
         )
     ])
     eq_(
         db.with_labels(join1).c.keys(), [
             'users_name',
             'users_email',
             'users_password',
             'users_classname',
             'users_admin',
             'loans_book_id',
             'loans_user_name',
             'loans_loan_date',
         ])
     labeled_loans = db.with_labels(db.loans)
     eq_(
         db.join(db.users, labeled_loans, isouter=True).c.keys(), [
             'name',
             'email',
             'password',
             'classname',
             'admin',
             'loans_book_id',
             'loans_user_name',
             'loans_loan_date',
         ])
コード例 #55
0
 def test_order_by(self):
     db = sqlsoup.SQLSoup(engine)
     MappedUsers = db.users
     users = db.users.order_by(db.users.name).all()
     eq_(users, [
         MappedUsers(name='Bhargan Basepair',
                     email='*****@*****.**',
                     password='******',
                     classname=None,
                     admin=1),
         MappedUsers(name='Joe Student',
                     email='*****@*****.**',
                     password='******',
                     classname=None,
                     admin=0)
     ])
コード例 #56
0
 def test_map_table(self):
     db = sqlsoup.SQLSoup(engine)
     users = Table('users', db._metadata, autoload=True)
     MappedUsers = db.map(users)
     users = MappedUsers.order_by(db.users.name).all()
     eq_(users, [
         MappedUsers(name='Bhargan Basepair',
                     email='*****@*****.**',
                     password='******',
                     classname=None,
                     admin=1),
         MappedUsers(name='Joe Student',
                     email='*****@*****.**',
                     password='******',
                     classname=None,
                     admin=0)
     ])
コード例 #57
0
    def test_bulk_insert_round_trip(self):
        self.op.bulk_insert(self.t1, [
            {
                'data': "d1",
                "x": "x1"
            },
            {
                'data': "d2",
                "x": "x2"
            },
            {
                'data': "d3",
                "x": "x3"
            },
        ])

        eq_(
            self.conn.execute("select id, data, x from foo").fetchall(),
            [(1, "d1", "x1"), (2, "d2", "x2"), (3, "d3", "x3")])
コード例 #58
0
 def test_whereclause(self):
     db = sqlsoup.SQLSoup(engine)
     MappedUsers = db.users
     where = or_(db.users.name == 'Bhargan Basepair',
                 db.users.email == '*****@*****.**')
     users = \
         db.users.filter(where).order_by(desc(db.users.name)).all()
     eq_(users, [
         MappedUsers(name='Joe Student',
                     email='*****@*****.**',
                     password='******',
                     classname=None,
                     admin=0),
         MappedUsers(name='Bhargan Basepair',
                     email='*****@*****.**',
                     password='******',
                     classname=None,
                     admin=1)
     ])
コード例 #59
0
    def test_boolean_gen_downgrade(self):
        # on the downgrade side, we are OK for now, as SQLAlchemy
        # does not reflect check constraints yet.

        template_args = {}
        autogenerate._produce_migration_diffs(
            self.context,
            template_args,
            set(),
        )
        eq_(
            re.sub(r"u'", "'", template_args['downgrades']),
            "### commands auto generated by Alembic - please adjust! ###\n"
            "    op.create_table('someothertable',\n"
            "    sa.Column('id', mysql.INTEGER(display_width=11), "
            "nullable=False),\n"
            "    sa.Column('value', mysql.TINYINT(display_width=1), "
            "nullable=True),\n"
            "    sa.PrimaryKeyConstraint('id')\n    )\n"
            "    op.drop_table('sometable')\n"
            "    ### end Alembic commands ###")