def test_all_traverse(self): writer = autogenerate.Rewriter() mocker = mock.Mock(side_effect=lambda context, revision, op: op) writer.rewrites(ops.MigrateOperation)(mocker) addcolop = ops.AddColumnOp( 't1', sa.Column('x', sa.Integer()) ) directives = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps(ops=[ ops.ModifyTableOps('t1', ops=[ addcolop ]) ]), ops.DowngradeOps(ops=[ ]), ) ] ctx, rev = mock.Mock(), mock.Mock() writer(ctx, rev, directives) eq_( mocker.mock_calls, [ mock.call(ctx, rev, directives[0]), mock.call(ctx, rev, directives[0].upgrade_ops), mock.call(ctx, rev, directives[0].upgrade_ops.ops[0]), mock.call(ctx, rev, addcolop), mock.call(ctx, rev, directives[0].downgrade_ops), ] )
def test_add_foreign_key_dialect_kw(self): op_fixture() with mock.patch("sqlalchemy.schema.ForeignKeyConstraint") as fkc: op.create_foreign_key("fk_test", "t1", "t2", ["foo", "bar"], ["bat", "hoho"], foobar_arg="xyz") if config.requirements.foreign_key_match.enabled: eq_( fkc.mock_calls[0], mock.call( ["foo", "bar"], ["t2.bat", "t2.hoho"], onupdate=None, ondelete=None, name="fk_test", foobar_arg="xyz", deferrable=None, initially=None, match=None, ), ) else: eq_( fkc.mock_calls[0], mock.call( ["foo", "bar"], ["t2.bat", "t2.hoho"], onupdate=None, ondelete=None, name="fk_test", foobar_arg="xyz", deferrable=None, initially=None, ), )
def test_create_fk_schema(self): with self._fixture(schema='foo') as batch: batch.create_foreign_key('myfk', 'user', ['x'], ['y']) eq_(self.mock_schema.ForeignKeyConstraint.mock_calls, [ mock.call(['x'], ['user.y'], onupdate=None, ondelete=None, name='myfk', initially=None, deferrable=None, match=None) ]) eq_(self.mock_schema.Table.mock_calls, [ mock.call('user', self.mock_schema.MetaData(), self.mock_schema.Column(), schema=None), mock.call('tname', self.mock_schema.MetaData(), self.mock_schema.Column(), schema='foo'), mock.call().append_constraint( self.mock_schema.ForeignKeyConstraint()) ]) eq_(batch.impl.operations.impl.mock_calls, [ mock.call.add_constraint(self.mock_schema.ForeignKeyConstraint()) ])
def test_create_fk_schema(self): with self._fixture(schema='foo') as batch: batch.create_foreign_key('myfk', 'user', ['x'], ['y']) eq_( self.mock_schema.ForeignKeyConstraint.mock_calls, [ mock.call( ['x'], ['user.y'], onupdate=None, ondelete=None, name='myfk', initially=None, deferrable=None, match=None) ] ) eq_( self.mock_schema.Table.mock_calls, [ mock.call( 'user', self.mock_schema.MetaData(), self.mock_schema.Column(), schema=None ), mock.call( 'tname', self.mock_schema.MetaData(), self.mock_schema.Column(), schema='foo' ), mock.call().append_constraint( self.mock_schema.ForeignKeyConstraint()) ] ) eq_( batch.impl.operations.impl.mock_calls, [mock.call.add_constraint( self.mock_schema.ForeignKeyConstraint())] )
def test_add_foreign_key_dialect_kw(self): op_fixture() with mock.patch("sqlalchemy.schema.ForeignKeyConstraint") as fkc: op.create_foreign_key('fk_test', 't1', 't2', ['foo', 'bar'], ['bat', 'hoho'], foobar_arg='xyz') if config.requirements.foreign_key_match.enabled: eq_( fkc.mock_calls[0], mock.call(['foo', 'bar'], ['t2.bat', 't2.hoho'], onupdate=None, ondelete=None, name='fk_test', foobar_arg='xyz', deferrable=None, initially=None, match=None)) else: eq_( fkc.mock_calls[0], mock.call(['foo', 'bar'], ['t2.bat', 't2.hoho'], onupdate=None, ondelete=None, name='fk_test', foobar_arg='xyz', deferrable=None, initially=None))
def test_all_traverse(self): writer = autogenerate.Rewriter() mocker = mock.Mock(side_effect=lambda context, revision, op: op) writer.rewrites(ops.MigrateOperation)(mocker) addcolop = ops.AddColumnOp('t1', sa.Column('x', sa.Integer())) directives = [ ops.MigrationScript( util.rev_id(), ops.UpgradeOps(ops=[ops.ModifyTableOps('t1', ops=[addcolop])]), ops.DowngradeOps(ops=[]), ) ] ctx, rev = mock.Mock(), mock.Mock() writer(ctx, rev, directives) eq_(mocker.mock_calls, [ mock.call(ctx, rev, directives[0]), mock.call(ctx, rev, directives[0].upgrade_ops), mock.call(ctx, rev, directives[0].upgrade_ops.ops[0]), mock.call(ctx, rev, addcolop), mock.call(ctx, rev, directives[0].downgrade_ops), ])
def test_create_uq(self): with self._fixture() as batch: batch.create_unique_constraint('uq1', ['a', 'b']) eq_(self.mock_schema.Table().c.__getitem__.mock_calls, [mock.call('a'), mock.call('b')]) eq_(self.mock_schema.UniqueConstraint.mock_calls, [ mock.call(self.mock_schema.Table().c.__getitem__(), self.mock_schema.Table().c.__getitem__(), name='uq1') ]) eq_(batch.impl.operations.impl.mock_calls, [mock.call.add_constraint(self.mock_schema.UniqueConstraint())])
def test_create_pk(self): with self._fixture() as batch: batch.create_primary_key('pk1', ['a', 'b']) eq_(self.mock_schema.Table().c.__getitem__.mock_calls, [mock.call('a'), mock.call('b')]) eq_(self.mock_schema.PrimaryKeyConstraint.mock_calls, [ mock.call(self.mock_schema.Table().c.__getitem__(), self.mock_schema.Table().c.__getitem__(), name='pk1') ]) eq_(batch.impl.operations.impl.mock_calls, [ mock.call.add_constraint(self.mock_schema.PrimaryKeyConstraint()) ])
def test_console_scripts(self): self.cfg = _no_sql_testing_config( directives=("\n[post_write_hooks]\n" "hooks=black\n" "black.type=console_scripts\n" "black.entrypoint=black\n" "black.options=-l 79\n")) impl = mock.Mock(attrs=("foo", "bar"), module_name="black_module") entrypoints = mock.Mock(return_value=iter([impl])) with mock.patch("pkg_resources.iter_entry_points", entrypoints), mock.patch( "alembic.script.write_hooks.subprocess" ) as mock_subprocess: rev = command.revision(self.cfg, message="x") eq_(entrypoints.mock_calls, [mock.call("console_scripts", "black")]) eq_( mock_subprocess.mock_calls, [ mock.call.run([ sys.executable, "-c", "import black_module; black_module.foo.bar()", rev.path, "-l", "79", ]) ], )
def test_cant_change_computed_warning(self, test_case): arg_before, arg_after = testing.resolve_lambda(test_case, **locals()) m1 = MetaData() m2 = MetaData() arg_before = [] if arg_before is None else [arg_before] arg_after = [] if arg_after is None else [arg_after] Table( "user", m1, Column("id", Integer, primary_key=True), Column("bar", Integer), Column("foo", Integer, *arg_before), ) Table( "user", m2, Column("id", Integer, primary_key=True), Column("bar", Integer), Column("foo", Integer, *arg_after), ) with mock.patch("alembic.util.warn") as mock_warn: diffs = self._fixture(m1, m2) eq_( mock_warn.mock_calls, [mock.call("Computed default on user.foo cannot be modified")], ) eq_(list(diffs), [])
def _run_black_with_config(self, input_config, expected_additional_arguments_fn, cwd=None): self.cfg = _no_sql_testing_config(directives=input_config) impl = mock.Mock(attrs=("foo", "bar"), module_name="black_module") entrypoints = mock.Mock(return_value=iter([impl])) with mock.patch("pkg_resources.iter_entry_points", entrypoints), mock.patch( "alembic.script.write_hooks.subprocess" ) as mock_subprocess: rev = command.revision(self.cfg, message="x") eq_(entrypoints.mock_calls, [mock.call("console_scripts", "black")]) eq_( mock_subprocess.mock_calls, [ mock.call.run( [ sys.executable, "-c", "import black_module; black_module.foo.bar()", ] + expected_additional_arguments_fn(rev.path), cwd=cwd, ) ], )
def test_init_file_exists_and_is_empty(self): def access_(path, mode): if "generic" in path or path == "foobar": return True else: return False def listdir_(path): if path == "foobar": return [] else: return ["file1", "file2", "alembic.ini.mako"] with mock.patch( "alembic.command.os.access", side_effect=access_ ), mock.patch("alembic.command.os.makedirs") as makedirs, mock.patch( "alembic.command.os.listdir", side_effect=listdir_ ), mock.patch( "alembic.command.ScriptDirectory" ): command.init(self.cfg, directory="foobar") eq_( makedirs.mock_calls, [mock.call(os.path.normpath("foobar/versions"))], )
def _run_black_with_config(self, input_config, expected_additional_arguments_fn, cwd=None): self.cfg = _no_sql_testing_config(directives=input_config) class MocksCantName: name = "black" attr = "bar" module = "black_module.foo" importlib_metadata_get = mock.Mock(return_value=iter([MocksCantName])) with mock.patch( "alembic.util.compat.importlib_metadata_get", importlib_metadata_get, ), mock.patch( "alembic.script.write_hooks.subprocess") as mock_subprocess: rev = command.revision(self.cfg, message="x") eq_(importlib_metadata_get.mock_calls, [mock.call("console_scripts")]) eq_( mock_subprocess.mock_calls, [ mock.call.run( [ sys.executable, "-c", "import black_module.foo; black_module.foo.bar()", ] + expected_additional_arguments_fn(rev.path), cwd=cwd, ) ], )
def test_run_cmd_args_missing(self): canary = mock.Mock() orig_revision = command.revision # the command function has "process_revision_directives" # however the ArgumentParser does not. ensure things work def revision( config, message=None, autogenerate=False, sql=False, head="head", splice=False, branch_label=None, version_path=None, rev_id=None, depends_on=None, process_revision_directives=None, ): canary(config, message=message) revision.__module__ = "alembic.command" # CommandLine() pulls the function into the ArgumentParser # and needs the full signature, so we can't patch the "revision" # command normally as ArgumentParser gives us no way to get to it. config.command.revision = revision try: commandline = config.CommandLine() options = commandline.parser.parse_args(["revision", "-m", "foo"]) commandline.run_cmd(self.cfg, options) finally: config.command.revision = orig_revision eq_(canary.mock_calls, [mock.call(self.cfg, message="foo")])
def test_drop_constraint(self): with self._fixture() as batch: batch.drop_constraint('uq1') eq_(self.mock_schema.Constraint.mock_calls, [mock.call(name='uq1')]) eq_(batch.impl.operations.impl.mock_calls, [mock.call.drop_constraint(self.mock_schema.Constraint())])
def test_init_file_doesnt_exist(self): def access_(path, mode): if "generic" in path: return True else: return False with mock.patch( "alembic.command.os.access", side_effect=access_), mock.patch( "alembic.command.os.makedirs") as makedirs, mock.patch( "alembic.command.ScriptDirectory"): command.init(self.cfg, directory="foobar") eq_( makedirs.mock_calls, [mock.call("foobar"), mock.call("foobar/versions")], )
def test_create_check(self): expr = text("a > b") with self._fixture() as batch: batch.create_check_constraint('ck1', expr) eq_(self.mock_schema.CheckConstraint.mock_calls, [mock.call(expr, name="ck1")]) eq_(batch.impl.operations.impl.mock_calls, [mock.call.add_constraint(self.mock_schema.CheckConstraint())])
def test_add_foreign_key_dialect_kw(self): op_fixture() with mock.patch( "alembic.operations.sa_schema.ForeignKeyConstraint") as fkc: op.create_foreign_key('fk_test', 't1', 't2', ['foo', 'bar'], ['bat', 'hoho'], foobar_arg='xyz') if config.requirements.foreign_key_match.enabled: eq_(fkc.mock_calls[0], mock.call(['foo', 'bar'], ['t2.bat', 't2.hoho'], onupdate=None, ondelete=None, name='fk_test', foobar_arg='xyz', deferrable=None, initially=None, match=None)) else: eq_(fkc.mock_calls[0], mock.call(['foo', 'bar'], ['t2.bat', 't2.hoho'], onupdate=None, ondelete=None, name='fk_test', foobar_arg='xyz', deferrable=None, initially=None))
def test_generic(self): hook1 = mock.Mock() hook2 = mock.Mock() write_hooks.register("hook1")(hook1) write_hooks.register("hook2")(hook2) self.cfg = _no_sql_testing_config(directives=("\n[post_write_hooks]\n" "hooks=hook1,hook2\n" "hook1.type=hook1\n" "hook1.arg1=foo\n" "hook2.type=hook2\n" "hook2.arg1=bar\n")) rev = command.revision(self.cfg, message="x") eq_( hook1.mock_calls, [ mock.call( rev.path, { "type": "hook1", "arg1": "foo", "_hook_name": "hook1" }, ) ], ) eq_( hook2.mock_calls, [ mock.call( rev.path, { "type": "hook2", "arg1": "bar", "_hook_name": "hook2" }, ) ], )
def test_init_w_package(self): path = os.path.join(_get_staging_directory(), "foobar") with mock.patch("alembic.command.open") as open_: command.init(self.cfg, directory=path, package=True) eq_( open_.mock_calls, [ mock.call( os.path.abspath(os.path.join(path, "__init__.py")), "w"), mock.call().close(), mock.call( os.path.abspath( os.path.join(path, "versions", "__init__.py")), "w", ), mock.call().close(), ], )
def test_init_file_doesnt_exist(self): def access_(path, mode): if "generic" in path: return True else: return False template_dir = self.cfg.get_template_directory() with mock.patch( "alembic.command.os.access", side_effect=access_ ) as access, mock.patch( "alembic.command.os.makedirs" ) as makedirs, mock.patch( "alembic.command.ScriptDirectory" ): command.init(self.cfg, directory="foobar") eq_( access.mock_calls, [ mock.call("foobar", os.F_OK), mock.call(os.path.join(template_dir, "generic"), os.F_OK), mock.call("foobar", os.F_OK), mock.call( os.path.abspath("./scratch/test_alembic.ini"), os.F_OK ), ], ) eq_( makedirs.mock_calls, [mock.call("foobar"), mock.call("foobar/versions")], )
def test_add_foreign_key_dialect_kw(self): op_fixture() with mock.patch("sqlalchemy.schema.ForeignKeyConstraint") as fkc: op.create_foreign_key( "fk_test", "t1", "t2", ["foo", "bar"], ["bat", "hoho"], foobar_arg="xyz", ) if config.requirements.foreign_key_match.enabled: eq_( fkc.mock_calls[0], mock.call( ["foo", "bar"], ["t2.bat", "t2.hoho"], onupdate=None, ondelete=None, name="fk_test", foobar_arg="xyz", deferrable=None, initially=None, match=None, ), ) else: eq_( fkc.mock_calls[0], mock.call( ["foo", "bar"], ["t2.bat", "t2.hoho"], onupdate=None, ondelete=None, name="fk_test", foobar_arg="xyz", deferrable=None, initially=None, ), )
def test_drop_constraint(self): with self._fixture() as batch: batch.drop_constraint('uq1') eq_( self.mock_schema.Constraint.mock_calls, [ mock.call(name='uq1') ] ) eq_( batch.impl.operations.impl.mock_calls, [mock.call.drop_constraint(self.mock_schema.Constraint())] )
def test_create_pk(self): with self._fixture() as batch: batch.create_primary_key('pk1', ['a', 'b']) eq_( self.mock_schema.Table().c.__getitem__.mock_calls, [mock.call('a'), mock.call('b')] ) eq_( self.mock_schema.PrimaryKeyConstraint.mock_calls, [ mock.call( self.mock_schema.Table().c.__getitem__(), self.mock_schema.Table().c.__getitem__(), name='pk1' ) ] ) eq_( batch.impl.operations.impl.mock_calls, [mock.call.add_constraint( self.mock_schema.PrimaryKeyConstraint())] )
def test_create_uq(self): with self._fixture() as batch: batch.create_unique_constraint('uq1', ['a', 'b']) eq_( self.mock_schema.Table().c.__getitem__.mock_calls, [mock.call('a'), mock.call('b')] ) eq_( self.mock_schema.UniqueConstraint.mock_calls, [ mock.call( self.mock_schema.Table().c.__getitem__(), self.mock_schema.Table().c.__getitem__(), name='uq1' ) ] ) eq_( batch.impl.operations.impl.mock_calls, [mock.call.add_constraint( self.mock_schema.UniqueConstraint())] )
def test_create_fk(self): with self._fixture() as batch: batch.create_foreign_key('myfk', 'user', ['x'], ['y']) eq_(self.mock_schema.ForeignKeyConstraint.mock_calls, [ mock.call(['x'], ['user.y'], onupdate=None, ondelete=None, name='myfk', initially=None, deferrable=None, match=None, schema=None) ]) eq_(batch.impl.operations.impl.mock_calls, [ mock.call.add_constraint(self.mock_schema.ForeignKeyConstraint()) ])
def test_warning_on_passing_engine(self): env = self._fixture() engine = _sqlite_file_db() a_rev = "arev" env.script.generate_revision(a_rev, "revision a", refresh=True) write_script( env.script, a_rev, """\ "Rev A" revision = '%s' down_revision = None from alembic import op def upgrade(): pass def downgrade(): pass """ % a_rev, ) migration_fn = mock.MagicMock() def upgrade(rev, context): migration_fn(rev, context) return env.script._upgrade_revs(a_rev, rev) with expect_warnings( r"'connection' argument to configure\(\) is " r"expected to be a sqlalchemy.engine.Connection " ): env.configure( connection=engine, fn=upgrade, transactional_ddl=False ) env.run_migrations() eq_(migration_fn.mock_calls, [mock.call((), env._migration_context)])
def test_warning_on_passing_engine(self): env = self._fixture() engine = _sqlite_file_db() a_rev = "arev" env.script.generate_revision(a_rev, "revision a", refresh=True) write_script( env.script, a_rev, """\ "Rev A" revision = '%s' down_revision = None from alembic import op def upgrade(): pass def downgrade(): pass """ % a_rev, ) migration_fn = MagicMock() def upgrade(rev, context): migration_fn(rev, context) return env.script._upgrade_revs(a_rev, rev) with expect_warnings( r"'connection' argument to configure\(\) is " r"expected to be a sqlalchemy.engine.Connection " ): env.configure( connection=engine, fn=upgrade, transactional_ddl=False ) env.run_migrations() eq_(migration_fn.mock_calls, [call((), env._migration_context)])
def test_create_check(self): expr = text("a > b") with self._fixture() as batch: batch.create_check_constraint('ck1', expr) eq_( self.mock_schema.CheckConstraint.mock_calls, [ mock.call( expr, name="ck1" ) ] ) eq_( batch.impl.operations.impl.mock_calls, [mock.call.add_constraint( self.mock_schema.CheckConstraint())] )
def _run_black_with_config( self, input_config, expected_additional_arguments_fn, cwd=None ): self.cfg = _no_sql_testing_config(directives=input_config) retVal = [ compat.EntryPoint( name="black", value="black.foo:patched_main", group="console_scripts", ), compat.EntryPoint( name="alembic", value="alembic.config:main", group="console_scripts", ), ] importlib_metadata_get = mock.Mock(return_value=retVal) with mock.patch( "alembic.util.compat.importlib_metadata_get", importlib_metadata_get, ), mock.patch( "alembic.script.write_hooks.subprocess" ) as mock_subprocess: rev = command.revision(self.cfg, message="x") eq_(importlib_metadata_get.mock_calls, [mock.call("console_scripts")]) eq_( mock_subprocess.mock_calls, [ mock.call.run( [ sys.executable, "-c", "import black.foo; black.foo.patched_main()", ] + expected_additional_arguments_fn(rev.path), cwd=cwd, ) ], )
def test_create_fk(self): with self._fixture() as batch: batch.create_foreign_key('myfk', 'user', ['x'], ['y']) eq_( self.mock_schema.ForeignKeyConstraint.mock_calls, [ mock.call( ['x'], ['user.y'], onupdate=None, ondelete=None, name='myfk', initially=None, deferrable=None, match=None, schema=None) ] ) eq_( batch.impl.operations.impl.mock_calls, [mock.call.add_constraint( self.mock_schema.ForeignKeyConstraint())] )
def test_init_file_exists_and_is_empty(self): def access_(path, mode): if "generic" in path or path == "foobar": return True else: return False def listdir_(path): if path == "foobar": return [] else: return ["file1", "file2", "alembic.ini.mako"] template_dir = self.cfg.get_template_directory() with mock.patch( "alembic.command.os.access", side_effect=access_ ) as access, mock.patch( "alembic.command.os.makedirs" ) as makedirs, mock.patch( "alembic.command.os.listdir", side_effect=listdir_ ) as listdir, mock.patch( "alembic.command.ScriptDirectory" ): command.init(self.cfg, directory="foobar") eq_( access.mock_calls, [ mock.call("foobar", os.F_OK), mock.call(os.path.join(template_dir, "generic"), os.F_OK), mock.call("foobar", os.F_OK), mock.call( os.path.abspath("./scratch/test_alembic.ini"), os.F_OK ), ], ) eq_( listdir.mock_calls, [ mock.call("foobar"), mock.call(os.path.join(template_dir, "generic")), ], ) eq_(makedirs.mock_calls, [mock.call("foobar/versions")])