test_smart_plug_temp_source_migration_3464.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. """Migration test for #3464 — smart_plugs.off_temp_source / off_bed_temp_threshold.
  2. An existing plug in temperature mode waited for the nozzle only. The upgrade
  3. must keep it doing so (source "nozzle"), and the added columns must come out
  4. as a fresh install builds them: NOT NULL, with the model's defaults.
  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 = ("off_temp_source", "off_bed_temp_threshold")
  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 is unquoted:
  22. create_all writes an integer server default as '35', the migration as 35."""
  23. rows = await conn.execute(text("PRAGMA table_info(smart_plugs)"))
  24. return {row[1]: (row[2], row[3], row[4] and row[4].strip("'")) for row in rows}
  25. @pytest.fixture
  26. async def fresh_engine():
  27. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  28. async with engine.begin() as conn:
  29. await conn.run_sync(load_all_models().create_all)
  30. yield engine
  31. await engine.dispose()
  32. @pytest.fixture
  33. async def legacy_engine():
  34. """A current schema whose smart_plugs predates #3464, holding one temp-mode plug."""
  35. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  36. async with engine.begin() as conn:
  37. metadata = load_all_models()
  38. await conn.run_sync(metadata.create_all)
  39. # Through the table, which fills in the model's Python-side defaults.
  40. await conn.execute(
  41. metadata.tables["smart_plugs"]
  42. .insert()
  43. .values(id=1, name="P1S Power", plug_type="tasmota", off_delay_mode="temperature", off_temp_threshold=60)
  44. )
  45. for column in NEW_COLUMNS:
  46. await conn.execute(text(f"ALTER TABLE smart_plugs DROP COLUMN {column}"))
  47. yield engine
  48. await engine.dispose()
  49. async def test_columns_missing_before_migration(legacy_engine):
  50. """Sanity check so the assertions below can't pass by accident."""
  51. async with legacy_engine.begin() as conn:
  52. columns = await _columns(conn)
  53. assert not set(NEW_COLUMNS) & set(columns)
  54. async def test_existing_plug_keeps_waiting_for_the_nozzle(legacy_engine):
  55. async with legacy_engine.begin() as conn:
  56. await run_migrations(conn)
  57. async with legacy_engine.begin() as conn:
  58. row = (
  59. await conn.execute(
  60. text("SELECT off_temp_source, off_bed_temp_threshold, off_temp_threshold FROM smart_plugs WHERE id = 1")
  61. )
  62. ).one()
  63. assert tuple(row) == ("nozzle", 35, 60)
  64. async def test_upgraded_columns_match_a_fresh_install(legacy_engine, fresh_engine):
  65. async with legacy_engine.begin() as conn:
  66. await run_migrations(conn)
  67. upgraded = await _columns(conn)
  68. async with fresh_engine.begin() as conn:
  69. fresh = await _columns(conn)
  70. for column in NEW_COLUMNS:
  71. assert upgraded[column] == fresh[column], column
  72. assert upgraded[column][1] == 1, f"{column} must be NOT NULL"
  73. async def test_migration_is_idempotent(legacy_engine):
  74. """A second boot must not fail on the columns already being there."""
  75. async with legacy_engine.begin() as conn:
  76. await run_migrations(conn)
  77. async with legacy_engine.begin() as conn:
  78. await run_migrations(conn)
  79. async with legacy_engine.begin() as conn:
  80. source = (await conn.execute(text("SELECT off_temp_source FROM smart_plugs WHERE id = 1"))).scalar_one()
  81. assert source == "nozzle"