test_internal_printer_jobs.py 11 KB

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