test_internal_printer_jobs.py 13 KB

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