test_internal_printer_jobs.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. """The printer's own calibration runs leave no archive and send no notification.
  2. Auto pressure-advance calibration -- the K-profile line the printer lays down
  3. before a print when flow dynamics calibration is on -- reports over MQTT through
  4. the same print-start event a real print uses, as the subtask name
  5. ``auto_pa_line_calib_mode`` with no ``/usr/`` path attached. The only guard
  6. Bambuddy had tested ``filename.startswith("/usr/")``, so the calibration sailed
  7. past it, found no 3MF anywhere on the printer (there is none to find), and left
  8. a no-3MF archive named after itself in the user's history.
  9. The same name is already known to the completion guard: #2829's capture of
  10. queue item 649 has ``auto_pa_line_calib_mode`` arriving as the subtask name of a
  11. completion that had to be refused against a running job.
  12. """
  13. from unittest.mock import AsyncMock, MagicMock, patch
  14. import pytest
  15. from backend.app.utils.print_jobs import is_internal_printer_job
  16. class TestTheCalibrationIsRecognised:
  17. def test_the_pressure_advance_line_by_subtask_name(self):
  18. """How it actually arrives: a bare subtask name, no filename at all."""
  19. assert is_internal_printer_job("", "auto_pa_line_calib_mode")
  20. def test_the_pressure_advance_line_by_filename(self):
  21. """Both fields are tested, because which one carries it is not fixed."""
  22. assert is_internal_printer_job("auto_pa_line_calib_mode", None)
  23. def test_the_levelling_run_by_its_system_path(self):
  24. assert is_internal_printer_job("/usr/etc/print/auto_cali_for_user.gcode", "auto_cali_for_user")
  25. def test_the_levelling_run_by_name_alone(self):
  26. """The /usr/ path is not guaranteed, so the name is listed too."""
  27. assert is_internal_printer_job(None, "auto_cali_for_user")
  28. @pytest.mark.parametrize(
  29. "reported",
  30. [
  31. "auto_pa_line_calib_mode",
  32. "auto_pa_line_calib_mode.gcode",
  33. "auto_pa_line_calib_mode.3mf",
  34. "auto_pa_line_calib_mode.gcode.3mf",
  35. "AUTO_PA_LINE_CALIB_MODE",
  36. "/data/auto_pa_line_calib_mode.gcode.3mf",
  37. ],
  38. )
  39. def test_however_the_name_is_dressed_up(self, reported):
  40. """Path, suffix and case all vary between the fields and firmwares."""
  41. assert is_internal_printer_job(reported, None)
  42. def test_anything_under_usr_counts(self):
  43. """Nothing a user can print lives on the read-only system partition."""
  44. assert is_internal_printer_job("/usr/bin/firmware_test.gcode", "test")
  45. class TestItLeavesRealPrintsAlone:
  46. """The failure that matters: swallowing somebody's actual print."""
  47. def test_an_ordinary_print(self):
  48. assert not is_internal_printer_job("Benchy.gcode.3mf", "Benchy")
  49. def test_nothing_reported_at_all(self):
  50. assert not is_internal_printer_job(None, None)
  51. assert not is_internal_printer_job("", "")
  52. @pytest.mark.parametrize(
  53. "reported",
  54. [
  55. "auto_pa_line_calib_mode_v2.3mf",
  56. "my_auto_pa_line_calib_mode.3mf",
  57. "auto_cali_for_user_test.gcode.3mf",
  58. ],
  59. )
  60. def test_a_users_file_that_merely_contains_the_name(self, reported):
  61. """Exact match after normalising, so no prefix or substring rule can
  62. eat a file somebody deliberately named after the calibration."""
  63. assert not is_internal_printer_job(reported, None)
  64. def test_a_calibration_cube(self):
  65. """The obvious false positive for any rule built on the word 'calib'."""
  66. assert not is_internal_printer_job("Calibration_Cube.gcode.3mf", "Calibration Cube")
  67. def _mocked_print_start():
  68. """Patch set for driving on_print_start without a printer or database."""
  69. return (
  70. patch("backend.app.main.async_session"),
  71. patch("backend.app.main.notification_service"),
  72. patch("backend.app.main.smart_plug_manager"),
  73. patch("backend.app.main.ws_manager"),
  74. patch("backend.app.main.printer_manager"),
  75. patch("backend.app.main.mqtt_relay"),
  76. )
  77. class TestPrintStartSkipsTheCalibration:
  78. @pytest.mark.asyncio
  79. async def test_no_archive_and_no_notification(self, capture_logs):
  80. sess, notif, plug, ws, pm, relay = _mocked_print_start()
  81. with sess as mock_session_maker, notif as mock_notif, plug as mock_plug, ws as mock_ws, pm as mock_pm, relay:
  82. mock_notif.on_print_start = AsyncMock()
  83. mock_plug.on_print_start = AsyncMock()
  84. mock_ws.send_print_start = AsyncMock()
  85. mock_pm.get_printer = MagicMock(return_value=MagicMock(name="Test", serial_number="TEST123"))
  86. mock_printer = MagicMock()
  87. mock_printer.auto_archive = True
  88. mock_printer.id = 1
  89. mock_session = AsyncMock()
  90. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  91. mock_session.__aexit__ = AsyncMock()
  92. mock_session.execute = AsyncMock(
  93. return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=mock_printer))
  94. )
  95. mock_session_maker.return_value = mock_session
  96. with patch("backend.app.main._send_print_start_notification", new_callable=AsyncMock) as mock_notify:
  97. from backend.app.main import on_print_start
  98. # No filename: exactly what the printer reports for this run,
  99. # and the reason the old /usr/ prefix test never fired.
  100. await on_print_start(1, {"filename": "", "subtask_name": "auto_pa_line_calib_mode"})
  101. mock_notify.assert_not_called()
  102. skipped = [r for r in capture_logs.records if "internal printer job" in str(r.message)]
  103. assert skipped, "Should log that the calibration run was skipped"
  104. class TestPrintCompleteStaysQuiet:
  105. @pytest.mark.asyncio
  106. async def test_no_orphan_notification_when_the_calibration_finishes(self):
  107. """With no archive to close, the completion would otherwise fall into
  108. the no-archive notification path -- which attributes an unmatched
  109. completion to any queue item this printer finished in the last five
  110. minutes. For a calibration running alongside a real print that means
  111. telling its owner their print is done, early and twice.
  112. """
  113. with (
  114. patch("backend.app.main.async_session") as mock_session_maker,
  115. patch("backend.app.main.ws_manager") as mock_ws,
  116. patch("backend.app.main.printer_manager") as mock_pm,
  117. patch("backend.app.main.mqtt_relay") as mock_relay,
  118. patch("backend.app.main.spawn_background_task") as mock_spawn,
  119. patch("backend.app.main.clear_3mf_cache"),
  120. ):
  121. mock_ws.send_print_complete = AsyncMock()
  122. mock_relay.on_print_complete = AsyncMock()
  123. mock_pm.get_printer = MagicMock(return_value=MagicMock(name="Test", serial_number="TEST123"))
  124. mock_pm.get_current_print_user = MagicMock(return_value=None)
  125. mock_pm.clear_current_print_user = MagicMock()
  126. mock_pm.set_awaiting_plate_clear = MagicMock()
  127. mock_session = AsyncMock()
  128. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  129. mock_session.__aexit__ = AsyncMock()
  130. mock_session.execute = AsyncMock(
  131. return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=None), scalars=MagicMock())
  132. )
  133. mock_session_maker.return_value = mock_session
  134. from backend.app.main import on_print_complete
  135. await on_print_complete(
  136. 1,
  137. {"filename": "", "subtask_name": "auto_pa_line_calib_mode", "status": "completed"},
  138. )
  139. spawned = [c for c in mock_spawn.call_args_list if "notify-no-archive" in str(c)]
  140. assert not spawned, "No completion notification should be spawned for a calibration run"
  141. @pytest.mark.asyncio
  142. async def test_a_real_orphan_print_still_notifies(self):
  143. """The no-archive path exists for prints started outside Bambuddy. The
  144. guard must not take those down with it.
  145. """
  146. with (
  147. patch("backend.app.main.async_session") as mock_session_maker,
  148. patch("backend.app.main.ws_manager") as mock_ws,
  149. patch("backend.app.main.printer_manager") as mock_pm,
  150. patch("backend.app.main.mqtt_relay") as mock_relay,
  151. patch("backend.app.main.spawn_background_task") as mock_spawn,
  152. patch("backend.app.main.clear_3mf_cache"),
  153. ):
  154. mock_ws.send_print_complete = AsyncMock()
  155. mock_relay.on_print_complete = AsyncMock()
  156. mock_pm.get_printer = MagicMock(return_value=MagicMock(name="Test", serial_number="TEST123"))
  157. mock_pm.get_current_print_user = MagicMock(return_value=None)
  158. mock_pm.clear_current_print_user = MagicMock()
  159. mock_pm.set_awaiting_plate_clear = MagicMock()
  160. mock_session = AsyncMock()
  161. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  162. mock_session.__aexit__ = AsyncMock()
  163. mock_session.execute = AsyncMock(
  164. return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=None), scalars=MagicMock())
  165. )
  166. mock_session_maker.return_value = mock_session
  167. from backend.app.main import on_print_complete
  168. await on_print_complete(
  169. 1,
  170. {"filename": "", "subtask_name": "Benchy", "status": "completed"},
  171. )
  172. spawned = [c for c in mock_spawn.call_args_list if "notify-no-archive" in str(c)]
  173. assert spawned, "An unmatched real print must still notify"