test_internal_printer_jobs.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. class TestPrintCompleteStaysQuiet:
  140. @pytest.mark.asyncio
  141. async def test_no_orphan_notification_when_the_calibration_finishes(self):
  142. """With no archive to close, the completion would otherwise fall into
  143. the no-archive notification path -- which attributes an unmatched
  144. completion to any queue item this printer finished in the last five
  145. minutes. For a calibration running alongside a real print that means
  146. telling its owner their print is done, early and twice.
  147. """
  148. with (
  149. patch("backend.app.main.async_session") as mock_session_maker,
  150. patch("backend.app.main.ws_manager") as mock_ws,
  151. patch("backend.app.main.printer_manager") as mock_pm,
  152. patch("backend.app.main.mqtt_relay") as mock_relay,
  153. patch("backend.app.main.spawn_background_task") as mock_spawn,
  154. patch("backend.app.main.clear_3mf_cache"),
  155. ):
  156. mock_ws.send_print_complete = AsyncMock()
  157. mock_relay.on_print_complete = AsyncMock()
  158. mock_pm.get_printer = MagicMock(return_value=MagicMock(name="Test", serial_number="TEST123"))
  159. mock_pm.get_current_print_user = MagicMock(return_value=None)
  160. mock_pm.clear_current_print_user = MagicMock()
  161. mock_pm.set_awaiting_plate_clear = MagicMock()
  162. mock_session = AsyncMock()
  163. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  164. mock_session.__aexit__ = AsyncMock()
  165. mock_session.execute = AsyncMock(
  166. return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=None), scalars=MagicMock())
  167. )
  168. mock_session_maker.return_value = mock_session
  169. from backend.app.main import on_print_complete
  170. await on_print_complete(
  171. 1,
  172. {"filename": "", "subtask_name": "auto_pa_line_calib_mode", "status": "completed"},
  173. )
  174. spawned = [c for c in mock_spawn.call_args_list if "notify-no-archive" in str(c)]
  175. assert not spawned, "No completion notification should be spawned for a calibration run"
  176. @pytest.mark.asyncio
  177. async def test_a_real_orphan_print_still_notifies(self):
  178. """The no-archive path exists for prints started outside Bambuddy. The
  179. guard must not take those down with it.
  180. """
  181. with (
  182. patch("backend.app.main.async_session") as mock_session_maker,
  183. patch("backend.app.main.ws_manager") as mock_ws,
  184. patch("backend.app.main.printer_manager") as mock_pm,
  185. patch("backend.app.main.mqtt_relay") as mock_relay,
  186. patch("backend.app.main.spawn_background_task") as mock_spawn,
  187. patch("backend.app.main.clear_3mf_cache"),
  188. ):
  189. mock_ws.send_print_complete = AsyncMock()
  190. mock_relay.on_print_complete = AsyncMock()
  191. mock_pm.get_printer = MagicMock(return_value=MagicMock(name="Test", serial_number="TEST123"))
  192. mock_pm.get_current_print_user = MagicMock(return_value=None)
  193. mock_pm.clear_current_print_user = MagicMock()
  194. mock_pm.set_awaiting_plate_clear = MagicMock()
  195. mock_session = AsyncMock()
  196. mock_session.__aenter__ = AsyncMock(return_value=mock_session)
  197. mock_session.__aexit__ = AsyncMock()
  198. mock_session.execute = AsyncMock(
  199. return_value=MagicMock(scalar_one_or_none=MagicMock(return_value=None), scalars=MagicMock())
  200. )
  201. mock_session_maker.return_value = mock_session
  202. from backend.app.main import on_print_complete
  203. await on_print_complete(
  204. 1,
  205. {"filename": "", "subtask_name": "Benchy", "status": "completed"},
  206. )
  207. spawned = [c for c in mock_spawn.call_args_list if "notify-no-archive" in str(c)]
  208. assert spawned, "An unmatched real print must still notify"