test_maintenance_log_backfill.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """Resets from before the maintenance log are copied into it once, on upgrade.
  2. They are only in maintenance_history, which goes with its printer task. The
  3. copy takes the printer's and the task's names as they are now; who reset them
  4. was never recorded. A second start copies nothing again, not even entries
  5. deleted from the log since.
  6. """
  7. from __future__ import annotations
  8. from datetime import datetime
  9. import pytest
  10. from sqlalchemy import text
  11. from sqlalchemy.ext.asyncio import create_async_engine
  12. from backend.app.core.database import _backfill_maintenance_log
  13. from backend.app.models.maintenance import MaintenanceLogEntry
  14. pytestmark = pytest.mark.asyncio
  15. @pytest.fixture
  16. async def engine():
  17. """In-memory SQLite with the tables the copy reads, as an upgrade finds them,
  18. and the log as create_all builds it from the model."""
  19. engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
  20. async with engine.begin() as conn:
  21. for ddl in (
  22. 'CREATE TABLE settings (id INTEGER PRIMARY KEY, "key" VARCHAR(100) NOT NULL UNIQUE, value TEXT)',
  23. "CREATE TABLE printers (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL)",
  24. "CREATE TABLE maintenance_types (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL)",
  25. "CREATE TABLE printer_maintenance (id INTEGER PRIMARY KEY, printer_id INTEGER NOT NULL, "
  26. "maintenance_type_id INTEGER NOT NULL)",
  27. "CREATE TABLE maintenance_history (id INTEGER PRIMARY KEY, printer_maintenance_id INTEGER NOT NULL, "
  28. "performed_at DATETIME, hours_at_maintenance FLOAT, notes TEXT)",
  29. ):
  30. await conn.execute(text(ddl))
  31. await conn.run_sync(lambda sync: MaintenanceLogEntry.__table__.create(sync))
  32. await conn.execute(text("INSERT INTO printers (id, name) VALUES (1, 'X1C')"))
  33. await conn.execute(text("INSERT INTO maintenance_types (id, name) VALUES (7, 'Clean Nozzle')"))
  34. await conn.execute(
  35. text("INSERT INTO printer_maintenance (id, printer_id, maintenance_type_id) VALUES (3, 1, 7)")
  36. )
  37. for history_id, at, hours, notes in (
  38. (10, datetime(2026, 1, 2, 3, 4), 12.5, "old note"),
  39. (11, datetime(2026, 2, 1), 40.0, None),
  40. ):
  41. await conn.execute(
  42. text(
  43. "INSERT INTO maintenance_history (id, printer_maintenance_id, performed_at, hours_at_maintenance, notes) "
  44. "VALUES (:id, 3, :at, :hours, :notes)"
  45. ),
  46. {"id": history_id, "at": at, "hours": hours, "notes": notes},
  47. )
  48. try:
  49. yield engine
  50. finally:
  51. await engine.dispose()
  52. async def _entries(conn) -> list[tuple]:
  53. result = await conn.execute(
  54. text(
  55. "SELECT history_id, printer_id, printer_name, maintenance_type_id, maintenance_type_name, "
  56. "hours_at_maintenance, notes, performed_by_id, performed_by_username "
  57. "FROM maintenance_log_entries ORDER BY history_id"
  58. )
  59. )
  60. return [tuple(row) for row in result]
  61. async def test_old_resets_are_copied_with_their_printer_and_task(engine):
  62. async with engine.begin() as conn:
  63. await _backfill_maintenance_log(conn)
  64. entries = await _entries(conn)
  65. assert entries == [
  66. (10, 1, "X1C", 7, "Clean Nozzle", 12.5, "old note", None, None),
  67. (11, 1, "X1C", 7, "Clean Nozzle", 40.0, None, None, None),
  68. ]
  69. async def test_the_copy_keeps_when_they_were_done(engine):
  70. async with engine.begin() as conn:
  71. await _backfill_maintenance_log(conn)
  72. performed = (
  73. await conn.execute(text("SELECT performed_at FROM maintenance_log_entries WHERE history_id = 10"))
  74. ).scalar_one()
  75. assert str(performed).startswith("2026-01-02 03:04")
  76. async def test_a_second_start_copies_nothing_again(engine):
  77. async with engine.begin() as conn:
  78. await _backfill_maintenance_log(conn)
  79. await _backfill_maintenance_log(conn)
  80. entries = await _entries(conn)
  81. assert [e[0] for e in entries] == [10, 11]
  82. async def test_resets_already_logged_are_not_copied(engine):
  83. async with engine.begin() as conn:
  84. await conn.execute(
  85. text(
  86. "INSERT INTO maintenance_log_entries (printer_id, printer_name, maintenance_type_id, "
  87. "maintenance_type_name, hours_at_maintenance, performed_by_username, history_id) "
  88. "VALUES (1, 'X1C', 7, 'Clean Nozzle', 12.5, 'mechanic', 10)"
  89. )
  90. )
  91. await _backfill_maintenance_log(conn)
  92. entries = await _entries(conn)
  93. assert [(e[0], e[-1]) for e in entries] == [(10, "mechanic"), (11, None)]
  94. async def test_entries_deleted_from_the_log_stay_deleted(engine):
  95. async with engine.begin() as conn:
  96. await _backfill_maintenance_log(conn)
  97. await conn.execute(text("DELETE FROM maintenance_log_entries WHERE history_id = 10"))
  98. await _backfill_maintenance_log(conn)
  99. entries = await _entries(conn)
  100. assert [e[0] for e in entries] == [11]