test_product_management_migration.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from importlib.util import module_from_spec, spec_from_file_location
  2. from pathlib import Path
  3. from types import ModuleType
  4. from typing import Any
  5. from sqlalchemy.schema import Table
  6. def load_migration() -> ModuleType:
  7. migration_path = (
  8. Path(__file__).resolve().parents[1]
  9. / "migrations"
  10. / "core"
  11. / "versions"
  12. / "core_0004_product_management.py"
  13. )
  14. spec = spec_from_file_location("core_0004_product_management", migration_path)
  15. if spec is None or spec.loader is None:
  16. raise RuntimeError(f"无法加载迁移文件:{migration_path}")
  17. module = module_from_spec(spec)
  18. spec.loader.exec_module(module)
  19. return module
  20. migration = load_migration()
  21. class ExistingPlansInspector:
  22. def get_columns(self, table_name: str) -> list[dict[str, str]]:
  23. assert table_name == "plans"
  24. return [
  25. {"name": "premium_cents"},
  26. {"name": "coverage_amount_cents"},
  27. {"name": "min_age"},
  28. {"name": "max_age"},
  29. ]
  30. def has_table(self, table_name: str) -> bool:
  31. assert table_name == "product_change_logs"
  32. return False
  33. def test_product_management_migration_accepts_fresh_schema_from_current_baseline(
  34. monkeypatch: Any,
  35. ) -> None:
  36. added_columns: list[str] = []
  37. created_tables: list[str] = []
  38. monkeypatch.setattr(migration.op, "get_bind", lambda: object())
  39. monkeypatch.setattr(
  40. migration.op,
  41. "add_column",
  42. lambda _table_name, column: added_columns.append(str(column.name)),
  43. )
  44. monkeypatch.setattr(
  45. Table,
  46. "create",
  47. lambda self, bind: created_tables.append(self.name),
  48. )
  49. monkeypatch.setattr(
  50. migration.sa,
  51. "inspect",
  52. lambda _bind: ExistingPlansInspector(),
  53. )
  54. migration.upgrade()
  55. assert added_columns == []
  56. assert created_tables == ["product_change_logs"]