1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
|
import io
import logging
import os
import pathlib
import sys
import tempfile
from alembic import command
from alembic import config
from alembic import testing
from alembic import util
from alembic.migration import MigrationContext
from alembic.operations import Operations
from alembic.script import ScriptDirectory
from alembic.testing import assert_raises_message
from alembic.testing import eq_
from alembic.testing import mock
from alembic.testing.assertions import expect_raises_message
from alembic.testing.env import _get_staging_directory
from alembic.testing.env import _no_sql_testing_config
from alembic.testing.env import _testing_config
from alembic.testing.env import _write_config_file
from alembic.testing.env import clear_staging_env
from alembic.testing.env import staging_env
from alembic.testing.fixtures import capture_db
from alembic.testing.fixtures import TestBase
class FileConfigTest(TestBase):
def test_config_args(self):
cfg = _write_config_file(
"""
[alembic]
migrations = %(base_path)s/db/migrations
"""
)
test_cfg = config.Config(
cfg.config_file_name, config_args=dict(base_path="/home/alembic")
)
eq_(
test_cfg.get_section_option("alembic", "migrations"),
"/home/alembic/db/migrations",
)
def tearDown(self):
clear_staging_env()
class ConfigTest(TestBase):
def test_config_logging_with_file(self):
buf = io.StringIO()
handler = logging.StreamHandler(buf)
handler.setLevel(logging.INFO)
logger = logging.getLogger("alembic.config")
# logger.x=True
with (
mock.patch.object(logger, "handlers", []),
mock.patch.object(logger, "level", logging.NOTSET),
):
logger.addHandler(handler)
logger.setLevel(logging.INFO)
cfg = _write_config_file(
"""
[alembic]
script_location = %(base_path)s/db/migrations
"""
)
test_cfg = config.Config(
cfg.config_file_name, config_args=dict(base_path="/tmp")
)
test_cfg.cmd_opts = mock.Mock(verbose=True)
_ = test_cfg.file_config
output = buf.getvalue()
assert "Loading config from file" in output
assert cfg.config_file_name.replace("/", os.path.sep) in output
def tearDown(self):
clear_staging_env()
def test_config_logging_without_file(self):
buf = io.StringIO()
handler = logging.StreamHandler(buf)
handler.setLevel(logging.INFO)
logger = logging.getLogger("alembic.config")
with (
mock.patch.object(logger, "handlers", []),
mock.patch.object(logger, "level", logging.NOTSET),
):
logger.addHandler(handler)
logger.setLevel(logging.INFO)
test_cfg = config.Config()
test_cfg.cmd_opts = mock.Mock(verbose=True)
_ = test_cfg.file_config
output = buf.getvalue()
assert "No config file provided" in output
assert (
test_cfg.config_file_name is None
and test_cfg._config_file_path is None
)
def test_config_no_file_main_option(self):
cfg = config.Config()
cfg.set_main_option("url", "postgresql://foo/bar")
eq_(cfg.get_main_option("url"), "postgresql://foo/bar")
def test_config_no_file_section_option(self):
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")
def test_config_set_main_option_percent(self):
cfg = config.Config()
cfg.set_main_option("foob", "a %% percent")
eq_(cfg.get_main_option("foob"), "a % percent")
def test_config_set_section_option_percent(self):
cfg = config.Config()
cfg.set_section_option("some_section", "foob", "a %% percent")
eq_(cfg.get_section_option("some_section", "foob"), "a % percent")
def test_config_set_section_option_interpolation(self):
cfg = config.Config()
cfg.set_section_option("some_section", "foob", "foob_value")
cfg.set_section_option("some_section", "bar", "bar with %(foob)s")
eq_(
cfg.get_section_option("some_section", "bar"),
"bar with foob_value",
)
def test_standalone_op(self):
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"])
def test_no_script_error(self):
cfg = config.Config()
assert_raises_message(
util.CommandError,
"No 'script_location' key found in configuration.",
ScriptDirectory.from_config,
cfg,
)
def test_attributes_attr(self):
m1 = mock.Mock()
cfg = config.Config()
cfg.attributes["connection"] = m1
eq_(cfg.attributes["connection"], m1)
def test_attributes_constructor(self):
m1 = mock.Mock()
m2 = mock.Mock()
cfg = config.Config(attributes={"m1": m1})
cfg.attributes["connection"] = m2
eq_(cfg.attributes, {"m1": m1, "connection": m2})
@testing.combinations(
(
"legacy raw string 1",
None,
"/foo",
["/foo"],
),
(
"legacy raw string 2",
None,
"/foo /bar",
["/foo", "/bar"],
),
(
"legacy raw string 3",
"space",
"/foo",
["/foo"],
),
(
"legacy raw string 4",
"space",
"/foo /bar",
["/foo", "/bar"],
),
(
"multiline string 1",
"newline",
" /foo \n/bar ",
["/foo", "/bar"],
),
(
"Linux pathsep 1",
":",
"/Project A",
["/Project A"],
),
(
"Linux pathsep 2",
":",
"/Project A:/Project B",
["/Project A", "/Project B"],
),
(
"Windows pathsep 1",
";",
r"C:\Project A",
[r"C:\Project A"],
),
(
"Windows pathsep 2",
";",
r"C:\Project A;C:\Project B",
[r"C:\Project A", r"C:\Project B"],
),
(
"os pathsep",
"os",
r"path_number_one%(sep)spath_number_two%(sep)s"
% {"sep": os.pathsep},
[r"path_number_one", r"path_number_two"],
),
(
"invalid pathsep 2",
"|",
"/foo|/bar",
ValueError(
"'|' is not a valid value for path_separator; "
"expected 'space', 'newline', 'os', ':', ';'"
),
),
id_="iaaa",
argnames="separator, string_value, expected_result",
)
def test_version_locations(self, separator, string_value, expected_result):
cfg = config.Config()
if separator is not None:
cfg.set_main_option(
"path_separator",
separator,
)
cfg.set_main_option("script_location", tempfile.gettempdir())
cfg.set_main_option("version_locations", string_value)
if isinstance(expected_result, ValueError):
message = str(expected_result)
with expect_raises_message(ValueError, message, text_exact=True):
ScriptDirectory.from_config(cfg)
else:
if separator is None:
with testing.expect_deprecated(
"No path_separator found in configuration; "
"falling back to legacy splitting on spaces/commas "
"for version_locations"
):
s = ScriptDirectory.from_config(cfg)
else:
s = ScriptDirectory.from_config(cfg)
eq_(s.version_locations, expected_result)
@testing.combinations(
(
"legacy raw string 1",
None,
"/foo",
["/foo"],
),
(
"legacy raw string 2",
None,
"/foo /bar",
["/foo", "/bar"],
),
(
"legacy raw string 3",
"space",
"/foo",
["/foo"],
),
(
"legacy raw string 4",
"space",
"/foo /bar",
["/foo", "/bar"],
),
(
"multiline string 1",
"newline",
" /foo \n/bar ",
["/foo", "/bar"],
),
(
"Linux pathsep 1",
":",
"/Project A",
["/Project A"],
),
(
"Linux pathsep 2",
":",
"/Project A:/Project B",
["/Project A", "/Project B"],
),
(
"Windows pathsep 1",
";",
r"C:\Project A",
[r"C:\Project A"],
),
(
"Windows pathsep 2",
";",
r"C:\Project A;C:\Project B",
[r"C:\Project A", r"C:\Project B"],
),
(
"os pathsep",
"os",
r"path_number_one%(sep)spath_number_two%(sep)s"
% {"sep": os.pathsep},
[r"path_number_one", r"path_number_two"],
),
(
"invalid pathsep 2",
"|",
"/foo|/bar",
ValueError(
"'|' is not a valid value for path_separator; "
"expected 'space', 'newline', 'os', ':', ';'"
),
),
id_="iaaa",
argnames="separator, string_value, expected_result",
)
def test_prepend_sys_path_locations(
self, separator, string_value, expected_result
):
cfg = config.Config()
if separator is not None:
cfg.set_main_option(
"path_separator",
separator,
)
cfg.set_main_option("script_location", tempfile.gettempdir())
cfg.set_main_option("prepend_sys_path", string_value)
if isinstance(expected_result, ValueError):
message = str(expected_result)
with expect_raises_message(ValueError, message, text_exact=True):
ScriptDirectory.from_config(cfg)
else:
restore_path = list(sys.path)
try:
sys.path.clear()
if separator is None:
with testing.expect_deprecated(
"No path_separator found in configuration; "
"falling back to legacy splitting on spaces, commas, "
"and colons for prepend_sys_path"
):
ScriptDirectory.from_config(cfg)
else:
ScriptDirectory.from_config(cfg)
eq_(sys.path, expected_result)
finally:
sys.path = restore_path
def test_version_path_separator_deprecation_warning(self):
cfg = config.Config()
cfg.set_main_option("script_location", tempfile.gettempdir())
cfg.set_main_option("version_path_separator", "space")
cfg.set_main_option(
"version_locations", "/path/one /path/two /path:/three"
)
with testing.expect_deprecated(
"The version_path_separator configuration parameter is "
"deprecated; please use path_separator"
):
script = ScriptDirectory.from_config(cfg)
eq_(
script.version_locations,
["/path/one", "/path/two", "/path:/three"],
)
class PyprojectConfigTest(TestBase):
@testing.fixture
def pyproject_only_env(self):
cfg = _testing_config()
path = pathlib.Path(_get_staging_directory(), "scripts")
command.init(cfg, str(path), template="pyproject")
cfg._config_file_path.unlink()
yield cfg
clear_staging_env()
def test_revision_command_no_alembicini(self, pyproject_only_env):
cfg = pyproject_only_env
path = pathlib.Path(_get_staging_directory(), "scripts")
pyproject_path = path.parent / "pyproject.toml"
eq_(pyproject_path, cfg._toml_file_path)
assert pyproject_path.exists()
assert not cfg._config_file_path.exists()
# the cfg contains the path to alembic.ini but the file
# is not present. the idea here is that all the required config
# should go to pyproject.toml first before raising.
ScriptDirectory.from_config(cfg)
command.revision(cfg, message="x")
command.history(cfg)
def test_no_config_at_all_still_raises(self, pyproject_only_env):
cfg = pyproject_only_env
cfg._toml_file_path.unlink()
assert not cfg._toml_file_path.exists()
assert not cfg._config_file_path.exists()
with expect_raises_message(
util.CommandError,
r"No 'script_location' key found in configuration.",
):
ScriptDirectory.from_config(cfg)
def test_get_main_option_raises(self, pyproject_only_env):
cfg = pyproject_only_env
with expect_raises_message(
util.CommandError,
r"No config file '.*test_alembic.ini' found, "
r"or file has no '\[alembic\]' section",
):
cfg.get_main_option("asdf")
def test_get_main_ini_added(self, pyproject_only_env):
cfg = pyproject_only_env
with cfg._config_file_path.open("w") as file_:
file_.write("[alembic]\nasdf = back_at_ya")
eq_(cfg.get_main_option("asdf"), "back_at_ya")
def test_script_location(self, pyproject_only_env):
cfg = pyproject_only_env
with cfg._toml_file_path.open("wb") as file_:
file_.write(
rb"""
[tool.alembic]
script_location = "%(here)s/scripts"
"""
)
new_cfg = config.Config(
file_=cfg.config_file_name, toml_file=cfg._toml_file_path
)
sd = ScriptDirectory.from_config(new_cfg)
eq_(
pathlib.Path(sd.dir),
pathlib.Path(_get_staging_directory(), "scripts").absolute(),
)
def test_version_locations(self, pyproject_only_env):
cfg = pyproject_only_env
with cfg._toml_file_path.open("ba") as file_:
file_.write(
b"""
version_locations = [
"%(here)s/foo/bar"
]
"""
)
if "toml_alembic_config" in cfg.__dict__:
cfg.__dict__.pop("toml_alembic_config")
eq_(
cfg.get_version_locations_list(),
[
pathlib.Path(_get_staging_directory(), "foo/bar")
.absolute()
.as_posix()
],
)
def test_prepend_sys_path(self, pyproject_only_env):
cfg = pyproject_only_env
with cfg._toml_file_path.open("wb") as file_:
file_.write(
rb"""
[tool.alembic]
script_location = "%(here)s/scripts"
prepend_sys_path = [
".",
"%(here)s/path/to/python",
"c:\\some\\path"
]
"""
)
if "toml_alembic_config" in cfg.__dict__:
cfg.__dict__.pop("toml_alembic_config")
eq_(
cfg.get_prepend_sys_paths_list(),
[
".",
pathlib.Path(_get_staging_directory(), "path/to/python")
.absolute()
.as_posix(),
r"c:\some\path",
],
)
def test_write_hooks(self, pyproject_only_env):
cfg = pyproject_only_env
with cfg._toml_file_path.open("wb") as file_:
file_.write(
rb"""
[tool.alembic]
script_location = "%(here)s/scripts"
[[tool.alembic.post_write_hooks]]
name = "myhook"
type = "exec"
executable = "%(here)s/.venv/bin/ruff"
options = "-l 79 REVISION_SCRIPT_FILENAME"
"""
)
if "toml_alembic_config" in cfg.__dict__:
cfg.__dict__.pop("toml_alembic_config")
eq_(
cfg.get_hooks_list(),
[
{
"type": "exec",
"executable": (
cfg._toml_file_path.absolute().parent
/ ".venv/bin/ruff"
).as_posix(),
"options": "-l 79 REVISION_SCRIPT_FILENAME",
"_hook_name": "myhook",
}
],
)
def test_string_list(self, pyproject_only_env):
cfg = pyproject_only_env
with cfg._toml_file_path.open("wb") as file_:
file_.write(
rb"""
[tool.alembic]
script_location = "%(here)s/scripts"
my_list = [
"one",
"two %(here)s three"
]
"""
)
if "toml_alembic_config" in cfg.__dict__:
cfg.__dict__.pop("toml_alembic_config")
eq_(
cfg.get_alembic_option("my_list"),
[
"one",
f"two {cfg._toml_file_path.absolute().parent.as_posix()} "
"three",
],
)
@testing.combinations(
"sourceless", "recursive_version_locations", argnames="paramname"
)
@testing.variation("argtype", ["true", "false", "omit", "wrongvalue"])
def test_bool(
self, pyproject_only_env, argtype: testing.Variation, paramname
):
cfg = pyproject_only_env
with cfg._toml_file_path.open("w") as file_:
if argtype.true:
config_option = f"{paramname} = true"
elif argtype.false:
config_option = f"{paramname} = false"
elif argtype.omit:
config_option = ""
elif argtype.wrongvalue:
config_option = f"{paramname} = 'false'"
else:
argtype.fail()
file_.write(
rf"""
[tool.alembic]
script_location = "%(here)s/scripts"
{config_option}
"""
)
if "toml_alembic_config" in cfg.__dict__:
cfg.__dict__.pop("toml_alembic_config")
if argtype.wrongvalue:
with expect_raises_message(
util.CommandError,
f"boolean value expected for TOML parameter '{paramname}'",
):
sd = ScriptDirectory.from_config(cfg)
else:
sd = ScriptDirectory.from_config(cfg)
eq_(getattr(sd, paramname), bool(argtype.true))
@testing.variation(
"arg_type", ["int", "string_int", "omit", "wrong_value"]
)
def test_truncate_slug_length_types(
self, pyproject_only_env, arg_type: testing.Variation
):
param_name = "truncate_slug_length"
cfg = pyproject_only_env
with cfg._toml_file_path.open("w") as file_:
if arg_type.int:
config_option = f"{param_name} = 42"
elif arg_type.string_int:
config_option = f"{param_name} = '42'"
elif arg_type.omit:
config_option = ""
elif arg_type.wrong_value:
config_option = f"{param_name} = 'wrong_value'"
else:
arg_type.fail()
file_.write(
rf"""
[tool.alembic]
script_location = "%(here)s/scripts"
{config_option}
"""
)
if "toml_alembic_config" in cfg.__dict__:
cfg.__dict__.pop("toml_alembic_config")
if arg_type.wrong_value:
with expect_raises_message(
ValueError,
"invalid literal for int() with base 10: 'wrong_value'",
text_exact=True,
):
sd = ScriptDirectory.from_config(cfg)
elif arg_type.omit:
sd = ScriptDirectory.from_config(cfg)
DEFAULT_TRUNCATE_SLUG_LENGTH = 40
eq_(getattr(sd, param_name), DEFAULT_TRUNCATE_SLUG_LENGTH)
else:
sd = ScriptDirectory.from_config(cfg)
eq_(getattr(sd, param_name), 42)
class StdoutOutputEncodingTest(TestBase):
def test_plain(self):
stdout = mock.Mock(encoding="latin-1")
cfg = config.Config(stdout=stdout)
cfg.print_stdout("test %s %s", "x", "y")
eq_(
stdout.mock_calls,
[mock.call.write("test x y"), mock.call.write("\n")],
)
def test_utf8_unicode(self):
stdout = mock.Mock(encoding="latin-1")
cfg = config.Config(stdout=stdout)
cfg.print_stdout("méil %s %s", "x", "y")
eq_(
stdout.mock_calls,
[mock.call.write("méil x y"), mock.call.write("\n")],
)
def test_ascii_unicode(self):
stdout = mock.Mock(encoding=None)
cfg = config.Config(stdout=stdout)
cfg.print_stdout("méil %s %s", "x", "y")
eq_(
stdout.mock_calls,
[mock.call.write("m?il x y"), mock.call.write("\n")],
)
def test_only_formats_output_with_args(self):
stdout = mock.Mock(encoding=None)
cfg = config.Config(stdout=stdout)
cfg.print_stdout("test 3%")
eq_(
stdout.mock_calls,
[mock.call.write("test 3%"), mock.call.write("\n")],
)
class TemplateOutputEncodingTest(TestBase):
def setUp(self):
staging_env()
self.cfg = _no_sql_testing_config()
def tearDown(self):
clear_staging_env()
def test_default(self):
script = ScriptDirectory.from_config(self.cfg)
eq_(script.output_encoding, "utf-8")
def test_setting(self):
self.cfg.set_main_option("output_encoding", "latin-1")
script = ScriptDirectory.from_config(self.cfg)
eq_(script.output_encoding, "latin-1")
class CommandLineTest(TestBase):
def test_register_command(self):
cli = config.CommandLine()
fake_stdout = []
def frobnicate(config: config.Config, revision: str) -> None:
"""Frobnicates the revision.
:param config: a :class:`.Config` instance
:param revision: the revision to frobnicate
"""
fake_stdout.append(f"Revision {revision} frobnicated.")
cli.register_command(frobnicate)
help_text = cli.parser.format_help()
assert frobnicate.__name__ in help_text
assert frobnicate.__doc__.split("\n")[0] in help_text
cli.main(["frobnicate", "abc42"])
assert fake_stdout == ["Revision abc42 frobnicated."]
|