test_mqtt_lifetime_energy_migration_3582.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. """Migration test for #3582 — smart_plugs.mqtt_energy_total_path / _multiplier.
  2. An existing MQTT plug has no lifetime path, so it keeps reading its one energy
  3. value as before. The added columns must come out as a fresh install builds
  4. them: the path nullable, the multiplier NOT NULL with the model's default.
  5. """
  6. from __future__ import annotations
  7. import pytest
  8. from sqlalchemy import text
  9. from sqlalchemy.ext.asyncio import create_async_engine
  10. from backend.app.core.database import load_all_models, run_migrations
  11. NEW_COLUMNS = ("mqtt_energy_total_path", "mqtt_energy_total_multiplier")
  12. @pytest.fixture(autouse=True)
  13. def force_sqlite_dialect(monkeypatch):
  14. """settings.database_url may point at Postgres in dev configs; the test engine
  15. is SQLite, so force the dialect both places run_migrations reads it from."""
  16. from backend.app.core import database as database_module, db_dialect
  17. monkeypatch.setattr(db_dialect, "is_sqlite", lambda: True)
  18. monkeypatch.setattr(db_dialect, "is_postgres", lambda: False)
  19. monkeypatch.setattr(database_module, "is_sqlite", lambda: True)
  20. async def _columns(conn) -> dict[str, tuple]:
  21. """name -> (type, notnull, default) for smart_plugs, the default unquoted."""
  22. rows = await conn.execute(text("PRAGMA table_info(smart_plugs)"))
  23. return {row[1]: (row[2], row[3], row[4] and row[4].strip("'")) for row in rows}
  24. @pytest.fixture
  25. async def fresh_engine():
  26. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  27. async with engine.begin() as conn:
  28. await conn.run_sync(load_all_models().create_all)
  29. yield engine
  30. await engine.dispose()
  31. @pytest.fixture
  32. async def legacy_engine():
  33. """A current schema whose smart_plugs predates #3582, holding one MQTT plug."""
  34. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  35. async with engine.begin() as conn:
  36. metadata = load_all_models()
  37. await conn.run_sync(metadata.create_all)
  38. await conn.execute(
  39. metadata.tables["smart_plugs"]
  40. .insert()
  41. .values(
  42. id=1,
  43. name="Tasmota MQTT",
  44. plug_type="mqtt",
  45. mqtt_energy_topic="tele/plug/SENSOR",
  46. mqtt_energy_path="ENERGY.Today",
  47. )
  48. )
  49. for column in NEW_COLUMNS:
  50. await conn.execute(text(f"ALTER TABLE smart_plugs DROP COLUMN {column}"))
  51. yield engine
  52. await engine.dispose()
  53. async def test_columns_missing_before_migration(legacy_engine):
  54. """Sanity check so the assertions below can't pass by accident."""
  55. async with legacy_engine.begin() as conn:
  56. columns = await _columns(conn)
  57. assert not set(NEW_COLUMNS) & set(columns)
  58. async def test_existing_plug_has_no_lifetime_path(legacy_engine):
  59. async with legacy_engine.begin() as conn:
  60. await run_migrations(conn)
  61. async with legacy_engine.begin() as conn:
  62. row = (
  63. await conn.execute(
  64. text("SELECT mqtt_energy_total_path, mqtt_energy_total_multiplier FROM smart_plugs WHERE id = 1")
  65. )
  66. ).one()
  67. assert tuple(row) == (None, 1.0)
  68. async def test_upgraded_columns_match_a_fresh_install(legacy_engine, fresh_engine):
  69. async with legacy_engine.begin() as conn:
  70. await run_migrations(conn)
  71. upgraded = await _columns(conn)
  72. async with fresh_engine.begin() as conn:
  73. fresh = await _columns(conn)
  74. # NOT NULL and default as a fresh install; the type name differs (REAL from
  75. # the migration, FLOAT from create_all), the REAL affinity does not.
  76. for column in NEW_COLUMNS:
  77. assert upgraded[column][1:] == fresh[column][1:], column
  78. assert upgraded["mqtt_energy_total_multiplier"][1] == 1, "the multiplier must be NOT NULL"
  79. async def test_migration_is_idempotent(legacy_engine):
  80. """A second boot must not fail on the columns already being there."""
  81. async with legacy_engine.begin() as conn:
  82. await run_migrations(conn)
  83. async with legacy_engine.begin() as conn:
  84. await run_migrations(conn)
  85. async with legacy_engine.begin() as conn:
  86. multiplier = (
  87. await conn.execute(text("SELECT mqtt_energy_total_multiplier FROM smart_plugs WHERE id = 1"))
  88. ).scalar_one()
  89. assert multiplier == 1.0