test_migrations.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import importlib.util
  2. from pathlib import Path
  3. from unittest.mock import Mock
  4. import sqlalchemy as sa
  5. from alembic.config import Config
  6. from alembic.script import ScriptDirectory
  7. def load_core_0004():
  8. migration_path = (
  9. Path(__file__).parents[1]
  10. / "migrations/core/versions/core_0004_product_management.py"
  11. )
  12. spec = importlib.util.spec_from_file_location("core_0004_product_management", migration_path)
  13. assert spec is not None and spec.loader is not None
  14. module = importlib.util.module_from_spec(spec)
  15. spec.loader.exec_module(module)
  16. return module
  17. def test_each_database_has_the_expected_independent_migration_head() -> None:
  18. backend_dir = Path(__file__).parents[1]
  19. expected_heads = {
  20. "alembic_core": "core_0004",
  21. "alembic_agent": "agent_0001",
  22. "alembic_analytics": "analytics_0001",
  23. }
  24. for section, expected_head in expected_heads.items():
  25. config = Config(backend_dir / "alembic.ini", ini_section=section)
  26. scripts = ScriptDirectory.from_config(config)
  27. assert scripts.get_current_head() == expected_head
  28. def test_core_0004_skips_columns_that_already_exist(monkeypatch) -> None:
  29. core_0004_product_management = load_core_0004()
  30. bind = Mock()
  31. inspector = Mock()
  32. inspector.get_columns.return_value = [
  33. {"name": "premium_cents"},
  34. {"name": "min_age"},
  35. ]
  36. add_column = Mock()
  37. create_table = Mock()
  38. monkeypatch.setattr(sa, "inspect", lambda connection: inspector)
  39. monkeypatch.setattr(core_0004_product_management.op, "get_bind", lambda: bind)
  40. monkeypatch.setattr(core_0004_product_management.op, "add_column", add_column)
  41. monkeypatch.setattr(
  42. core_0004_product_management.CoreBase.metadata.tables["product_change_logs"],
  43. "create",
  44. create_table,
  45. )
  46. core_0004_product_management.upgrade()
  47. assert [call.args[1].name for call in add_column.call_args_list] == [
  48. "coverage_amount_cents",
  49. "max_age",
  50. ]
  51. create_table.assert_called_once_with(bind=bind, checkfirst=True)