test_virtual_printer.py 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137
  1. """Unit tests for Virtual Printer services.
  2. Tests the virtual printer manager, FTP server, and SSDP server components.
  3. """
  4. import asyncio
  5. import json
  6. import zipfile
  7. from pathlib import Path
  8. from unittest.mock import AsyncMock, MagicMock, patch
  9. import pytest
  10. def _write_3mf_with_filaments(file_path: Path, filaments: list[dict], plate_index: int = 1) -> None:
  11. """Build a minimal 3MF zip with `Metadata/slice_info.config` carrying the
  12. given per-slot filament entries. Each `filaments` dict needs `id`, `type`,
  13. `color`, `used_g`. Used by the #1188 VP queue-mode tests below."""
  14. filament_xml = "".join(
  15. f'<filament id="{f["id"]}" type="{f["type"]}" color="{f["color"]}" '
  16. f'used_g="{f["used_g"]}" tray_info_idx="{f.get("tray_info_idx", "")}"/>'
  17. for f in filaments
  18. )
  19. config = (
  20. '<?xml version="1.0" encoding="utf-8"?>'
  21. "<config>"
  22. f'<plate><metadata key="index" value="{plate_index}"/>'
  23. f"{filament_xml}"
  24. "</plate>"
  25. "</config>"
  26. )
  27. with zipfile.ZipFile(file_path, "w") as zf:
  28. zf.writestr("Metadata/slice_info.config", config)
  29. # Plate gcode is referenced for plate-id detection in the VP path —
  30. # presence is enough; contents don't matter.
  31. zf.writestr(f"Metadata/plate_{plate_index}.gcode", "; gcode\n")
  32. class TestVirtualPrinterInstance:
  33. """Tests for VirtualPrinterInstance class."""
  34. @pytest.fixture
  35. def instance(self, tmp_path):
  36. """Create a VirtualPrinterInstance with test defaults."""
  37. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  38. return VirtualPrinterInstance(
  39. vp_id=1,
  40. name="TestPrinter",
  41. mode="archive",
  42. model="C11",
  43. access_code="12345678",
  44. serial_suffix="391800001",
  45. base_dir=tmp_path,
  46. )
  47. # ========================================================================
  48. # Tests for instance properties
  49. # ========================================================================
  50. def test_instance_stores_parameters(self, instance):
  51. """Verify constructor stores parameters correctly."""
  52. assert instance.id == 1
  53. assert instance.name == "TestPrinter"
  54. assert instance.mode == "archive"
  55. assert instance.model == "C11"
  56. assert instance.access_code == "12345678"
  57. assert instance.serial_suffix == "391800001"
  58. def test_instance_serial_property(self, instance):
  59. """Verify serial is generated from model prefix + suffix."""
  60. # C11 = P1P, prefix = 01S00A
  61. assert instance.serial == "01S00A391800001"
  62. def test_instance_serial_x1c(self, tmp_path):
  63. """Verify X1C serial uses correct prefix."""
  64. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  65. inst = VirtualPrinterInstance(
  66. vp_id=2,
  67. name="X1C",
  68. mode="archive",
  69. model="BL-P001",
  70. access_code="12345678",
  71. serial_suffix="391800002",
  72. base_dir=tmp_path,
  73. )
  74. assert inst.serial == "00M00A391800002"
  75. def test_instance_is_proxy_false(self, instance):
  76. """Verify is_proxy is False for non-proxy mode."""
  77. assert instance.is_proxy is False
  78. def test_instance_is_proxy_true(self, tmp_path):
  79. """Verify is_proxy is True for proxy mode."""
  80. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  81. inst = VirtualPrinterInstance(
  82. vp_id=3,
  83. name="Proxy",
  84. mode="proxy",
  85. model="C11",
  86. access_code="",
  87. serial_suffix="391800003",
  88. target_printer_ip="192.168.1.100",
  89. base_dir=tmp_path,
  90. )
  91. assert inst.is_proxy is True
  92. def test_instance_is_running_with_active_tasks(self, instance):
  93. """Verify is_running is True when tasks are active."""
  94. mock_task = MagicMock()
  95. mock_task.done.return_value = False
  96. instance._tasks = [mock_task]
  97. assert instance.is_running is True
  98. def test_instance_is_running_with_no_tasks(self, instance):
  99. """Verify is_running is False when no tasks."""
  100. assert instance.is_running is False
  101. def test_instance_creates_directories(self, instance, tmp_path):
  102. """Verify instance creates upload and cert directories."""
  103. assert (tmp_path / "uploads" / "1").exists()
  104. assert (tmp_path / "uploads" / "1" / "cache").exists()
  105. assert (tmp_path / "certs" / "1").exists()
  106. # ========================================================================
  107. # Tests for status
  108. # ========================================================================
  109. def test_get_status_returns_correct_format(self, instance):
  110. """Verify get_status returns expected fields."""
  111. instance._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")} # nosec B108
  112. mock_task = MagicMock(done=MagicMock(return_value=False))
  113. instance._tasks = [mock_task]
  114. status = instance.get_status()
  115. assert status["running"] is True
  116. assert status["pending_files"] == 1
  117. def test_get_status_not_running(self, instance):
  118. """Verify get_status when no tasks."""
  119. status = instance.get_status()
  120. assert status["running"] is False
  121. assert status["pending_files"] == 0
  122. # ========================================================================
  123. # Tests for file handling
  124. # ========================================================================
  125. @pytest.mark.asyncio
  126. async def test_on_file_received_adds_to_pending(self, instance):
  127. """Verify received file is added to pending list in review mode."""
  128. instance.mode = "review"
  129. file_path = Path("/tmp/test.3mf") # nosec B108
  130. with patch.object(instance, "_queue_file", new_callable=AsyncMock) as mock_queue:
  131. await instance.on_file_received(file_path, "192.168.1.100")
  132. assert "test.3mf" in instance._pending_files
  133. mock_queue.assert_called_once()
  134. @pytest.mark.asyncio
  135. async def test_on_file_received_archives_immediately(self, instance):
  136. """Verify file is archived in immediate mode."""
  137. file_path = Path("/tmp/test.3mf") # nosec B108
  138. with patch.object(instance, "_archive_file", new_callable=AsyncMock) as mock_archive:
  139. await instance.on_file_received(file_path, "192.168.1.100")
  140. mock_archive.assert_called_once_with(file_path, "192.168.1.100")
  141. @pytest.mark.asyncio
  142. async def test_on_file_received_signals_FINISH_to_slicer(self, instance):
  143. """Regression #1280: when a slicer's Print flow uploads to a non-proxy VP,
  144. the VP must transition gcode_state PREPARE → FINISH so the slicer's
  145. in-flight-job lock releases. Going PREPARE → IDLE wedges Orca at
  146. "Downloading...(0%)" and blocks the next dispatch with "busy with
  147. another print job".
  148. Send-flow slicers don't watch the post-upload state, so this is a
  149. no-op behavior change for them.
  150. """
  151. instance.mode = "archive"
  152. instance._mqtt = MagicMock()
  153. instance._mqtt.set_gcode_state = MagicMock()
  154. file_path = Path("/tmp/test.3mf") # nosec B108
  155. with patch.object(instance, "_archive_file", new_callable=AsyncMock):
  156. await instance.on_file_received(file_path, "192.168.1.100")
  157. instance._mqtt.set_gcode_state.assert_called_once_with("FINISH", filename="test.3mf", prepare_percent="100")
  158. @pytest.mark.asyncio
  159. async def test_on_file_received_non_3mf_does_not_touch_state(self, instance):
  160. """Non-3MF uploads (e.g., a job's auxiliary files) must not transition
  161. the visible state — the slicer is only tracking the .3mf upload."""
  162. instance.mode = "archive"
  163. instance._mqtt = MagicMock()
  164. instance._mqtt.set_gcode_state = MagicMock()
  165. file_path = Path("/tmp/test.gcode") # nosec B108
  166. with patch.object(instance, "_archive_file", new_callable=AsyncMock):
  167. await instance.on_file_received(file_path, "192.168.1.100")
  168. instance._mqtt.set_gcode_state.assert_not_called()
  169. @pytest.mark.asyncio
  170. async def test_on_print_command_schedules_finish_release_non_proxy(self, instance):
  171. """#1658: Bambu Studio 2.7.x flipped the slicer's Send flow to
  172. FTP → FTP → MQTT project_file. Under that order the synthetic
  173. project_file ack overwrites the FINISH set by #1280 in
  174. ``on_file_received`` back to PREPARE, leaving the slicer's
  175. "Downloading" modal stuck forever. Re-firing FINISH a moment after
  176. the ack releases the modal.
  177. """
  178. instance.mode = "archive"
  179. instance._mqtt = MagicMock()
  180. instance._mqtt.set_gcode_state = MagicMock()
  181. with patch.object(instance, "_delayed_finish_release", new_callable=AsyncMock) as mock_delayed:
  182. await instance.on_print_command("test.3mf", {"command": "project_file"})
  183. mock_delayed.assert_called_once()
  184. # First positional arg should be the filename; second is the delay seconds.
  185. args = mock_delayed.call_args.args
  186. assert args[0] == "test.3mf"
  187. assert isinstance(args[1], int | float)
  188. @pytest.mark.asyncio
  189. async def test_on_print_command_proxy_mode_does_not_reschedule_finish(self, instance):
  190. """Proxy mode hands push_status straight from the real printer through
  191. the bridge. Re-firing a synthetic FINISH would clobber a real
  192. PREPARE / RUNNING transition coming back from the printer, so the
  193. scheduler is exempt for proxy mode."""
  194. instance.mode = "proxy"
  195. instance._mqtt = MagicMock()
  196. with patch.object(instance, "_delayed_finish_release", new_callable=AsyncMock) as mock_delayed:
  197. await instance.on_print_command("test.3mf", {"command": "project_file"})
  198. mock_delayed.assert_not_called()
  199. @pytest.mark.asyncio
  200. async def test_on_print_command_no_mqtt_does_not_schedule(self, instance):
  201. """If the MQTT server isn't running yet (transient race during boot),
  202. the scheduler must skip silently — no AttributeError, no orphan task."""
  203. instance.mode = "queue"
  204. instance._mqtt = None
  205. # Should not raise.
  206. await instance.on_print_command("test.3mf", {"command": "project_file"})
  207. assert instance._finish_release_task is None
  208. @pytest.mark.asyncio
  209. async def test_schedule_finish_release_cancels_previous_timer(self, instance):
  210. """A slicer that fires project_file twice (e.g. retry after a transient
  211. FTP hiccup) must only result in one FINISH transition — the earlier
  212. in-flight timer is cancelled when the next one is scheduled."""
  213. instance.mode = "queue"
  214. instance._mqtt = MagicMock()
  215. instance._schedule_finish_release("first.3mf", delay=10.0)
  216. first_task = instance._finish_release_task
  217. assert first_task is not None
  218. instance._schedule_finish_release("second.3mf", delay=10.0)
  219. second_task = instance._finish_release_task
  220. assert second_task is not first_task
  221. # Give the loop one tick so the cancelled task settles.
  222. await asyncio.sleep(0)
  223. assert first_task.cancelled() or first_task.done()
  224. # Clean up the still-pending second task so the test doesn't leak it.
  225. second_task.cancel()
  226. try:
  227. await second_task
  228. except asyncio.CancelledError:
  229. pass
  230. @pytest.mark.asyncio
  231. async def test_delayed_finish_release_sets_finish_state(self, instance):
  232. """End-to-end: after the delay elapses, set_gcode_state is called with
  233. FINISH and prepare_percent=100, matching the wire-format the slicer's
  234. Print flow consumes to release "Downloading"."""
  235. instance._mqtt = MagicMock()
  236. instance._mqtt.set_gcode_state = MagicMock()
  237. await instance._delayed_finish_release("queued.3mf", delay=0.0)
  238. instance._mqtt.set_gcode_state.assert_called_once_with("FINISH", filename="queued.3mf", prepare_percent="100")
  239. @pytest.mark.asyncio
  240. async def test_on_print_command_no_filename_does_not_schedule(self, instance):
  241. """A project_file command without a subtask_name (defensive — real
  242. slicers always send one) must not schedule a no-op FINISH that would
  243. carry an empty filename on the next 1 Hz push."""
  244. instance.mode = "queue"
  245. instance._mqtt = MagicMock()
  246. with patch.object(instance, "_delayed_finish_release", new_callable=AsyncMock) as mock_delayed:
  247. await instance.on_print_command("", {"command": "project_file"})
  248. mock_delayed.assert_not_called()
  249. @pytest.mark.asyncio
  250. async def test_archive_file_skips_non_3mf(self, instance):
  251. """Verify non-3MF files are skipped and cleaned up."""
  252. instance._session_factory = MagicMock()
  253. instance._pending_files["verify_job"] = Path("/tmp/verify_job") # nosec B108
  254. with patch("pathlib.Path.unlink"):
  255. await instance._archive_file(Path("/tmp/verify_job"), "192.168.1.100") # nosec B108
  256. assert "verify_job" not in instance._pending_files
  257. @pytest.mark.asyncio
  258. async def test_archive_file_broadcasts_archive_created(self, tmp_path):
  259. """#1282: VP immediate-mode archives must broadcast archive_created so
  260. the Archives page refreshes without a tab switch. Real-printer prints
  261. get this via main.py's MQTT print_start handler; the VP path used to
  262. skip the broadcast entirely."""
  263. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  264. mock_db = AsyncMock()
  265. mock_db.commit = AsyncMock()
  266. mock_session_factory = MagicMock()
  267. mock_session_ctx = AsyncMock()
  268. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  269. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  270. mock_session_factory.return_value = mock_session_ctx
  271. inst = VirtualPrinterInstance(
  272. vp_id=30,
  273. name="ImmediateBroadcast",
  274. mode="archive",
  275. model="C12",
  276. access_code="12345678",
  277. serial_suffix="391800030",
  278. base_dir=tmp_path,
  279. session_factory=mock_session_factory,
  280. )
  281. file_path = tmp_path / "test.3mf"
  282. file_path.write_bytes(b"fake3mf")
  283. mock_archive = MagicMock()
  284. mock_archive.id = 99
  285. mock_archive.printer_id = None
  286. mock_archive.filename = "test.3mf"
  287. mock_archive.print_name = "test"
  288. mock_archive.status = "archived"
  289. with (
  290. patch(
  291. "backend.app.api.routes.settings.get_setting",
  292. new_callable=AsyncMock,
  293. return_value=None,
  294. ),
  295. patch(
  296. "backend.app.services.archive.ArchiveService.archive_print",
  297. new_callable=AsyncMock,
  298. return_value=mock_archive,
  299. ),
  300. patch(
  301. "backend.app.core.websocket.ws_manager.send_archive_created",
  302. new_callable=AsyncMock,
  303. ) as mock_broadcast,
  304. ):
  305. await inst._archive_file(file_path, "192.168.1.100")
  306. mock_broadcast.assert_awaited_once()
  307. payload = mock_broadcast.await_args.args[0]
  308. assert payload["id"] == 99
  309. assert payload["filename"] == "test.3mf"
  310. assert payload["status"] == "archived"
  311. # ========================================================================
  312. # Tests for auto_dispatch
  313. # ========================================================================
  314. def test_auto_dispatch_defaults_to_true(self, tmp_path):
  315. """Verify auto_dispatch defaults to True when not specified."""
  316. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  317. inst = VirtualPrinterInstance(
  318. vp_id=10,
  319. name="DefaultDispatch",
  320. mode="queue",
  321. model="C11",
  322. access_code="12345678",
  323. serial_suffix="391800010",
  324. base_dir=tmp_path,
  325. )
  326. assert inst.auto_dispatch is True
  327. @pytest.mark.asyncio
  328. async def test_add_to_print_queue_with_auto_dispatch_on(self, tmp_path):
  329. """Verify queue items have manual_start=False when auto_dispatch=True."""
  330. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  331. mock_db = AsyncMock()
  332. added_items = []
  333. def capture_add(item):
  334. added_items.append(item)
  335. mock_db.add = MagicMock(side_effect=capture_add)
  336. mock_db.commit = AsyncMock()
  337. mock_session_factory = MagicMock()
  338. mock_session_ctx = AsyncMock()
  339. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  340. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  341. mock_session_factory.return_value = mock_session_ctx
  342. inst = VirtualPrinterInstance(
  343. vp_id=11,
  344. name="AutoDispatchOn",
  345. mode="queue",
  346. model="C11",
  347. access_code="12345678",
  348. serial_suffix="391800011",
  349. auto_dispatch=True,
  350. base_dir=tmp_path,
  351. session_factory=mock_session_factory,
  352. )
  353. # Create a temp 3mf file
  354. file_path = tmp_path / "test.3mf"
  355. file_path.write_bytes(b"fake3mf")
  356. mock_archive = MagicMock()
  357. mock_archive.id = 1
  358. mock_archive.print_name = "test"
  359. with (
  360. patch(
  361. "backend.app.api.routes.settings.get_setting",
  362. new_callable=AsyncMock,
  363. return_value=None,
  364. ),
  365. patch(
  366. "backend.app.services.archive.ArchiveService.archive_print",
  367. new_callable=AsyncMock,
  368. return_value=mock_archive,
  369. ),
  370. ):
  371. await inst._add_to_print_queue(file_path, "192.168.1.100")
  372. assert len(added_items) == 1
  373. queue_item = added_items[0]
  374. assert queue_item.manual_start is False
  375. @pytest.mark.asyncio
  376. async def test_add_to_print_queue_broadcasts_archive_created(self, tmp_path):
  377. """#1282: VP queue-mode uploads must broadcast archive_created so the
  378. Archives page picks up the new entry live. Pre-fix the page only
  379. refreshed when the user manually switched tabs."""
  380. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  381. mock_db = AsyncMock()
  382. mock_db.add = MagicMock()
  383. mock_db.commit = AsyncMock()
  384. mock_session_factory = MagicMock()
  385. mock_session_ctx = AsyncMock()
  386. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  387. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  388. mock_session_factory.return_value = mock_session_ctx
  389. inst = VirtualPrinterInstance(
  390. vp_id=31,
  391. name="QueueBroadcast",
  392. mode="queue",
  393. model="C12",
  394. access_code="12345678",
  395. serial_suffix="391800031",
  396. auto_dispatch=True,
  397. base_dir=tmp_path,
  398. session_factory=mock_session_factory,
  399. )
  400. file_path = tmp_path / "test.3mf"
  401. file_path.write_bytes(b"fake3mf")
  402. mock_archive = MagicMock()
  403. mock_archive.id = 77
  404. mock_archive.printer_id = None
  405. mock_archive.filename = "test.3mf"
  406. mock_archive.print_name = "test"
  407. mock_archive.status = "archived"
  408. with (
  409. patch(
  410. "backend.app.api.routes.settings.get_setting",
  411. new_callable=AsyncMock,
  412. return_value=None,
  413. ),
  414. patch(
  415. "backend.app.services.archive.ArchiveService.archive_print",
  416. new_callable=AsyncMock,
  417. return_value=mock_archive,
  418. ),
  419. patch(
  420. "backend.app.core.websocket.ws_manager.send_archive_created",
  421. new_callable=AsyncMock,
  422. ) as mock_broadcast,
  423. ):
  424. await inst._add_to_print_queue(file_path, "192.168.1.100")
  425. mock_broadcast.assert_awaited_once()
  426. payload = mock_broadcast.await_args.args[0]
  427. assert payload["id"] == 77
  428. assert payload["print_name"] == "test"
  429. assert payload["status"] == "archived"
  430. @pytest.mark.asyncio
  431. async def test_add_to_print_queue_with_auto_dispatch_off(self, tmp_path):
  432. """Verify queue items have manual_start=True when auto_dispatch=False."""
  433. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  434. mock_db = AsyncMock()
  435. added_items = []
  436. def capture_add(item):
  437. added_items.append(item)
  438. mock_db.add = MagicMock(side_effect=capture_add)
  439. mock_db.commit = AsyncMock()
  440. mock_session_factory = MagicMock()
  441. mock_session_ctx = AsyncMock()
  442. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  443. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  444. mock_session_factory.return_value = mock_session_ctx
  445. inst = VirtualPrinterInstance(
  446. vp_id=12,
  447. name="AutoDispatchOff",
  448. mode="queue",
  449. model="C11",
  450. access_code="12345678",
  451. serial_suffix="391800012",
  452. auto_dispatch=False,
  453. base_dir=tmp_path,
  454. session_factory=mock_session_factory,
  455. )
  456. # Create a temp 3mf file
  457. file_path = tmp_path / "test.3mf"
  458. file_path.write_bytes(b"fake3mf")
  459. mock_archive = MagicMock()
  460. mock_archive.id = 1
  461. mock_archive.print_name = "test"
  462. with (
  463. patch(
  464. "backend.app.api.routes.settings.get_setting",
  465. new_callable=AsyncMock,
  466. return_value=None,
  467. ),
  468. patch(
  469. "backend.app.services.archive.ArchiveService.archive_print",
  470. new_callable=AsyncMock,
  471. return_value=mock_archive,
  472. ),
  473. ):
  474. await inst._add_to_print_queue(file_path, "192.168.1.100")
  475. assert len(added_items) == 1
  476. queue_item = added_items[0]
  477. assert queue_item.manual_start is True
  478. @pytest.mark.asyncio
  479. async def test_add_to_print_queue_uses_workflow_defaults_from_settings(self, tmp_path):
  480. """#1235: VP queue-mode constructed PrintQueueItem without specifying
  481. bed_levelling / flow_cali / vibration_cali / layer_inspect / timelapse,
  482. so SQLAlchemy applied the column-level defaults and ignored the user's
  483. workflow preferences entirely. Every print sent from the slicer to the
  484. VP came through with the OPPOSITE of what the workflow page said,
  485. forcing the user to edit each queue item by hand.
  486. """
  487. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  488. added_items = []
  489. mock_db = AsyncMock()
  490. mock_db.add = MagicMock(side_effect=added_items.append)
  491. mock_db.commit = AsyncMock()
  492. mock_session_factory = MagicMock()
  493. mock_session_ctx = AsyncMock()
  494. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  495. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  496. mock_session_factory.return_value = mock_session_ctx
  497. inst = VirtualPrinterInstance(
  498. vp_id=22,
  499. name="DefaultsTest",
  500. mode="queue",
  501. model="C12",
  502. access_code="12345678",
  503. serial_suffix="391800022",
  504. auto_dispatch=True,
  505. base_dir=tmp_path,
  506. session_factory=mock_session_factory,
  507. )
  508. file_path = tmp_path / "test.3mf"
  509. file_path.write_bytes(b"fake3mf")
  510. # The reporter set every workflow default to the OPPOSITE of the model's
  511. # column default. Pre-fix the column defaults won; with the fix the
  512. # settings values must flow through to the queue item exactly as stored.
  513. settings_map = {
  514. "virtual_printer_archive_name_source": None,
  515. "default_bed_levelling": "false", # model default: True
  516. "default_flow_cali": "true", # model default: False
  517. "default_vibration_cali": "false", # model default: True
  518. "default_layer_inspect": "true", # model default: False
  519. "default_timelapse": "true", # model default: False
  520. }
  521. async def fake_get_setting(_db, key):
  522. return settings_map.get(key)
  523. mock_archive = MagicMock()
  524. mock_archive.id = 1
  525. mock_archive.print_name = "test"
  526. with (
  527. patch(
  528. "backend.app.api.routes.settings.get_setting",
  529. new=fake_get_setting,
  530. ),
  531. patch(
  532. "backend.app.services.archive.ArchiveService.archive_print",
  533. new_callable=AsyncMock,
  534. return_value=mock_archive,
  535. ),
  536. ):
  537. await inst._add_to_print_queue(file_path, "192.168.1.100")
  538. assert len(added_items) == 1
  539. queue_item = added_items[0]
  540. assert queue_item.bed_levelling is False, "default_bed_levelling=false must flow through"
  541. assert queue_item.flow_cali is True, "default_flow_cali=true must flow through"
  542. assert queue_item.vibration_cali is False, "default_vibration_cali=false must flow through"
  543. assert queue_item.layer_inspect is True, "default_layer_inspect=true must flow through"
  544. assert queue_item.timelapse is True, "default_timelapse=true must flow through"
  545. @pytest.mark.asyncio
  546. async def test_add_to_print_queue_falls_back_to_schema_defaults_when_unset(self, tmp_path):
  547. """#1235 fallback: when no workflow setting is in the DB, the queue
  548. item should use the AppSettings (Pydantic) defaults — same values
  549. the user sees in the workflow page on a fresh install.
  550. """
  551. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  552. added_items = []
  553. mock_db = AsyncMock()
  554. mock_db.add = MagicMock(side_effect=added_items.append)
  555. mock_db.commit = AsyncMock()
  556. mock_session_factory = MagicMock()
  557. mock_session_ctx = AsyncMock()
  558. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  559. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  560. mock_session_factory.return_value = mock_session_ctx
  561. inst = VirtualPrinterInstance(
  562. vp_id=23,
  563. name="FreshInstallDefaults",
  564. mode="queue",
  565. model="C12",
  566. access_code="12345678",
  567. serial_suffix="391800023",
  568. auto_dispatch=True,
  569. base_dir=tmp_path,
  570. session_factory=mock_session_factory,
  571. )
  572. file_path = tmp_path / "test.3mf"
  573. file_path.write_bytes(b"fake3mf")
  574. mock_archive = MagicMock()
  575. mock_archive.id = 1
  576. mock_archive.print_name = "test"
  577. with (
  578. patch(
  579. "backend.app.api.routes.settings.get_setting",
  580. new_callable=AsyncMock,
  581. return_value=None, # No settings → fall back to schema defaults
  582. ),
  583. patch(
  584. "backend.app.services.archive.ArchiveService.archive_print",
  585. new_callable=AsyncMock,
  586. return_value=mock_archive,
  587. ),
  588. ):
  589. await inst._add_to_print_queue(file_path, "192.168.1.100")
  590. assert len(added_items) == 1
  591. queue_item = added_items[0]
  592. # These must match the AppSettings (Pydantic) defaults in schemas/settings.py
  593. assert queue_item.bed_levelling is True
  594. assert queue_item.flow_cali is False
  595. assert queue_item.vibration_cali is True
  596. assert queue_item.layer_inspect is False
  597. assert queue_item.timelapse is False
  598. @pytest.mark.asyncio
  599. async def test_add_to_print_queue_inherits_slicer_print_options(self, tmp_path):
  600. """#1403: VP-queue items used to fall back to `default_timelapse` even
  601. though the slicer's MQTT `project_file` command carries the user's
  602. actual choice. Capture-via-`on_print_command` flow lets the user's
  603. slicer toggle reach the queue item.
  604. Settings here have timelapse OFF; the slicer's MQTT capture has it ON.
  605. After the fix the queue item must reflect the slicer's choice.
  606. """
  607. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  608. added_items = []
  609. mock_db = AsyncMock()
  610. mock_db.add = MagicMock(side_effect=added_items.append)
  611. mock_db.commit = AsyncMock()
  612. mock_session_factory = MagicMock()
  613. mock_session_ctx = AsyncMock()
  614. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  615. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  616. mock_session_factory.return_value = mock_session_ctx
  617. inst = VirtualPrinterInstance(
  618. vp_id=24,
  619. name="SlicerInherits",
  620. mode="queue",
  621. model="C12",
  622. access_code="12345678",
  623. serial_suffix="391800024",
  624. auto_dispatch=True,
  625. base_dir=tmp_path,
  626. session_factory=mock_session_factory,
  627. )
  628. file_path = tmp_path / "test.3mf"
  629. file_path.write_bytes(b"fake3mf")
  630. # Pre-populate the capture as if MQTT `project_file` arrived already.
  631. # Settings (below) deliberately have timelapse OFF — only the slicer
  632. # capture should drive the resulting queue item.
  633. await inst.on_print_command(
  634. file_path.name,
  635. {
  636. "command": "project_file",
  637. "timelapse": True,
  638. "bed_leveling": False, # Note: MQTT field is single-L `bed_leveling`
  639. "flow_cali": True,
  640. "vibration_cali": False,
  641. "layer_inspect": True,
  642. },
  643. )
  644. settings_map = {
  645. "virtual_printer_archive_name_source": None,
  646. "default_bed_levelling": "true",
  647. "default_flow_cali": "false",
  648. "default_vibration_cali": "true",
  649. "default_layer_inspect": "false",
  650. "default_timelapse": "false",
  651. }
  652. async def fake_get_setting(_db, key):
  653. return settings_map.get(key)
  654. mock_archive = MagicMock()
  655. mock_archive.id = 1
  656. mock_archive.print_name = "test"
  657. with (
  658. patch(
  659. "backend.app.api.routes.settings.get_setting",
  660. new=fake_get_setting,
  661. ),
  662. patch(
  663. "backend.app.services.archive.ArchiveService.archive_print",
  664. new_callable=AsyncMock,
  665. return_value=mock_archive,
  666. ),
  667. ):
  668. await inst._add_to_print_queue(file_path, "192.168.1.100")
  669. assert len(added_items) == 1
  670. queue_item = added_items[0]
  671. assert queue_item.timelapse is True, "Slicer's timelapse=True must override settings.default_timelapse=False"
  672. assert queue_item.bed_levelling is False, "Slicer's bed_leveling=False must override default_bed_levelling=True"
  673. assert queue_item.flow_cali is True
  674. assert queue_item.vibration_cali is False
  675. assert queue_item.layer_inspect is True
  676. # Capture is consumed — no lingering state for the next print of the same name.
  677. assert file_path.name not in inst._slicer_print_options
  678. @pytest.mark.asyncio
  679. async def test_add_to_print_queue_coerces_slicer_integer_zero_one(self, tmp_path):
  680. """#1403: H-family firmwares carry calibration flags as integers
  681. (0/1) rather than booleans. The capture must coerce both shapes so
  682. H-family-sliced jobs through the VP queue work the same as P1/X1.
  683. """
  684. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  685. added_items = []
  686. mock_db = AsyncMock()
  687. mock_db.add = MagicMock(side_effect=added_items.append)
  688. mock_db.commit = AsyncMock()
  689. mock_session_factory = MagicMock()
  690. mock_session_ctx = AsyncMock()
  691. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  692. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  693. mock_session_factory.return_value = mock_session_ctx
  694. inst = VirtualPrinterInstance(
  695. vp_id=25,
  696. name="SlicerIntegers",
  697. mode="queue",
  698. model="C12",
  699. access_code="12345678",
  700. serial_suffix="391800025",
  701. auto_dispatch=True,
  702. base_dir=tmp_path,
  703. session_factory=mock_session_factory,
  704. )
  705. file_path = tmp_path / "test.3mf"
  706. file_path.write_bytes(b"fake3mf")
  707. await inst.on_print_command(
  708. file_path.name,
  709. {"command": "project_file", "timelapse": 1, "bed_leveling": 0, "flow_cali": 1},
  710. )
  711. mock_archive = MagicMock()
  712. mock_archive.id = 1
  713. mock_archive.print_name = "test"
  714. with (
  715. patch(
  716. "backend.app.api.routes.settings.get_setting",
  717. new_callable=AsyncMock,
  718. return_value=None,
  719. ),
  720. patch(
  721. "backend.app.services.archive.ArchiveService.archive_print",
  722. new_callable=AsyncMock,
  723. return_value=mock_archive,
  724. ),
  725. ):
  726. await inst._add_to_print_queue(file_path, "192.168.1.100")
  727. assert len(added_items) == 1
  728. queue_item = added_items[0]
  729. assert queue_item.timelapse is True, "integer 1 must coerce to True"
  730. assert queue_item.bed_levelling is False, "integer 0 must coerce to False"
  731. assert queue_item.flow_cali is True
  732. @pytest.mark.asyncio
  733. async def test_add_to_print_queue_populates_required_filament_types(self, tmp_path):
  734. """#1188: VP queue-mode used to create PrintQueueItems with no
  735. filament fields, so the scheduler fell through to model-only matching
  736. and dispatched onto whatever printer was free regardless of loaded
  737. colour. ``required_filament_types`` is populated unconditionally
  738. (cheap, helps the scheduler validate type even without
  739. ``force_color_match``) — pin that contract here."""
  740. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  741. added_items = []
  742. mock_db = AsyncMock()
  743. mock_db.add = MagicMock(side_effect=added_items.append)
  744. mock_db.commit = AsyncMock()
  745. mock_session_factory = MagicMock()
  746. mock_session_ctx = AsyncMock()
  747. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  748. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  749. mock_session_factory.return_value = mock_session_ctx
  750. inst = VirtualPrinterInstance(
  751. vp_id=21,
  752. name="Reqs",
  753. mode="queue",
  754. model="C12",
  755. access_code="12345678",
  756. serial_suffix="391800021",
  757. auto_dispatch=True,
  758. queue_force_color_match=False, # off → only required_filament_types
  759. base_dir=tmp_path,
  760. session_factory=mock_session_factory,
  761. )
  762. file_path = tmp_path / "multi.3mf"
  763. _write_3mf_with_filaments(
  764. file_path,
  765. [
  766. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "12.3"},
  767. {"id": "2", "type": "PETG", "color": "#000000", "used_g": "4.5"},
  768. # used_g=0 → not actually consumed by this plate, must be ignored
  769. {"id": "3", "type": "ABS", "color": "#FF0000", "used_g": "0"},
  770. ],
  771. plate_index=1,
  772. )
  773. mock_archive = MagicMock()
  774. mock_archive.id = 1
  775. mock_archive.print_name = "multi"
  776. with (
  777. patch(
  778. "backend.app.api.routes.settings.get_setting",
  779. new_callable=AsyncMock,
  780. return_value=None,
  781. ),
  782. patch(
  783. "backend.app.services.archive.ArchiveService.archive_print",
  784. new_callable=AsyncMock,
  785. return_value=mock_archive,
  786. ),
  787. ):
  788. await inst._add_to_print_queue(file_path, "192.168.1.100")
  789. assert len(added_items) == 1
  790. queue_item = added_items[0]
  791. # Type-only fallback always populated. Sorted, deduped, no zero-use ABS.
  792. assert queue_item.required_filament_types is not None
  793. assert json.loads(queue_item.required_filament_types) == ["PETG", "PLA"]
  794. # Setting off → no force_color_match overrides leaked.
  795. assert queue_item.filament_overrides is None
  796. @pytest.mark.asyncio
  797. async def test_add_to_print_queue_force_color_match_writes_overrides(self, tmp_path):
  798. """#1188 core fix: when the per-VP ``queue_force_color_match`` toggle
  799. is on, every consumed slot lands as a ``filament_overrides`` entry
  800. with ``force_color_match: true``. This is the field the scheduler
  801. keys on (``print_scheduler.py:512``) — without it, slot-by-slot
  802. type+color matching never runs."""
  803. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  804. added_items = []
  805. mock_db = AsyncMock()
  806. mock_db.add = MagicMock(side_effect=added_items.append)
  807. mock_db.commit = AsyncMock()
  808. mock_session_factory = MagicMock()
  809. mock_session_ctx = AsyncMock()
  810. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  811. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  812. mock_session_factory.return_value = mock_session_ctx
  813. inst = VirtualPrinterInstance(
  814. vp_id=22,
  815. name="ForceColor",
  816. mode="queue",
  817. model="C12",
  818. access_code="12345678",
  819. serial_suffix="391800022",
  820. auto_dispatch=True,
  821. queue_force_color_match=True, # on
  822. base_dir=tmp_path,
  823. session_factory=mock_session_factory,
  824. )
  825. file_path = tmp_path / "forced.3mf"
  826. _write_3mf_with_filaments(
  827. file_path,
  828. [
  829. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "10.0"},
  830. {"id": "2", "type": "PLA", "color": "#FF00FF", "used_g": "5.0"},
  831. ],
  832. plate_index=1,
  833. )
  834. mock_archive = MagicMock()
  835. mock_archive.id = 1
  836. mock_archive.print_name = "forced"
  837. with (
  838. patch(
  839. "backend.app.api.routes.settings.get_setting",
  840. new_callable=AsyncMock,
  841. return_value=None,
  842. ),
  843. patch(
  844. "backend.app.services.archive.ArchiveService.archive_print",
  845. new_callable=AsyncMock,
  846. return_value=mock_archive,
  847. ),
  848. ):
  849. await inst._add_to_print_queue(file_path, "192.168.1.100")
  850. assert len(added_items) == 1
  851. queue_item = added_items[0]
  852. assert queue_item.filament_overrides is not None
  853. overrides = json.loads(queue_item.filament_overrides)
  854. assert overrides == [
  855. {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "force_color_match": True},
  856. {"slot_id": 2, "type": "PLA", "color": "#FF00FF", "force_color_match": True},
  857. ]
  858. # required_filament_types still populated alongside overrides.
  859. assert json.loads(queue_item.required_filament_types) == ["PLA"]
  860. @pytest.mark.asyncio
  861. async def test_add_to_print_queue_force_color_match_skips_when_3mf_unparseable(self, tmp_path):
  862. """A malformed or fake-bytes 3MF must not crash the upload path —
  863. we just write the queue item with no filament fields and let the
  864. scheduler fall back to model-only matching (the pre-#1188 default).
  865. Regression guard for the existing fake-bytes happy-path tests."""
  866. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  867. added_items = []
  868. mock_db = AsyncMock()
  869. mock_db.add = MagicMock(side_effect=added_items.append)
  870. mock_db.commit = AsyncMock()
  871. mock_session_factory = MagicMock()
  872. mock_session_ctx = AsyncMock()
  873. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  874. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  875. mock_session_factory.return_value = mock_session_ctx
  876. inst = VirtualPrinterInstance(
  877. vp_id=23,
  878. name="Unparseable",
  879. mode="queue",
  880. model="C12",
  881. access_code="12345678",
  882. serial_suffix="391800023",
  883. auto_dispatch=True,
  884. queue_force_color_match=True,
  885. base_dir=tmp_path,
  886. session_factory=mock_session_factory,
  887. )
  888. file_path = tmp_path / "bad.3mf"
  889. file_path.write_bytes(b"not a real 3mf zip")
  890. mock_archive = MagicMock()
  891. mock_archive.id = 1
  892. mock_archive.print_name = "bad"
  893. with (
  894. patch(
  895. "backend.app.api.routes.settings.get_setting",
  896. new_callable=AsyncMock,
  897. return_value=None,
  898. ),
  899. patch(
  900. "backend.app.services.archive.ArchiveService.archive_print",
  901. new_callable=AsyncMock,
  902. return_value=mock_archive,
  903. ),
  904. ):
  905. await inst._add_to_print_queue(file_path, "192.168.1.100")
  906. assert len(added_items) == 1
  907. queue_item = added_items[0]
  908. # No filament data extractable → both fields stay None (graceful
  909. # fallback to model-only scheduling).
  910. assert queue_item.required_filament_types is None
  911. assert queue_item.filament_overrides is None
  912. # ========================================================================
  913. # Tests for archive_name_source setting (#1152)
  914. # ========================================================================
  915. @pytest.mark.asyncio
  916. @pytest.mark.parametrize(
  917. ("setting_value", "expected_prefer_filename"),
  918. [
  919. ("filename", True),
  920. ("metadata", False),
  921. (None, False), # Default when setting unset
  922. ("", False), # Defensive: empty string is not "filename"
  923. ],
  924. )
  925. async def test_archive_file_passes_prefer_filename_per_setting(
  926. self, tmp_path, setting_value, expected_prefer_filename
  927. ):
  928. """_archive_file reads `virtual_printer_archive_name_source` and forwards
  929. prefer_filename_for_name=True only when it equals 'filename' (#1152)."""
  930. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  931. mock_db = AsyncMock()
  932. mock_session_factory = MagicMock()
  933. mock_session_ctx = AsyncMock()
  934. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  935. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  936. mock_session_factory.return_value = mock_session_ctx
  937. inst = VirtualPrinterInstance(
  938. vp_id=20,
  939. name="NameSource",
  940. mode="archive",
  941. model="C11",
  942. access_code="12345678",
  943. serial_suffix="391800020",
  944. base_dir=tmp_path,
  945. session_factory=mock_session_factory,
  946. )
  947. file_path = tmp_path / "user-renamed-job.3mf"
  948. file_path.write_bytes(b"fake3mf")
  949. mock_archive = MagicMock()
  950. mock_archive.id = 1
  951. mock_archive.print_name = "user-renamed-job"
  952. archive_print_mock = AsyncMock(return_value=mock_archive)
  953. with (
  954. patch(
  955. "backend.app.api.routes.settings.get_setting",
  956. new_callable=AsyncMock,
  957. return_value=setting_value,
  958. ),
  959. patch(
  960. "backend.app.services.archive.ArchiveService.archive_print",
  961. archive_print_mock,
  962. ),
  963. ):
  964. await inst._archive_file(file_path, "192.168.1.100")
  965. assert archive_print_mock.await_count == 1
  966. kwargs = archive_print_mock.await_args.kwargs
  967. assert kwargs.get("prefer_filename_for_name") is expected_prefer_filename
  968. # ========================================================================
  969. # Tests for failure-path cleanup (#audit-R2-1)
  970. # ========================================================================
  971. #
  972. # All three file handlers (_archive_file, _queue_file, _add_to_print_queue)
  973. # previously only popped _pending_files and unlinked the temp file on the
  974. # success branch. Failure paths leaked the marker (blocking same-name
  975. # retries via the FTP layer) and the temp file on disk. The cleanup must
  976. # ALWAYS run, even when archival / queue insert raises.
  977. @pytest.mark.asyncio
  978. async def test_archive_file_failure_path_pops_pending_and_unlinks(self, tmp_path):
  979. """When the archive layer raises, `_pending_files[filename]` must still
  980. be popped and the temp file must be unlinked. Otherwise the FTP layer's
  981. same-name retry guard would silently reject the slicer's next attempt
  982. and the upload_dir would accumulate ghost files."""
  983. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  984. mock_db = AsyncMock()
  985. mock_session_factory = MagicMock()
  986. mock_session_ctx = AsyncMock()
  987. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  988. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  989. mock_session_factory.return_value = mock_session_ctx
  990. inst = VirtualPrinterInstance(
  991. vp_id=40,
  992. name="ArchiveFailCleanup",
  993. mode="archive",
  994. model="C12",
  995. access_code="12345678",
  996. serial_suffix="391800040",
  997. base_dir=tmp_path,
  998. session_factory=mock_session_factory,
  999. )
  1000. file_path = tmp_path / "cleanup-archive.3mf"
  1001. file_path.write_bytes(b"fake3mf")
  1002. inst._pending_files[file_path.name] = file_path
  1003. with (
  1004. patch(
  1005. "backend.app.api.routes.settings.get_setting",
  1006. new_callable=AsyncMock,
  1007. return_value=None,
  1008. ),
  1009. patch(
  1010. "backend.app.services.archive.ArchiveService.archive_print",
  1011. new_callable=AsyncMock,
  1012. side_effect=RuntimeError("archive blew up"),
  1013. ),
  1014. ):
  1015. await inst._archive_file(file_path, "192.168.1.100")
  1016. assert file_path.name not in inst._pending_files
  1017. assert not file_path.exists()
  1018. @pytest.mark.asyncio
  1019. async def test_queue_file_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1020. """Same invariant for _queue_file: a DB error during PendingUpload
  1021. insert must not leak the in-flight marker or the temp file."""
  1022. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1023. mock_db = AsyncMock()
  1024. # Commit raises — emulating a DB connectivity error.
  1025. mock_db.add = MagicMock()
  1026. mock_db.commit = AsyncMock(side_effect=RuntimeError("db unreachable"))
  1027. mock_session_factory = MagicMock()
  1028. mock_session_ctx = AsyncMock()
  1029. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1030. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1031. mock_session_factory.return_value = mock_session_ctx
  1032. inst = VirtualPrinterInstance(
  1033. vp_id=41,
  1034. name="QueueFailCleanup",
  1035. mode="review",
  1036. model="C12",
  1037. access_code="12345678",
  1038. serial_suffix="391800041",
  1039. base_dir=tmp_path,
  1040. session_factory=mock_session_factory,
  1041. )
  1042. file_path = tmp_path / "cleanup-queue.3mf"
  1043. file_path.write_bytes(b"fake3mf")
  1044. inst._pending_files[file_path.name] = file_path
  1045. await inst._queue_file(file_path, "192.168.1.100")
  1046. assert file_path.name not in inst._pending_files
  1047. assert not file_path.exists()
  1048. @pytest.mark.asyncio
  1049. async def test_add_to_print_queue_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1050. """Same invariant for _add_to_print_queue: a DB error or archive
  1051. failure must not leak the in-flight marker or the temp file."""
  1052. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1053. mock_db = AsyncMock()
  1054. mock_db.add = MagicMock()
  1055. mock_db.commit = AsyncMock()
  1056. mock_db.execute = AsyncMock(side_effect=RuntimeError("queue insert blew up"))
  1057. mock_session_factory = MagicMock()
  1058. mock_session_ctx = AsyncMock()
  1059. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1060. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1061. mock_session_factory.return_value = mock_session_ctx
  1062. inst = VirtualPrinterInstance(
  1063. vp_id=42,
  1064. name="DispatchFailCleanup",
  1065. mode="queue",
  1066. model="C12",
  1067. access_code="12345678",
  1068. serial_suffix="391800042",
  1069. auto_dispatch=True,
  1070. base_dir=tmp_path,
  1071. session_factory=mock_session_factory,
  1072. )
  1073. file_path = tmp_path / "cleanup-dispatch.3mf"
  1074. file_path.write_bytes(b"fake3mf")
  1075. inst._pending_files[file_path.name] = file_path
  1076. with patch(
  1077. "backend.app.api.routes.settings.get_setting",
  1078. new_callable=AsyncMock,
  1079. return_value=None,
  1080. ):
  1081. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1082. assert file_path.name not in inst._pending_files
  1083. assert not file_path.exists()
  1084. # ========================================================================
  1085. # Test for position=MAX+1 (audit-R2)
  1086. # ========================================================================
  1087. @pytest.mark.asyncio
  1088. async def test_add_to_print_queue_position_picks_max_plus_one(self, tmp_path):
  1089. """VP-queue items previously got hardcoded `position=1`, colliding
  1090. with existing items at position 1 and producing non-deterministic
  1091. execution order. Now the position is chosen by `MAX(position)+1`
  1092. against the target queue, matching the canonical `POST /print-queue/`
  1093. path."""
  1094. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1095. # Capture the inserted PrintQueueItem so we can assert on .position.
  1096. added_items: list = []
  1097. class _RecordingDb:
  1098. def __init__(self):
  1099. self.add = lambda item: added_items.append(item)
  1100. self.commit = AsyncMock()
  1101. async def execute(self, query): # noqa: ARG002
  1102. """Return a stub result whose `.scalar()` reports the existing
  1103. MAX(position) for the target. Returning 7 means the new item
  1104. should land at 8."""
  1105. result = MagicMock()
  1106. result.scalar = MagicMock(return_value=7)
  1107. return result
  1108. mock_db = _RecordingDb()
  1109. mock_session_factory = MagicMock()
  1110. mock_session_ctx = AsyncMock()
  1111. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1112. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1113. mock_session_factory.return_value = mock_session_ctx
  1114. inst = VirtualPrinterInstance(
  1115. vp_id=43,
  1116. name="PositionMaxPlusOne",
  1117. mode="queue",
  1118. model="C12",
  1119. access_code="12345678",
  1120. serial_suffix="391800043",
  1121. target_printer_id=99,
  1122. auto_dispatch=True,
  1123. base_dir=tmp_path,
  1124. session_factory=mock_session_factory,
  1125. )
  1126. file_path = tmp_path / "next-position.3mf"
  1127. file_path.write_bytes(b"fake3mf")
  1128. mock_archive = MagicMock()
  1129. mock_archive.id = 555
  1130. mock_archive.printer_id = None
  1131. mock_archive.filename = "next-position.3mf"
  1132. mock_archive.print_name = "next-position"
  1133. mock_archive.status = "archived"
  1134. with (
  1135. patch(
  1136. "backend.app.api.routes.settings.get_setting",
  1137. new_callable=AsyncMock,
  1138. return_value=None,
  1139. ),
  1140. patch(
  1141. "backend.app.services.archive.ArchiveService.archive_print",
  1142. new_callable=AsyncMock,
  1143. return_value=mock_archive,
  1144. ),
  1145. patch(
  1146. "backend.app.core.websocket.ws_manager.send_archive_created",
  1147. new_callable=AsyncMock,
  1148. ),
  1149. ):
  1150. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1151. # One queue item was added.
  1152. assert len(added_items) == 1
  1153. queue_item = added_items[0]
  1154. # Position = max(7) + 1 = 8 — NOT the legacy hardcoded 1.
  1155. assert queue_item.position == 8
  1156. @pytest.mark.asyncio
  1157. async def test_add_to_print_queue_multi_plate_send_all_enqueues_one_per_plate(self, tmp_path):
  1158. """#1733: BambuStudio / OrcaSlicer "Send All" of a multi-plate project
  1159. uploads ONE 3MF containing every plate. Pre-fix only the first plate
  1160. index was extracted and one queue item was created; plates 2..N were
  1161. silently dropped. Post-fix every `<plate>` block in `slice_info.config`
  1162. produces its own PrintQueueItem with the correct ``plate_id``, sharing
  1163. the same backing archive, with consecutive positions for plate-order
  1164. execution.
  1165. """
  1166. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1167. added_items: list = []
  1168. class _RecordingDb:
  1169. def __init__(self):
  1170. # Capture inserted items as they're added; assign a fake .id
  1171. # on flush so the manager's logger doesn't see None.
  1172. self._next_id = 1000
  1173. def _add(item):
  1174. added_items.append(item)
  1175. self.add = _add
  1176. self.commit = AsyncMock()
  1177. async def execute(self, query): # noqa: ARG002
  1178. """Return MAX(position) = 0 so plate items land at 1, 2, 3."""
  1179. result = MagicMock()
  1180. result.scalar = MagicMock(return_value=0)
  1181. return result
  1182. async def flush(self):
  1183. # Mimic the FK populate so queue_item.id is available after add().
  1184. for item in added_items:
  1185. if getattr(item, "id", None) is None:
  1186. item.id = self._next_id
  1187. self._next_id += 1
  1188. mock_db = _RecordingDb()
  1189. mock_session_factory = MagicMock()
  1190. mock_session_ctx = AsyncMock()
  1191. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1192. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1193. mock_session_factory.return_value = mock_session_ctx
  1194. inst = VirtualPrinterInstance(
  1195. vp_id=44,
  1196. name="MultiPlateSendAll",
  1197. mode="queue",
  1198. model="O1D", # H2D — matches the live VP H2D-1 Proxy in #1733
  1199. access_code="12345678",
  1200. serial_suffix="391800044",
  1201. target_printer_id=1,
  1202. auto_dispatch=False, # manual_start, mirrors the live VP
  1203. base_dir=tmp_path,
  1204. session_factory=mock_session_factory,
  1205. )
  1206. # Build a 3MF with three plates baked into slice_info.config —
  1207. # mirrors what BambuStudio / OrcaSlicer's "Send All" puts on the wire.
  1208. file_path = tmp_path / "Cube.gcode.3mf"
  1209. _write_3mf_with_filaments(
  1210. file_path, [{"id": 1, "type": "PLA", "color": "#000000", "used_g": "15.61"}], plate_index=1
  1211. )
  1212. # Append plate 2 and 3 blocks to slice_info.config to mimic Send All.
  1213. with zipfile.ZipFile(file_path, "r") as zf:
  1214. existing = zf.read("Metadata/slice_info.config").decode()
  1215. # Inject two additional <plate> blocks (indices 2 and 3) inside <config>.
  1216. multi_plate_config = existing.replace(
  1217. "</config>",
  1218. (
  1219. '<plate><metadata key="index" value="2"/>'
  1220. '<filament id="2" type="PETG" color="#FB0207" used_g="14.45"/>'
  1221. "</plate>"
  1222. '<plate><metadata key="index" value="3"/>'
  1223. '<filament id="3" type="PLA" color="#FFFFFF" used_g="12.10"/>'
  1224. "</plate>"
  1225. "</config>"
  1226. ),
  1227. )
  1228. # Repack the zip with the expanded slice_info.config.
  1229. import io as _io
  1230. buf = _io.BytesIO()
  1231. with zipfile.ZipFile(file_path, "r") as src, zipfile.ZipFile(buf, "w") as dst:
  1232. for name in src.namelist():
  1233. if name == "Metadata/slice_info.config":
  1234. dst.writestr(name, multi_plate_config)
  1235. else:
  1236. dst.writestr(name, src.read(name))
  1237. # Plate-2 and plate-3 gcode payloads so `extract_filament_requirements`
  1238. # has something to read for each — contents irrelevant, presence matters.
  1239. dst.writestr("Metadata/plate_2.gcode", "; plate 2 gcode\n")
  1240. dst.writestr("Metadata/plate_3.gcode", "; plate 3 gcode\n")
  1241. file_path.write_bytes(buf.getvalue())
  1242. mock_archive = MagicMock()
  1243. mock_archive.id = 999
  1244. mock_archive.printer_id = None
  1245. mock_archive.filename = "Cube.gcode.3mf"
  1246. mock_archive.print_name = "Cube"
  1247. mock_archive.status = "archived"
  1248. with (
  1249. patch(
  1250. "backend.app.api.routes.settings.get_setting",
  1251. new_callable=AsyncMock,
  1252. return_value=None,
  1253. ),
  1254. patch(
  1255. "backend.app.services.archive.ArchiveService.archive_print",
  1256. new_callable=AsyncMock,
  1257. return_value=mock_archive,
  1258. ),
  1259. patch(
  1260. "backend.app.core.websocket.ws_manager.send_archive_created",
  1261. new_callable=AsyncMock,
  1262. ),
  1263. ):
  1264. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1265. # Three queue items, one per plate, with the correct plate_id and
  1266. # consecutive positions starting at MAX(position)+1 = 1.
  1267. assert len(added_items) == 3, f"Expected 3 queue items for 3-plate Send All, got {len(added_items)}"
  1268. plate_ids = [q.plate_id for q in added_items]
  1269. assert plate_ids == [1, 2, 3], f"plate_ids should preserve slice_info order, got {plate_ids}"
  1270. positions = [q.position for q in added_items]
  1271. assert positions == [1, 2, 3], f"positions should be consecutive, got {positions}"
  1272. archive_ids = {q.archive_id for q in added_items}
  1273. assert archive_ids == {999}, f"All queue items must share the single backing archive, got {archive_ids}"
  1274. # auto_dispatch=False on the VP → every item is manual_start.
  1275. assert all(q.manual_start for q in added_items)
  1276. class TestVirtualPrinterManager:
  1277. """Tests for VirtualPrinterManager orchestrator."""
  1278. @pytest.fixture
  1279. def manager(self):
  1280. """Create a VirtualPrinterManager instance."""
  1281. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  1282. return VirtualPrinterManager()
  1283. def test_manager_starts_empty(self, manager):
  1284. """Verify manager starts with no instances."""
  1285. assert len(manager._instances) == 0
  1286. assert manager.is_enabled is False
  1287. def test_manager_get_status_empty(self, manager):
  1288. """Verify get_status returns disabled state when no instances."""
  1289. status = manager.get_status()
  1290. assert status["enabled"] is False
  1291. assert status["running"] is False
  1292. assert status["mode"] == "archive"
  1293. def test_manager_is_enabled_with_instance(self, manager, tmp_path):
  1294. """Verify is_enabled is True when instances exist."""
  1295. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1296. inst = VirtualPrinterInstance(
  1297. vp_id=1,
  1298. name="Test",
  1299. mode="archive",
  1300. model="C11",
  1301. access_code="12345678",
  1302. serial_suffix="391800001",
  1303. base_dir=tmp_path,
  1304. )
  1305. manager._instances[1] = inst
  1306. assert manager.is_enabled is True
  1307. @pytest.mark.asyncio
  1308. async def test_manager_remove_instance_server(self, manager, tmp_path):
  1309. """Verify remove_instance stops and removes a server-mode instance."""
  1310. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1311. inst = VirtualPrinterInstance(
  1312. vp_id=1,
  1313. name="Test",
  1314. mode="archive",
  1315. model="C11",
  1316. access_code="12345678",
  1317. serial_suffix="391800001",
  1318. base_dir=tmp_path,
  1319. )
  1320. inst.stop_server = AsyncMock()
  1321. manager._instances[1] = inst
  1322. await manager.remove_instance(1)
  1323. assert 1 not in manager._instances
  1324. inst.stop_server.assert_called_once()
  1325. @pytest.mark.asyncio
  1326. async def test_manager_remove_instance_proxy(self, manager, tmp_path):
  1327. """Verify remove_instance stops proxy-mode instance."""
  1328. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1329. inst = VirtualPrinterInstance(
  1330. vp_id=2,
  1331. name="Proxy",
  1332. mode="proxy",
  1333. model="C11",
  1334. access_code="",
  1335. serial_suffix="391800002",
  1336. target_printer_ip="192.168.1.100",
  1337. base_dir=tmp_path,
  1338. )
  1339. inst.stop_proxy = AsyncMock()
  1340. manager._instances[2] = inst
  1341. await manager.remove_instance(2)
  1342. assert 2 not in manager._instances
  1343. inst.stop_proxy.assert_called_once()
  1344. def test_manager_get_status_with_instance(self, manager, tmp_path):
  1345. """Verify legacy get_status returns first instance data."""
  1346. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1347. inst = VirtualPrinterInstance(
  1348. vp_id=1,
  1349. name="Bambuddy",
  1350. mode="archive",
  1351. model="C11",
  1352. access_code="12345678",
  1353. serial_suffix="391800001",
  1354. base_dir=tmp_path,
  1355. )
  1356. mock_task = MagicMock(done=MagicMock(return_value=False))
  1357. inst._tasks = [mock_task]
  1358. inst._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")} # nosec B108
  1359. manager._instances[1] = inst
  1360. status = manager.get_status()
  1361. assert status["enabled"] is True
  1362. assert status["running"] is True
  1363. assert status["mode"] == "archive"
  1364. assert status["name"] == "Bambuddy"
  1365. assert status["serial"] == "01S00A391800001"
  1366. assert status["model"] == "C11"
  1367. assert status["model_name"] == "P1P"
  1368. assert status["pending_files"] == 1
  1369. def test_manager_get_all_status(self, manager, tmp_path):
  1370. """Verify get_all_status returns status for all instances."""
  1371. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1372. for i in range(1, 3):
  1373. inst = VirtualPrinterInstance(
  1374. vp_id=i,
  1375. name=f"VP{i}",
  1376. mode="archive",
  1377. model="C11",
  1378. access_code="12345678",
  1379. serial_suffix=f"39180000{i}",
  1380. base_dir=tmp_path,
  1381. )
  1382. manager._instances[i] = inst
  1383. statuses = manager.get_all_status()
  1384. assert len(statuses) == 2
  1385. assert statuses[0]["name"] == "VP1"
  1386. assert statuses[1]["name"] == "VP2"
  1387. @pytest.mark.asyncio
  1388. async def test_manager_stop_all(self, manager, tmp_path):
  1389. """Verify stop_all removes all instances."""
  1390. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1391. for i in range(1, 3):
  1392. inst = VirtualPrinterInstance(
  1393. vp_id=i,
  1394. name=f"VP{i}",
  1395. mode="archive",
  1396. model="C11",
  1397. access_code="12345678",
  1398. serial_suffix=f"39180000{i}",
  1399. base_dir=tmp_path,
  1400. )
  1401. inst.stop_server = AsyncMock()
  1402. manager._instances[i] = inst
  1403. await manager.stop_all()
  1404. assert len(manager._instances) == 0
  1405. # ========================================================================
  1406. # Tests for sync_from_db config change detection
  1407. # ========================================================================
  1408. def _make_db_vp(self, **overrides):
  1409. """Create a mock VirtualPrinter DB object."""
  1410. defaults = {
  1411. "id": 1,
  1412. "name": "TestVP",
  1413. "enabled": True,
  1414. "mode": "archive",
  1415. "model": "C11",
  1416. "access_code": "12345678",
  1417. "serial_suffix": "391800001",
  1418. "bind_ip": "",
  1419. "remote_interface_ip": "",
  1420. "target_printer_id": None,
  1421. "auto_dispatch": True,
  1422. "tailscale_disabled": True, # Opt-in default (#1070 UX fix)
  1423. "queue_force_color_match": False, # default — must be explicit so MagicMock truthiness doesn't trip the change detector
  1424. "position": 0,
  1425. }
  1426. defaults.update(overrides)
  1427. vp = MagicMock()
  1428. for k, v in defaults.items():
  1429. setattr(vp, k, v)
  1430. return vp
  1431. def _setup_sync_mocks(self, manager, enabled_vps, tmp_path):
  1432. """Wire up session_factory mock for sync_from_db."""
  1433. mock_result = MagicMock()
  1434. mock_result.scalars.return_value.all.return_value = enabled_vps
  1435. mock_db = AsyncMock()
  1436. mock_db.execute = AsyncMock(return_value=mock_result)
  1437. mock_db.__aenter__ = AsyncMock(return_value=mock_db)
  1438. mock_db.__aexit__ = AsyncMock(return_value=False)
  1439. manager._session_factory = MagicMock(return_value=mock_db)
  1440. manager._base_dir = tmp_path
  1441. @pytest.mark.asyncio
  1442. async def test_sync_from_db_restarts_on_mode_change(self, manager, tmp_path):
  1443. """Verify sync_from_db restarts VP when mode changes."""
  1444. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1445. inst = VirtualPrinterInstance(
  1446. vp_id=1,
  1447. name="TestVP",
  1448. mode="archive",
  1449. model="C11",
  1450. access_code="12345678",
  1451. serial_suffix="391800001",
  1452. base_dir=tmp_path,
  1453. )
  1454. inst.stop_server = AsyncMock()
  1455. manager._instances[1] = inst
  1456. # DB says mode changed to "review"
  1457. db_vp = self._make_db_vp(mode="review")
  1458. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1459. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1460. # Patch VirtualPrinterInstance to prevent actual start
  1461. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1462. mock_new = MagicMock()
  1463. mock_new.start_server = AsyncMock()
  1464. MockInst.return_value = mock_new
  1465. await manager.sync_from_db()
  1466. mock_remove.assert_called_once_with(1)
  1467. @pytest.mark.asyncio
  1468. async def test_sync_from_db_restarts_on_access_code_change(self, manager, tmp_path):
  1469. """Verify sync_from_db restarts VP when access_code changes."""
  1470. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1471. inst = VirtualPrinterInstance(
  1472. vp_id=1,
  1473. name="TestVP",
  1474. mode="archive",
  1475. model="C11",
  1476. access_code="12345678",
  1477. serial_suffix="391800001",
  1478. base_dir=tmp_path,
  1479. )
  1480. inst.stop_server = AsyncMock()
  1481. manager._instances[1] = inst
  1482. db_vp = self._make_db_vp(access_code="newcode99")
  1483. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1484. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1485. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1486. mock_new = MagicMock()
  1487. mock_new.start_server = AsyncMock()
  1488. MockInst.return_value = mock_new
  1489. await manager.sync_from_db()
  1490. mock_remove.assert_called_once_with(1)
  1491. @pytest.mark.asyncio
  1492. async def test_sync_from_db_skips_unchanged_instance(self, manager, tmp_path):
  1493. """Verify sync_from_db does NOT restart when config is identical."""
  1494. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1495. inst = VirtualPrinterInstance(
  1496. vp_id=1,
  1497. name="TestVP",
  1498. mode="archive",
  1499. model="C11",
  1500. access_code="12345678",
  1501. serial_suffix="391800001",
  1502. base_dir=tmp_path,
  1503. )
  1504. manager._instances[1] = inst
  1505. # DB matches running config exactly
  1506. db_vp = self._make_db_vp()
  1507. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1508. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1509. await manager.sync_from_db()
  1510. mock_remove.assert_not_called()
  1511. @pytest.mark.asyncio
  1512. async def test_sync_from_db_restarts_on_bind_ip_change(self, manager, tmp_path):
  1513. """Verify sync_from_db restarts VP when bind_ip changes."""
  1514. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1515. inst = VirtualPrinterInstance(
  1516. vp_id=1,
  1517. name="TestVP",
  1518. mode="archive",
  1519. model="C11",
  1520. access_code="12345678",
  1521. serial_suffix="391800001",
  1522. bind_ip="192.168.1.10",
  1523. base_dir=tmp_path,
  1524. )
  1525. inst.stop_server = AsyncMock()
  1526. manager._instances[1] = inst
  1527. db_vp = self._make_db_vp(bind_ip="192.168.1.20")
  1528. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1529. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1530. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1531. mock_new = MagicMock()
  1532. mock_new.start_server = AsyncMock()
  1533. MockInst.return_value = mock_new
  1534. await manager.sync_from_db()
  1535. mock_remove.assert_called_once_with(1)
  1536. @pytest.mark.asyncio
  1537. async def test_sync_from_db_restarts_on_model_change(self, manager, tmp_path):
  1538. """Verify sync_from_db restarts VP when model changes."""
  1539. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1540. inst = VirtualPrinterInstance(
  1541. vp_id=1,
  1542. name="TestVP",
  1543. mode="archive",
  1544. model="C11",
  1545. access_code="12345678",
  1546. serial_suffix="391800001",
  1547. base_dir=tmp_path,
  1548. )
  1549. inst.stop_server = AsyncMock()
  1550. manager._instances[1] = inst
  1551. db_vp = self._make_db_vp(model="C12")
  1552. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1553. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1554. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1555. mock_new = MagicMock()
  1556. mock_new.start_server = AsyncMock()
  1557. MockInst.return_value = mock_new
  1558. await manager.sync_from_db()
  1559. mock_remove.assert_called_once_with(1)
  1560. @pytest.mark.asyncio
  1561. async def test_sync_from_db_does_not_restart_on_tailscale_toggle(self, manager, tmp_path):
  1562. """Flipping tailscale_disabled is purely informational — must NOT trigger a restart.
  1563. Cert provisioning was removed; the toggle only governs whether the VP card surfaces
  1564. the host's Tailscale IP/FQDN to the user. No service needs to reload, so changing
  1565. it through sync_from_db should leave any running instance untouched.
  1566. """
  1567. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1568. inst = VirtualPrinterInstance(
  1569. vp_id=1,
  1570. name="TestVP",
  1571. mode="archive",
  1572. model="C11",
  1573. access_code="12345678",
  1574. serial_suffix="391800001",
  1575. tailscale_disabled=False,
  1576. base_dir=tmp_path,
  1577. )
  1578. inst.stop_server = AsyncMock()
  1579. manager._instances[1] = inst
  1580. db_vp = self._make_db_vp(tailscale_disabled=True)
  1581. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1582. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1583. await manager.sync_from_db()
  1584. mock_remove.assert_not_called()
  1585. class TestFTPSession:
  1586. """Tests for FTP session handling."""
  1587. @pytest.fixture
  1588. def mock_reader(self):
  1589. """Create a mock StreamReader."""
  1590. reader = AsyncMock()
  1591. return reader
  1592. @pytest.fixture
  1593. def mock_writer(self):
  1594. """Create a mock StreamWriter."""
  1595. writer = MagicMock()
  1596. writer.get_extra_info = MagicMock(return_value=("192.168.1.100", 12345))
  1597. writer.write = MagicMock()
  1598. writer.drain = AsyncMock()
  1599. writer.close = MagicMock()
  1600. writer.wait_closed = AsyncMock()
  1601. writer.is_closing = MagicMock(return_value=False)
  1602. return writer
  1603. @pytest.fixture
  1604. def ssl_context(self):
  1605. """Create a mock SSL context."""
  1606. return MagicMock()
  1607. @pytest.fixture
  1608. def session(self, mock_reader, mock_writer, ssl_context, tmp_path):
  1609. """Create an FTPSession instance."""
  1610. from backend.app.services.virtual_printer.ftp_server import FTPSession
  1611. return FTPSession(
  1612. reader=mock_reader,
  1613. writer=mock_writer,
  1614. upload_dir=tmp_path,
  1615. access_code="12345678",
  1616. ssl_context=ssl_context,
  1617. on_file_received=None,
  1618. )
  1619. # ========================================================================
  1620. # Tests for authentication
  1621. # ========================================================================
  1622. @pytest.mark.asyncio
  1623. async def test_user_command_accepts_bblp(self, session):
  1624. """Verify USER command accepts bblp user."""
  1625. await session.cmd_USER("bblp")
  1626. assert session.username == "bblp"
  1627. @pytest.mark.asyncio
  1628. async def test_pass_command_authenticates(self, session):
  1629. """Verify PASS command authenticates with correct code."""
  1630. session.username = "bblp"
  1631. await session.cmd_PASS("12345678")
  1632. assert session.authenticated is True
  1633. @pytest.mark.asyncio
  1634. async def test_pass_command_rejects_wrong_code(self, session):
  1635. """Verify PASS command rejects wrong access code."""
  1636. session.username = "bblp"
  1637. await session.cmd_PASS("wrongcode")
  1638. assert session.authenticated is False
  1639. # ========================================================================
  1640. # Tests for FTP commands
  1641. # ========================================================================
  1642. @pytest.mark.asyncio
  1643. async def test_syst_command(self, session):
  1644. """Verify SYST returns UNIX type."""
  1645. await session.cmd_SYST("")
  1646. session.writer.write.assert_called()
  1647. call_args = session.writer.write.call_args[0][0].decode()
  1648. assert "215" in call_args
  1649. assert "UNIX" in call_args
  1650. @pytest.mark.asyncio
  1651. async def test_pwd_command_requires_auth(self, session):
  1652. """Verify PWD requires authentication."""
  1653. session.authenticated = False
  1654. await session.cmd_PWD("")
  1655. call_args = session.writer.write.call_args[0][0].decode()
  1656. assert "530" in call_args
  1657. @pytest.mark.asyncio
  1658. async def test_pwd_command_when_authenticated(self, session):
  1659. """Verify PWD returns root directory when authenticated."""
  1660. session.authenticated = True
  1661. await session.cmd_PWD("")
  1662. call_args = session.writer.write.call_args[0][0].decode()
  1663. assert "257" in call_args
  1664. @pytest.mark.asyncio
  1665. async def test_type_command_sets_binary(self, session):
  1666. """Verify TYPE I sets binary mode."""
  1667. session.authenticated = True
  1668. await session.cmd_TYPE("I")
  1669. assert session.transfer_type == "I"
  1670. @pytest.mark.asyncio
  1671. async def test_pbsz_command(self, session):
  1672. """Verify PBSZ returns success."""
  1673. await session.cmd_PBSZ("0")
  1674. call_args = session.writer.write.call_args[0][0].decode()
  1675. assert "200" in call_args
  1676. @pytest.mark.asyncio
  1677. async def test_prot_command_accepts_p(self, session):
  1678. """Verify PROT P is accepted."""
  1679. await session.cmd_PROT("P")
  1680. call_args = session.writer.write.call_args[0][0].decode()
  1681. assert "200" in call_args
  1682. @pytest.mark.asyncio
  1683. async def test_quit_command(self, session):
  1684. """Verify QUIT sends goodbye and raises CancelledError."""
  1685. with pytest.raises(asyncio.CancelledError):
  1686. await session.cmd_QUIT("")
  1687. class TestSSDPServer:
  1688. """Tests for Virtual Printer SSDP server."""
  1689. @pytest.fixture
  1690. def ssdp_server(self):
  1691. """Create a VirtualPrinterSSDPServer instance."""
  1692. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1693. return VirtualPrinterSSDPServer(
  1694. serial="TEST123",
  1695. name="TestPrinter",
  1696. model="BL-P001",
  1697. )
  1698. # ========================================================================
  1699. # Tests for SSDP response
  1700. # ========================================================================
  1701. def test_build_notify_message(self, ssdp_server):
  1702. """Verify NOTIFY packet contains required headers."""
  1703. # Set a known IP for testing
  1704. ssdp_server._local_ip = "192.168.1.100"
  1705. message = ssdp_server._build_notify_message()
  1706. assert b"NOTIFY" in message
  1707. assert b"DevName.bambu.com: TestPrinter" in message
  1708. assert b"USN: TEST123" in message
  1709. def test_build_response_message(self, ssdp_server):
  1710. """Verify response packet contains required headers."""
  1711. # Set a known IP for testing
  1712. ssdp_server._local_ip = "192.168.1.100"
  1713. message = ssdp_server._build_response_message()
  1714. assert b"HTTP/1.1 200 OK" in message
  1715. assert b"DevName.bambu.com: TestPrinter" in message
  1716. assert b"USN: TEST123" in message
  1717. def test_ssdp_server_uses_correct_model(self, ssdp_server):
  1718. """Verify SSDP server uses the provided model."""
  1719. ssdp_server._local_ip = "192.168.1.100"
  1720. message = ssdp_server._build_notify_message()
  1721. assert b"DevModel.bambu.com: BL-P001" in message
  1722. # ========================================================================
  1723. # Tests for advertise_ip parameter
  1724. # ========================================================================
  1725. def test_advertise_ip_sets_local_ip(self):
  1726. """Verify advertise_ip overrides auto-detection."""
  1727. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1728. server = VirtualPrinterSSDPServer(
  1729. serial="TEST123",
  1730. name="TestPrinter",
  1731. model="BL-P001",
  1732. advertise_ip="10.0.0.50",
  1733. )
  1734. assert server._local_ip == "10.0.0.50"
  1735. def test_advertise_ip_empty_string_uses_auto_detect(self):
  1736. """Verify empty advertise_ip falls back to auto-detection."""
  1737. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1738. server = VirtualPrinterSSDPServer(
  1739. serial="TEST123",
  1740. name="TestPrinter",
  1741. model="BL-P001",
  1742. advertise_ip="",
  1743. )
  1744. assert server._local_ip is None
  1745. def test_advertise_ip_in_notify_message(self):
  1746. """Verify NOTIFY message uses the advertise_ip."""
  1747. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1748. server = VirtualPrinterSSDPServer(
  1749. serial="TEST123",
  1750. name="TestPrinter",
  1751. model="BL-P001",
  1752. advertise_ip="10.0.0.50",
  1753. )
  1754. message = server._build_notify_message()
  1755. assert b"Location: 10.0.0.50" in message
  1756. def test_advertise_ip_in_response_message(self):
  1757. """Verify M-SEARCH response uses the advertise_ip."""
  1758. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1759. server = VirtualPrinterSSDPServer(
  1760. serial="TEST123",
  1761. name="TestPrinter",
  1762. model="BL-P001",
  1763. advertise_ip="10.0.0.50",
  1764. )
  1765. message = server._build_response_message()
  1766. assert b"Location: 10.0.0.50" in message
  1767. def test_default_no_advertise_ip(self):
  1768. """Verify default constructor has None local_ip (auto-detect)."""
  1769. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1770. server = VirtualPrinterSSDPServer()
  1771. assert server._local_ip is None
  1772. class TestCertificateService:
  1773. """Tests for TLS certificate generation."""
  1774. @pytest.fixture
  1775. def cert_service(self, tmp_path):
  1776. """Create a CertificateService instance."""
  1777. from backend.app.services.virtual_printer.certificate import CertificateService
  1778. return CertificateService(cert_dir=tmp_path, serial="TEST123")
  1779. def test_generate_certificates(self, cert_service, tmp_path):
  1780. """Verify certificates are generated correctly."""
  1781. cert_path, key_path = cert_service.generate_certificates()
  1782. assert cert_path.exists()
  1783. assert key_path.exists()
  1784. # Verify certificate content
  1785. cert_content = cert_path.read_text()
  1786. assert "BEGIN CERTIFICATE" in cert_content
  1787. key_content = key_path.read_text()
  1788. assert "BEGIN" in key_content and "KEY" in key_content
  1789. def test_certificates_reused_if_exist(self, cert_service):
  1790. """Verify existing certificates are reused."""
  1791. # First generation
  1792. cert_path1, key_path1 = cert_service.generate_certificates()
  1793. mtime1 = cert_path1.stat().st_mtime
  1794. # Second call should reuse (via ensure_certificates)
  1795. cert_path2, key_path2 = cert_service.ensure_certificates()
  1796. mtime2 = cert_path2.stat().st_mtime
  1797. assert mtime1 == mtime2 # File wasn't regenerated
  1798. def test_delete_certificates(self, cert_service):
  1799. """Verify certificates can be deleted."""
  1800. cert_service.generate_certificates()
  1801. assert cert_service.cert_path.exists()
  1802. assert cert_service.key_path.exists()
  1803. cert_service.delete_certificates()
  1804. assert not cert_service.cert_path.exists()
  1805. assert not cert_service.key_path.exists()
  1806. def test_ensure_creates_if_not_exist(self, cert_service):
  1807. """Verify ensure_certificates generates if not existing."""
  1808. assert not cert_service.cert_path.exists()
  1809. cert_path, key_path = cert_service.ensure_certificates()
  1810. assert cert_path.exists()
  1811. assert key_path.exists()
  1812. class TestBindServer:
  1813. """Tests for BindServer (port 3002 bind/detect protocol)."""
  1814. @pytest.fixture
  1815. def bind_server(self):
  1816. """Create a BindServer instance."""
  1817. from backend.app.services.virtual_printer.bind_server import BindServer
  1818. return BindServer(
  1819. serial="09400A391800001",
  1820. model="O1D",
  1821. name="Bambuddy",
  1822. )
  1823. def test_build_frame(self, bind_server):
  1824. """Verify frame building produces correct format."""
  1825. payload = {"login": {"command": "detect"}}
  1826. frame = bind_server._build_frame(payload)
  1827. # Header: 0xA5A5
  1828. assert frame[:2] == b"\xa5\xa5"
  1829. # Trailer: 0xA7A7
  1830. assert frame[-2:] == b"\xa7\xa7"
  1831. # Length field is total message size (LE uint16)
  1832. import struct
  1833. total_len = struct.unpack_from("<H", frame, 2)[0]
  1834. assert total_len == len(frame)
  1835. # JSON payload is between header and trailer
  1836. import json
  1837. json_bytes = frame[4:-2]
  1838. parsed = json.loads(json_bytes)
  1839. assert parsed == payload
  1840. def test_parse_frame_valid(self, bind_server):
  1841. """Verify valid frame parsing extracts JSON correctly."""
  1842. import json
  1843. import struct
  1844. payload = {"login": {"command": "detect", "sequence_id": "20000"}}
  1845. json_bytes = json.dumps(payload, separators=(",", ":")).encode()
  1846. total_len = 4 + len(json_bytes) + 2
  1847. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + json_bytes + b"\xa7\xa7"
  1848. result = bind_server._parse_frame(frame)
  1849. assert result is not None
  1850. assert result["login"]["command"] == "detect"
  1851. assert result["login"]["sequence_id"] == "20000"
  1852. def test_parse_frame_invalid_header(self, bind_server):
  1853. """Verify invalid header returns None."""
  1854. result = bind_server._parse_frame(b"\xbb\xbb\x06\x00{}\xa7\xa7")
  1855. assert result is None
  1856. def test_parse_frame_invalid_trailer(self, bind_server):
  1857. """Verify invalid trailer returns None."""
  1858. result = bind_server._parse_frame(b"\xa5\xa5\x06\x00{}\xbb\xbb")
  1859. assert result is None
  1860. def test_parse_frame_too_short(self, bind_server):
  1861. """Verify short data returns None."""
  1862. result = bind_server._parse_frame(b"\xa5\xa5\x00")
  1863. assert result is None
  1864. def test_parse_frame_invalid_json(self, bind_server):
  1865. """Verify invalid JSON returns None."""
  1866. import struct
  1867. bad_json = b"not json"
  1868. total_len = 4 + len(bad_json) + 2
  1869. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  1870. result = bind_server._parse_frame(frame)
  1871. assert result is None
  1872. def test_build_frame_roundtrip(self, bind_server):
  1873. """Verify build_frame output can be parsed back."""
  1874. payload = {
  1875. "login": {
  1876. "bind": "free",
  1877. "command": "detect",
  1878. "connect": "lan",
  1879. "dev_cap": 1,
  1880. "id": "09400A391800001",
  1881. "model": "O1D",
  1882. "name": "Bambuddy",
  1883. "sequence_id": 3021,
  1884. "version": "01.00.00.00",
  1885. }
  1886. }
  1887. frame = bind_server._build_frame(payload)
  1888. parsed = bind_server._parse_frame(frame)
  1889. assert parsed is not None
  1890. assert parsed["login"]["id"] == "09400A391800001"
  1891. assert parsed["login"]["model"] == "O1D"
  1892. assert parsed["login"]["name"] == "Bambuddy"
  1893. assert parsed["login"]["bind"] == "free"
  1894. def test_bind_server_stores_config(self, bind_server):
  1895. """Verify bind server stores serial, model, name."""
  1896. assert bind_server.serial == "09400A391800001"
  1897. assert bind_server.model == "O1D"
  1898. assert bind_server.name == "Bambuddy"
  1899. assert bind_server.version == "01.00.00.00"
  1900. def test_bind_server_custom_version(self):
  1901. """Verify custom firmware version is stored."""
  1902. from backend.app.services.virtual_printer.bind_server import BindServer
  1903. server = BindServer(
  1904. serial="TEST123",
  1905. model="C13",
  1906. name="Test",
  1907. version="02.03.04.05",
  1908. )
  1909. assert server.version == "02.03.04.05"
  1910. def test_bind_ports_constant(self):
  1911. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  1912. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  1913. assert 3000 in BIND_PORTS
  1914. assert 3002 in BIND_PORTS
  1915. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  1916. """Verify bind server starts with empty servers list."""
  1917. assert bind_server._servers == []
  1918. assert bind_server._running is False
  1919. class TestSlicerProxyManager:
  1920. """Tests for SlicerProxyManager (proxy mode)."""
  1921. @pytest.fixture
  1922. def proxy_manager(self, tmp_path):
  1923. """Create a SlicerProxyManager instance."""
  1924. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  1925. # Create dummy cert files
  1926. cert_path = tmp_path / "cert.pem"
  1927. key_path = tmp_path / "key.pem"
  1928. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1929. # Split string to avoid pre-commit hook false positive on test data
  1930. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1931. return SlicerProxyManager(
  1932. target_host="192.168.1.100",
  1933. cert_path=cert_path,
  1934. key_path=key_path,
  1935. )
  1936. def test_proxy_manager_initializes_ports(self, proxy_manager):
  1937. """Verify proxy manager has correct port constants."""
  1938. # FTP proxy uses privileged port 990 to match what Bambu Studio expects
  1939. assert proxy_manager.LOCAL_FTP_PORT == 990
  1940. assert proxy_manager.LOCAL_MQTT_PORT == 8883
  1941. assert proxy_manager.PRINTER_FTP_PORT == 990
  1942. assert proxy_manager.PRINTER_MQTT_PORT == 8883
  1943. assert proxy_manager.PRINTER_FILE_TRANSFER_PORT == 6000
  1944. assert proxy_manager.PRINTER_RTSP_PORT == 322
  1945. # Auxiliary ports: undocumented proprietary ports for A1/P1S etc.
  1946. assert proxy_manager.PRINTER_AUX_PORTS == [2024, 2025, 2026]
  1947. # Bind ports: both 3000 and 3002 for slicer compatibility
  1948. assert proxy_manager.PRINTER_BIND_PORTS == [3000, 3002]
  1949. # FTP data port range for transparent EPSV proxying
  1950. assert proxy_manager.FTP_DATA_PORT_MIN == 50000
  1951. assert proxy_manager.FTP_DATA_PORT_MAX == 50100
  1952. def test_proxy_manager_stores_target_host(self, proxy_manager):
  1953. """Verify proxy manager stores target host."""
  1954. assert proxy_manager.target_host == "192.168.1.100"
  1955. def test_get_status_before_start(self, proxy_manager):
  1956. """Verify get_status returns zeros before start."""
  1957. status = proxy_manager.get_status()
  1958. assert status["running"] is False
  1959. assert status["ftp_connections"] == 0
  1960. assert status["mqtt_connections"] == 0
  1961. @pytest.mark.asyncio
  1962. async def test_proxy_start_creates_transparent_proxies(self, tmp_path):
  1963. """Verify start() uses TCPProxy for FTP/FileTransfer/RTSP and TLSProxy only for MQTT.
  1964. The transparent proxy architecture preserves end-to-end TLS between
  1965. slicer and printer for all protocols except MQTT, which must be
  1966. TLS-terminated to rewrite the printer's IP in MQTT payloads.
  1967. """
  1968. from unittest.mock import AsyncMock, patch
  1969. from backend.app.services.virtual_printer.tcp_proxy import (
  1970. SlicerProxyManager,
  1971. TCPProxy,
  1972. TLSProxy,
  1973. )
  1974. cert_path = tmp_path / "cert.pem"
  1975. key_path = tmp_path / "key.pem"
  1976. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  1977. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  1978. mgr = SlicerProxyManager(
  1979. target_host="192.168.1.100",
  1980. cert_path=cert_path,
  1981. key_path=key_path,
  1982. bind_address="10.0.0.1",
  1983. )
  1984. # Mock asyncio.create_task and asyncio.gather to prevent actual server start
  1985. with (
  1986. patch("asyncio.create_task") as mock_create_task,
  1987. patch("asyncio.gather", new_callable=AsyncMock),
  1988. patch.object(SlicerProxyManager, "_log_activity"),
  1989. ):
  1990. mock_create_task.return_value = MagicMock()
  1991. # start() will create proxies then try to gather tasks — we just
  1992. # need to verify the proxy types after creation.
  1993. # Trigger start but let gather return immediately.
  1994. await mgr.start()
  1995. # FTP, FileTransfer, RTSP should be TCPProxy (transparent)
  1996. assert isinstance(mgr._ftp_proxy, TCPProxy), "FTP should be TCPProxy (transparent)"
  1997. assert isinstance(mgr._file_transfer_proxy, TCPProxy), "FileTransfer should be TCPProxy"
  1998. assert isinstance(mgr._rtsp_proxy, TCPProxy), "RTSP should be TCPProxy"
  1999. # MQTT should be TLSProxy (TLS-terminated for IP rewriting)
  2000. assert isinstance(mgr._mqtt_proxy, TLSProxy), "MQTT should be TLSProxy (TLS-terminated)"
  2001. # Auxiliary ports (2024-2026) should be TCPProxy (transparent)
  2002. assert len(mgr._aux_proxies) == 3, "Should have 3 aux port proxies"
  2003. for ap in mgr._aux_proxies:
  2004. assert isinstance(ap, TCPProxy), "Aux proxies should be TCPProxy"
  2005. assert mgr._aux_proxies[0].listen_port == 2024
  2006. assert mgr._aux_proxies[0].target_port == 2024
  2007. assert mgr._aux_proxies[2].listen_port == 2026
  2008. # FTP data ports should be pre-created as TCPProxy instances
  2009. assert len(mgr._ftp_data_proxies) == 101 # 50000-50100 inclusive
  2010. for dp in mgr._ftp_data_proxies:
  2011. assert isinstance(dp, TCPProxy), "FTP data proxies should be TCPProxy"
  2012. # Verify FTP data proxies target the same port on the printer
  2013. first_dp = mgr._ftp_data_proxies[0]
  2014. assert first_dp.listen_port == 50000
  2015. assert first_dp.target_port == 50000
  2016. assert first_dp.target_host == "192.168.1.100"
  2017. last_dp = mgr._ftp_data_proxies[-1]
  2018. assert last_dp.listen_port == 50100
  2019. assert last_dp.target_port == 50100
  2020. def test_proxy_manager_mqtt_has_ip_rewriting(self, tmp_path):
  2021. """Verify MQTT proxy is configured with IP rewriting when bind_address is set."""
  2022. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  2023. cert_path = tmp_path / "cert.pem"
  2024. key_path = tmp_path / "key.pem"
  2025. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  2026. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  2027. mgr = SlicerProxyManager(
  2028. target_host="192.168.1.100",
  2029. cert_path=cert_path,
  2030. key_path=key_path,
  2031. bind_address="10.0.0.1",
  2032. )
  2033. # Before start, proxies are None — verify constructor stores rewrite config
  2034. assert mgr.bind_address == "10.0.0.1"
  2035. assert mgr.target_host == "192.168.1.100"
  2036. class TestSSDPProxy:
  2037. """Tests for SSDPProxy (cross-network SSDP relay)."""
  2038. @pytest.fixture
  2039. def ssdp_proxy(self):
  2040. """Create an SSDPProxy instance."""
  2041. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2042. return SSDPProxy(
  2043. local_interface_ip="192.168.1.100",
  2044. remote_interface_ip="10.0.0.100",
  2045. target_printer_ip="192.168.1.50",
  2046. )
  2047. def test_ssdp_proxy_stores_interface_ips(self, ssdp_proxy):
  2048. """Verify SSDPProxy stores interface IPs correctly."""
  2049. assert ssdp_proxy.local_interface_ip == "192.168.1.100"
  2050. assert ssdp_proxy.remote_interface_ip == "10.0.0.100"
  2051. assert ssdp_proxy.target_printer_ip == "192.168.1.50"
  2052. def test_rewrite_ssdp_location(self, ssdp_proxy):
  2053. """Verify SSDP Location header is rewritten to remote interface IP."""
  2054. original_packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: TestPrinter\r\n\r\n"
  2055. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  2056. # Location should be changed to remote interface IP
  2057. assert b"Location: 10.0.0.100" in rewritten
  2058. assert b"Location: 192.168.1.50" not in rewritten
  2059. # Other headers should be preserved
  2060. assert b"DevName.bambu.com: TestPrinter" in rewritten
  2061. def test_rewrite_ssdp_location_case_insensitive(self, ssdp_proxy):
  2062. """Verify SSDP Location rewrite is case insensitive."""
  2063. original_packet = b"NOTIFY * HTTP/1.1\r\nlocation: 192.168.1.50\r\n\r\n"
  2064. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  2065. assert b"10.0.0.100" in rewritten
  2066. def test_rewrite_ssdp_location_no_match(self, ssdp_proxy):
  2067. """Verify packet without Location header is returned unchanged."""
  2068. original_packet = b"NOTIFY * HTTP/1.1\r\nDevName.bambu.com: Test\r\n\r\n"
  2069. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  2070. # No Location header, but _rewrite_ssdp logs a warning and returns as-is
  2071. assert b"DevName.bambu.com: Test" in rewritten
  2072. def test_parse_ssdp_message(self, ssdp_proxy):
  2073. """Verify SSDP message parsing extracts headers."""
  2074. packet = (
  2075. b"NOTIFY * HTTP/1.1\r\n"
  2076. b"Location: 192.168.1.50\r\n"
  2077. b"DevName.bambu.com: TestPrinter\r\n"
  2078. b"DevModel.bambu.com: BL-P001\r\n"
  2079. b"\r\n"
  2080. )
  2081. headers = ssdp_proxy._parse_ssdp_message(packet)
  2082. assert headers["location"] == "192.168.1.50"
  2083. assert headers["devname.bambu.com"] == "TestPrinter"
  2084. assert headers["devmodel.bambu.com"] == "BL-P001"
  2085. class TestVirtualPrinterManagerDirectories:
  2086. """Tests for VirtualPrinterManager directory management."""
  2087. def test_ensure_base_directories_creates_subdirs(self, tmp_path):
  2088. """Verify _ensure_base_directories creates required base directories."""
  2089. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  2090. manager = VirtualPrinterManager()
  2091. manager._base_dir = tmp_path / "virtual_printer"
  2092. manager._ensure_base_directories()
  2093. assert (tmp_path / "virtual_printer").exists()
  2094. assert (tmp_path / "virtual_printer" / "uploads").exists()
  2095. assert (tmp_path / "virtual_printer" / "certs").exists()
  2096. def test_ensure_base_directories_handles_permission_error(self, tmp_path, caplog):
  2097. """Verify _ensure_base_directories logs error on permission failure."""
  2098. import logging
  2099. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  2100. manager = VirtualPrinterManager()
  2101. vp_dir = tmp_path / "virtual_printer"
  2102. manager._base_dir = vp_dir
  2103. original_mkdir = type(vp_dir).mkdir
  2104. def mock_mkdir(self, *args, **kwargs):
  2105. if "virtual_printer" in str(self):
  2106. raise PermissionError("Permission denied")
  2107. return original_mkdir(self, *args, **kwargs)
  2108. with caplog.at_level(logging.ERROR), patch.object(type(vp_dir), "mkdir", mock_mkdir):
  2109. manager._ensure_base_directories()
  2110. assert "Permission denied" in caplog.text
  2111. def test_instance_creates_per_vp_directories(self, tmp_path):
  2112. """Verify VirtualPrinterInstance creates per-VP upload and cert dirs."""
  2113. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2114. VirtualPrinterInstance(
  2115. vp_id=42,
  2116. name="Test",
  2117. mode="archive",
  2118. model="C11",
  2119. access_code="12345678",
  2120. serial_suffix="391800042",
  2121. base_dir=tmp_path,
  2122. )
  2123. assert (tmp_path / "uploads" / "42").exists()
  2124. assert (tmp_path / "uploads" / "42" / "cache").exists()
  2125. assert (tmp_path / "certs" / "42").exists()
  2126. class TestVirtualPrinterInstanceProxyMode:
  2127. """Tests for VirtualPrinterInstance proxy mode."""
  2128. @pytest.fixture
  2129. def proxy_instance(self, tmp_path):
  2130. """Create a proxy-mode VirtualPrinterInstance."""
  2131. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2132. return VirtualPrinterInstance(
  2133. vp_id=10,
  2134. name="ProxyTest",
  2135. mode="proxy",
  2136. model="C11",
  2137. access_code="",
  2138. serial_suffix="391800010",
  2139. target_printer_ip="192.168.1.100",
  2140. target_printer_serial="01P00A000000001",
  2141. base_dir=tmp_path,
  2142. )
  2143. def test_proxy_instance_properties(self, proxy_instance):
  2144. """Verify proxy instance stores config correctly."""
  2145. assert proxy_instance.is_proxy is True
  2146. assert proxy_instance.mode == "proxy"
  2147. assert proxy_instance.target_printer_ip == "192.168.1.100"
  2148. assert proxy_instance.target_printer_serial == "01P00A000000001"
  2149. def test_proxy_instance_does_not_require_access_code(self, proxy_instance):
  2150. """Verify proxy mode can have empty access code."""
  2151. assert proxy_instance.access_code == ""
  2152. def test_get_status_proxy_includes_proxy_fields(self, proxy_instance):
  2153. """Verify get_status includes proxy fields when proxy is active."""
  2154. mock_proxy = MagicMock()
  2155. mock_proxy.get_status.return_value = {
  2156. "running": True,
  2157. "ftp_port": 990,
  2158. "mqtt_port": 8883,
  2159. "ftp_connections": 1,
  2160. "mqtt_connections": 2,
  2161. "target_host": "192.168.1.100",
  2162. }
  2163. proxy_instance._proxy = mock_proxy
  2164. status = proxy_instance.get_status()
  2165. assert "proxy" in status
  2166. assert status["proxy"]["ftp_port"] == 990
  2167. assert status["proxy"]["mqtt_connections"] == 2
  2168. def test_proxy_instance_stores_remote_interface(self, tmp_path):
  2169. """Verify proxy instance stores remote_interface_ip."""
  2170. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2171. inst = VirtualPrinterInstance(
  2172. vp_id=11,
  2173. name="Proxy2",
  2174. mode="proxy",
  2175. model="C11",
  2176. access_code="",
  2177. serial_suffix="391800011",
  2178. target_printer_ip="192.168.1.100",
  2179. remote_interface_ip="10.0.0.50",
  2180. base_dir=tmp_path,
  2181. )
  2182. assert inst.remote_interface_ip == "10.0.0.50"
  2183. class TestVirtualPrinterInstanceIPOverride:
  2184. """Tests for remote_interface_ip and bind_ip on VirtualPrinterInstance."""
  2185. @pytest.fixture
  2186. def instance_with_remote_ip(self, tmp_path):
  2187. """Create an instance with remote_interface_ip set."""
  2188. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2189. return VirtualPrinterInstance(
  2190. vp_id=20,
  2191. name="IPTest",
  2192. mode="archive",
  2193. model="BL-P001",
  2194. access_code="12345678",
  2195. serial_suffix="391800020",
  2196. bind_ip="192.168.1.50",
  2197. remote_interface_ip="10.0.0.50",
  2198. base_dir=tmp_path,
  2199. )
  2200. def test_instance_stores_bind_ip(self, instance_with_remote_ip):
  2201. """Verify bind_ip is stored."""
  2202. assert instance_with_remote_ip.bind_ip == "192.168.1.50"
  2203. def test_instance_stores_remote_interface_ip(self, instance_with_remote_ip):
  2204. """Verify remote_interface_ip is stored."""
  2205. assert instance_with_remote_ip.remote_interface_ip == "10.0.0.50"
  2206. def test_generate_certificates_includes_remote_and_bind_ip(self, instance_with_remote_ip):
  2207. """Verify generate_certificates passes remote_interface_ip and bind_ip as SANs."""
  2208. with (
  2209. patch.object(instance_with_remote_ip._cert_service, "delete_printer_certificate"),
  2210. patch.object(
  2211. instance_with_remote_ip._cert_service,
  2212. "generate_certificates",
  2213. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2214. ) as mock_gen,
  2215. ):
  2216. instance_with_remote_ip.generate_certificates()
  2217. mock_gen.assert_called_once_with(additional_ips=["10.0.0.50", "192.168.1.50"])
  2218. def test_generate_certificates_no_remote_ip(self, tmp_path):
  2219. """Verify generate_certificates passes only bind_ip when no remote_interface_ip."""
  2220. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2221. inst = VirtualPrinterInstance(
  2222. vp_id=21,
  2223. name="NoRemote",
  2224. mode="archive",
  2225. model="BL-P001",
  2226. access_code="12345678",
  2227. serial_suffix="391800021",
  2228. bind_ip="192.168.1.50",
  2229. base_dir=tmp_path,
  2230. )
  2231. with (
  2232. patch.object(inst._cert_service, "delete_printer_certificate"),
  2233. patch.object(
  2234. inst._cert_service,
  2235. "generate_certificates",
  2236. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2237. ) as mock_gen,
  2238. ):
  2239. inst.generate_certificates()
  2240. mock_gen.assert_called_once_with(additional_ips=["192.168.1.50"])
  2241. def test_generate_certificates_no_ips(self, tmp_path):
  2242. """Verify generate_certificates passes None when no IPs configured."""
  2243. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2244. inst = VirtualPrinterInstance(
  2245. vp_id=22,
  2246. name="NoIPs",
  2247. mode="archive",
  2248. model="BL-P001",
  2249. access_code="12345678",
  2250. serial_suffix="391800022",
  2251. base_dir=tmp_path,
  2252. )
  2253. with (
  2254. patch.object(inst._cert_service, "delete_printer_certificate"),
  2255. patch.object(
  2256. inst._cert_service,
  2257. "generate_certificates",
  2258. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2259. ) as mock_gen,
  2260. ):
  2261. inst.generate_certificates()
  2262. mock_gen.assert_called_once_with(additional_ips=None)
  2263. class TestBindServer:
  2264. """Tests for the BindServer (port 3002 bind/detect protocol)."""
  2265. @pytest.fixture
  2266. def bind_server(self):
  2267. """Create a BindServer instance."""
  2268. from backend.app.services.virtual_printer.bind_server import BindServer
  2269. return BindServer(
  2270. serial="01S00C000000001",
  2271. model="BL-P001",
  2272. name="Bambuddy",
  2273. )
  2274. def test_build_frame(self, bind_server):
  2275. """Verify frame format: 0xA5A5 + len(u16le) + JSON + 0xA7A7."""
  2276. payload = {"login": {"command": "detect"}}
  2277. frame = bind_server._build_frame(payload)
  2278. assert frame[:2] == b"\xa5\xa5"
  2279. assert frame[-2:] == b"\xa7\xa7"
  2280. # Length field is total message size
  2281. import struct
  2282. total_len = struct.unpack_from("<H", frame, 2)[0]
  2283. assert total_len == len(frame)
  2284. # JSON payload is between header and trailer
  2285. import json
  2286. json_bytes = frame[4:-2]
  2287. parsed = json.loads(json_bytes)
  2288. assert parsed == payload
  2289. def test_parse_frame_valid(self, bind_server):
  2290. """Verify valid frame parsing."""
  2291. frame = bind_server._build_frame({"login": {"command": "detect", "sequence_id": "20000"}})
  2292. result = bind_server._parse_frame(frame)
  2293. assert result is not None
  2294. assert result["login"]["command"] == "detect"
  2295. assert result["login"]["sequence_id"] == "20000"
  2296. def test_parse_frame_invalid_header(self, bind_server):
  2297. """Verify invalid header returns None."""
  2298. frame = b"\xb5\xb5\x10\x00" + b'{"login":{}}' + b"\xa7\xa7"
  2299. assert bind_server._parse_frame(frame) is None
  2300. def test_parse_frame_invalid_trailer(self, bind_server):
  2301. """Verify invalid trailer returns None."""
  2302. frame = b"\xa5\xa5\x10\x00" + b'{"login":{}}' + b"\xb7\xb7"
  2303. assert bind_server._parse_frame(frame) is None
  2304. def test_parse_frame_too_short(self, bind_server):
  2305. """Verify short data returns None."""
  2306. assert bind_server._parse_frame(b"\xa5\xa5\x00") is None
  2307. assert bind_server._parse_frame(b"") is None
  2308. def test_parse_frame_invalid_json(self, bind_server):
  2309. """Verify invalid JSON returns None."""
  2310. import struct
  2311. bad_json = b"not json"
  2312. total_len = 4 + len(bad_json) + 2
  2313. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  2314. assert bind_server._parse_frame(frame) is None
  2315. def test_build_frame_roundtrip(self, bind_server):
  2316. """Verify build then parse roundtrip."""
  2317. original = {"login": {"bind": "free", "command": "detect", "id": "01S00C000000001"}}
  2318. frame = bind_server._build_frame(original)
  2319. parsed = bind_server._parse_frame(frame)
  2320. assert parsed == original
  2321. def test_bind_server_stores_config(self, bind_server):
  2322. """Verify config is stored correctly."""
  2323. assert bind_server.serial == "01S00C000000001"
  2324. assert bind_server.model == "BL-P001"
  2325. assert bind_server.name == "Bambuddy"
  2326. assert bind_server.version == "01.00.00.00"
  2327. def test_bind_server_custom_version(self):
  2328. """Verify custom firmware version is stored."""
  2329. from backend.app.services.virtual_printer.bind_server import BindServer
  2330. server = BindServer(
  2331. serial="01S00C000000001",
  2332. model="BL-P001",
  2333. name="Bambuddy",
  2334. version="01.09.00.10",
  2335. )
  2336. assert server.version == "01.09.00.10"
  2337. def test_bind_ports_includes_both(self):
  2338. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  2339. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  2340. assert 3000 in BIND_PORTS
  2341. assert 3002 in BIND_PORTS
  2342. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  2343. """Verify bind server starts with empty servers list."""
  2344. assert bind_server._servers == []
  2345. assert bind_server._running is False
  2346. @pytest.mark.asyncio
  2347. async def test_start_server_creates_bind_server(self, tmp_path):
  2348. """Verify start_server creates BindServer with correct params."""
  2349. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2350. inst = VirtualPrinterInstance(
  2351. vp_id=99,
  2352. name="Bambuddy",
  2353. mode="archive",
  2354. model="BL-P001",
  2355. access_code="12345678",
  2356. serial_suffix="391800099",
  2357. bind_ip="192.168.1.50",
  2358. base_dir=tmp_path,
  2359. )
  2360. # Each mocked child service exposes a real asyncio.Event for the
  2361. # readiness barrier added in start_server (set on instantiation so
  2362. # the barrier returns immediately in tests).
  2363. ready_event = asyncio.Event()
  2364. ready_event.set()
  2365. def with_ready(*_args, **_kwargs):
  2366. child = MagicMock()
  2367. child.ready = ready_event
  2368. return child
  2369. with (
  2370. patch(
  2371. "backend.app.services.virtual_printer.manager.VirtualPrinterSSDPServer",
  2372. side_effect=with_ready,
  2373. ),
  2374. patch(
  2375. "backend.app.services.virtual_printer.manager.VirtualPrinterFTPServer",
  2376. side_effect=with_ready,
  2377. ),
  2378. patch(
  2379. "backend.app.services.virtual_printer.manager.SimpleMQTTServer",
  2380. side_effect=with_ready,
  2381. ),
  2382. patch(
  2383. "backend.app.services.virtual_printer.manager.BindServer",
  2384. side_effect=with_ready,
  2385. ) as mock_bind_cls,
  2386. patch.object(inst._cert_service, "delete_printer_certificate"),
  2387. patch.object(
  2388. inst._cert_service,
  2389. "generate_certificates",
  2390. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2391. ),
  2392. ):
  2393. await inst.start_server()
  2394. mock_bind_cls.assert_called_once_with(
  2395. serial=inst.serial,
  2396. model="BL-P001",
  2397. name="Bambuddy",
  2398. bind_address="192.168.1.50",
  2399. cert_path=Path("/tmp/cert.pem"), # nosec B108
  2400. key_path=Path("/tmp/key.pem"), # nosec B108
  2401. )
  2402. class TestResolveModelCodes:
  2403. """Tests for model code resolution (display name → SSDP code)."""
  2404. def test_display_name_to_model_code_maps_all_models(self):
  2405. """Verify reverse mapping covers all VIRTUAL_PRINTER_MODELS entries."""
  2406. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE, VIRTUAL_PRINTER_MODELS
  2407. for _code, display_name in VIRTUAL_PRINTER_MODELS.items():
  2408. assert display_name in DISPLAY_NAME_TO_MODEL_CODE
  2409. # For non-duplicate display names, should map back to a valid code
  2410. assert DISPLAY_NAME_TO_MODEL_CODE[display_name] in VIRTUAL_PRINTER_MODELS
  2411. def test_resolve_printer_model_with_ssdp_code(self):
  2412. """SSDP codes pass through unchanged."""
  2413. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2414. assert _resolve_printer_model("BL-P001") == "BL-P001"
  2415. assert _resolve_printer_model("O1D") == "O1D"
  2416. assert _resolve_printer_model("N2S") == "N2S"
  2417. def test_resolve_printer_model_with_display_name(self):
  2418. """Display names resolve to SSDP codes."""
  2419. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2420. assert _resolve_printer_model("X1C") == "BL-P001"
  2421. assert _resolve_printer_model("H2D") == "O1D"
  2422. assert _resolve_printer_model("A1") == "N2S"
  2423. assert _resolve_printer_model("P1S") == "C12"
  2424. def test_resolve_printer_model_with_none_or_unknown(self):
  2425. """None and unknown values return None."""
  2426. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2427. assert _resolve_printer_model(None) is None
  2428. assert _resolve_printer_model("UnknownModel") is None
  2429. class TestMqttIpRewrite:
  2430. """Tests for TLSProxy._rewrite_mqtt_ip() MQTT packet IP rewriting."""
  2431. @staticmethod
  2432. def _build_mqtt_publish(topic: str, payload: bytes) -> bytes:
  2433. """Build a minimal MQTT PUBLISH packet."""
  2434. # PUBLISH fixed header: type 3, no flags
  2435. topic_bytes = topic.encode("utf-8")
  2436. # Variable header: topic length (2 bytes) + topic
  2437. var_header = len(topic_bytes).to_bytes(2, "big") + topic_bytes
  2438. body = var_header + payload
  2439. # Encode remaining length
  2440. remaining = len(body)
  2441. header = bytearray([0x30]) # PUBLISH, QoS 0
  2442. while True:
  2443. encoded_byte = remaining % 128
  2444. remaining //= 128
  2445. if remaining > 0:
  2446. encoded_byte |= 0x80
  2447. header.append(encoded_byte)
  2448. if remaining == 0:
  2449. break
  2450. return bytes(header) + body
  2451. @staticmethod
  2452. def _build_mqtt_pingreq() -> bytes:
  2453. """Build an MQTT PINGREQ packet (2 bytes, no payload)."""
  2454. return b"\xc0\x00"
  2455. def test_rewrite_ip_in_publish(self):
  2456. """IP string in PUBLISH payload is rewritten."""
  2457. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2458. payload = b'{"rtsp_url":"rtsps://192.168.1.100:322/live"}'
  2459. packet = self._build_mqtt_publish("device/status", payload)
  2460. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  2461. assert b"10.0.0.1" in result
  2462. assert b"192.168.1.100" not in result
  2463. def test_no_rewrite_when_ip_absent(self):
  2464. """Packets without the target IP are passed through unchanged."""
  2465. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2466. payload = b'{"status":"idle"}'
  2467. packet = self._build_mqtt_publish("device/status", payload)
  2468. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  2469. assert result == packet
  2470. def test_non_publish_packets_unchanged(self):
  2471. """Non-PUBLISH packets (e.g. PINGREQ) are never rewritten."""
  2472. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2473. pingreq = self._build_mqtt_pingreq()
  2474. result, buf = TLSProxy._rewrite_mqtt_ip(pingreq, b"192.168.1.100", b"10.0.0.1", bytearray())
  2475. assert result == pingreq
  2476. def test_rewrite_preserves_packet_framing(self):
  2477. """Rewritten packet has valid MQTT remaining length."""
  2478. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2479. # Use IPs of different lengths to test length re-encoding
  2480. old_ip = b"192.168.255.133" # 15 bytes
  2481. new_ip = b"10.0.0.1" # 8 bytes
  2482. payload = b'{"ip":"192.168.255.133"}'
  2483. packet = self._build_mqtt_publish("device/status", payload)
  2484. result, buf = TLSProxy._rewrite_mqtt_ip(packet, old_ip, new_ip, bytearray())
  2485. # Parse the result to verify framing
  2486. assert result[0] == 0x30 # PUBLISH header byte
  2487. # Decode remaining length
  2488. pos = 1
  2489. remaining = 0
  2490. multiplier = 1
  2491. while True:
  2492. b = result[pos]
  2493. pos += 1
  2494. remaining += (b & 0x7F) * multiplier
  2495. multiplier *= 128
  2496. if (b & 0x80) == 0:
  2497. break
  2498. # Remaining length should match actual data
  2499. assert pos + remaining == len(result)
  2500. assert new_ip in result
  2501. def test_incomplete_packet_buffered(self):
  2502. """Incomplete packet at end of chunk is buffered for next call."""
  2503. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2504. payload = b'{"ip":"192.168.1.100"}'
  2505. packet = self._build_mqtt_publish("device/status", payload)
  2506. # Split packet in the middle
  2507. half = len(packet) // 2
  2508. chunk1 = packet[:half]
  2509. chunk2 = packet[half:]
  2510. result1, buf = TLSProxy._rewrite_mqtt_ip(chunk1, b"192.168.1.100", b"10.0.0.1", bytearray())
  2511. # First chunk should be buffered (incomplete packet)
  2512. assert len(buf) > 0
  2513. result2, buf = TLSProxy._rewrite_mqtt_ip(chunk2, b"192.168.1.100", b"10.0.0.1", buf)
  2514. # Second chunk completes the packet, IP should be rewritten
  2515. combined = result1 + result2
  2516. assert b"10.0.0.1" in combined
  2517. assert b"192.168.1.100" not in combined
  2518. def test_multiple_packets_in_one_chunk(self):
  2519. """Multiple MQTT packets in a single chunk are all processed."""
  2520. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2521. payload1 = b'{"ip":"192.168.1.100"}'
  2522. payload2 = b'{"other":"data"}'
  2523. packet1 = self._build_mqtt_publish("topic1", payload1)
  2524. packet2 = self._build_mqtt_publish("topic2", payload2)
  2525. combined = packet1 + packet2
  2526. result, buf = TLSProxy._rewrite_mqtt_ip(combined, b"192.168.1.100", b"10.0.0.1", bytearray())
  2527. assert b"10.0.0.1" in result
  2528. assert b"192.168.1.100" not in result
  2529. # Second packet should still be present
  2530. assert b"other" in result
  2531. def test_extra_replacements(self):
  2532. """Extra replacement pairs (e.g. integer IP) are also applied."""
  2533. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2534. payload = b'{"net":{"info":[{"ip":2248124608}]}}'
  2535. packet = self._build_mqtt_publish("device/status", payload)
  2536. result, buf = TLSProxy._rewrite_mqtt_ip(
  2537. packet,
  2538. b"NOMATCH",
  2539. b"NOREPLACE",
  2540. bytearray(),
  2541. extra_replacements=[(b"2248124608", b"285190336")],
  2542. )
  2543. assert b"285190336" in result
  2544. assert b"2248124608" not in result
  2545. class TestIpToLeIntBytes:
  2546. """Tests for TLSProxy._ip_to_le_int_bytes() integer IP conversion."""
  2547. def test_converts_ip_to_le_int(self):
  2548. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2549. assert TLSProxy._ip_to_le_int_bytes("192.168.255.133") == b"2248124608"
  2550. assert TLSProxy._ip_to_le_int_bytes("192.168.255.16") == b"285190336"
  2551. assert TLSProxy._ip_to_le_int_bytes("10.0.0.1") == b"16777226"
  2552. def test_roundtrip(self):
  2553. """Verify the integer converts back to the correct IP."""
  2554. import struct
  2555. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2556. for ip in ["192.168.1.1", "10.0.0.1", "172.16.0.100", "192.168.255.133"]:
  2557. le_int = int(TLSProxy._ip_to_le_int_bytes(ip))
  2558. parts = ip.split(".")
  2559. expected = struct.unpack("<I", bytes(int(p) for p in parts))[0]
  2560. assert le_int == expected
  2561. class TestSSDPProxyName:
  2562. """Tests for SSDPProxy VP name rewriting."""
  2563. @pytest.fixture
  2564. def ssdp_proxy_with_name(self):
  2565. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2566. return SSDPProxy(
  2567. local_interface_ip="192.168.1.100",
  2568. remote_interface_ip="10.0.0.100",
  2569. target_printer_ip="192.168.1.50",
  2570. name="H2D-1 Proxy",
  2571. )
  2572. @pytest.fixture
  2573. def ssdp_proxy_without_name(self):
  2574. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2575. return SSDPProxy(
  2576. local_interface_ip="192.168.1.100",
  2577. remote_interface_ip="10.0.0.100",
  2578. target_printer_ip="192.168.1.50",
  2579. )
  2580. def test_rewrite_uses_configured_name(self, ssdp_proxy_with_name):
  2581. """When name is set, DevName is replaced entirely."""
  2582. packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: RealPrinter\r\nDevBind.bambu.com: cloud\r\n\r\n"
  2583. rewritten = ssdp_proxy_with_name._rewrite_ssdp(packet)
  2584. assert b"DevName.bambu.com: H2D-1 Proxy" in rewritten
  2585. assert b"RealPrinter" not in rewritten
  2586. def test_rewrite_appends_proxy_without_name(self, ssdp_proxy_without_name):
  2587. """When no name is set, ' - Proxy' is appended to the real name."""
  2588. packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: RealPrinter\r\nDevBind.bambu.com: cloud\r\n\r\n"
  2589. rewritten = ssdp_proxy_without_name._rewrite_ssdp(packet)
  2590. assert b"DevName.bambu.com: RealPrinter - Proxy" in rewritten