test_virtual_printer.py 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590
  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_gcode_injection_on(self, tmp_path):
  480. """#1516: queue items opt into injection when the VP has gcode_injection=True."""
  481. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  482. mock_db = AsyncMock()
  483. added_items = []
  484. mock_db.add = MagicMock(side_effect=added_items.append)
  485. mock_db.commit = AsyncMock()
  486. mock_session_factory = MagicMock()
  487. mock_session_ctx = AsyncMock()
  488. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  489. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  490. mock_session_factory.return_value = mock_session_ctx
  491. inst = VirtualPrinterInstance(
  492. vp_id=13,
  493. name="InjectOn",
  494. mode="queue",
  495. model="C11",
  496. access_code="12345678",
  497. serial_suffix="391800013",
  498. gcode_injection=True,
  499. base_dir=tmp_path,
  500. session_factory=mock_session_factory,
  501. )
  502. file_path = tmp_path / "test.3mf"
  503. file_path.write_bytes(b"fake3mf")
  504. mock_archive = MagicMock()
  505. mock_archive.id = 1
  506. mock_archive.print_name = "test"
  507. with (
  508. patch(
  509. "backend.app.api.routes.settings.get_setting",
  510. new_callable=AsyncMock,
  511. return_value=None,
  512. ),
  513. patch(
  514. "backend.app.services.archive.ArchiveService.archive_print",
  515. new_callable=AsyncMock,
  516. return_value=mock_archive,
  517. ),
  518. ):
  519. await inst._add_to_print_queue(file_path, "192.168.1.100")
  520. assert len(added_items) == 1
  521. assert added_items[0].gcode_injection is True
  522. @pytest.mark.asyncio
  523. async def test_add_to_print_queue_gcode_injection_off_by_default(self, tmp_path):
  524. """#1516: queue items do NOT inject when the VP leaves gcode_injection at its default."""
  525. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  526. mock_db = AsyncMock()
  527. added_items = []
  528. mock_db.add = MagicMock(side_effect=added_items.append)
  529. mock_db.commit = AsyncMock()
  530. mock_session_factory = MagicMock()
  531. mock_session_ctx = AsyncMock()
  532. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  533. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  534. mock_session_factory.return_value = mock_session_ctx
  535. inst = VirtualPrinterInstance(
  536. vp_id=14,
  537. name="InjectOff",
  538. mode="queue",
  539. model="C11",
  540. access_code="12345678",
  541. serial_suffix="391800014",
  542. base_dir=tmp_path,
  543. session_factory=mock_session_factory,
  544. )
  545. file_path = tmp_path / "test.3mf"
  546. file_path.write_bytes(b"fake3mf")
  547. mock_archive = MagicMock()
  548. mock_archive.id = 1
  549. mock_archive.print_name = "test"
  550. with (
  551. patch(
  552. "backend.app.api.routes.settings.get_setting",
  553. new_callable=AsyncMock,
  554. return_value=None,
  555. ),
  556. patch(
  557. "backend.app.services.archive.ArchiveService.archive_print",
  558. new_callable=AsyncMock,
  559. return_value=mock_archive,
  560. ),
  561. ):
  562. await inst._add_to_print_queue(file_path, "192.168.1.100")
  563. assert len(added_items) == 1
  564. assert added_items[0].gcode_injection is False
  565. @pytest.mark.asyncio
  566. async def test_add_to_print_queue_uses_workflow_defaults_from_settings(self, tmp_path):
  567. """#1235: VP queue-mode constructed PrintQueueItem without specifying
  568. bed_levelling / flow_cali / vibration_cali / layer_inspect / timelapse,
  569. so SQLAlchemy applied the column-level defaults and ignored the user's
  570. workflow preferences entirely. Every print sent from the slicer to the
  571. VP came through with the OPPOSITE of what the workflow page said,
  572. forcing the user to edit each queue item by hand.
  573. """
  574. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  575. added_items = []
  576. mock_db = AsyncMock()
  577. mock_db.add = MagicMock(side_effect=added_items.append)
  578. mock_db.commit = AsyncMock()
  579. mock_session_factory = MagicMock()
  580. mock_session_ctx = AsyncMock()
  581. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  582. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  583. mock_session_factory.return_value = mock_session_ctx
  584. inst = VirtualPrinterInstance(
  585. vp_id=22,
  586. name="DefaultsTest",
  587. mode="queue",
  588. model="C12",
  589. access_code="12345678",
  590. serial_suffix="391800022",
  591. auto_dispatch=True,
  592. base_dir=tmp_path,
  593. session_factory=mock_session_factory,
  594. )
  595. file_path = tmp_path / "test.3mf"
  596. file_path.write_bytes(b"fake3mf")
  597. # The reporter set every workflow default to the OPPOSITE of the model's
  598. # column default. Pre-fix the column defaults won; with the fix the
  599. # settings values must flow through to the queue item exactly as stored.
  600. settings_map = {
  601. "virtual_printer_archive_name_source": None,
  602. "default_bed_levelling": "false", # model default: True
  603. "default_flow_cali": "true", # model default: False
  604. "default_vibration_cali": "false", # model default: True
  605. "default_layer_inspect": "true", # model default: False
  606. "default_timelapse": "true", # model default: False
  607. }
  608. async def fake_get_setting(_db, key):
  609. return settings_map.get(key)
  610. mock_archive = MagicMock()
  611. mock_archive.id = 1
  612. mock_archive.print_name = "test"
  613. with (
  614. patch(
  615. "backend.app.api.routes.settings.get_setting",
  616. new=fake_get_setting,
  617. ),
  618. patch(
  619. "backend.app.services.archive.ArchiveService.archive_print",
  620. new_callable=AsyncMock,
  621. return_value=mock_archive,
  622. ),
  623. ):
  624. await inst._add_to_print_queue(file_path, "192.168.1.100")
  625. assert len(added_items) == 1
  626. queue_item = added_items[0]
  627. assert queue_item.bed_levelling is False, "default_bed_levelling=false must flow through"
  628. assert queue_item.flow_cali is True, "default_flow_cali=true must flow through"
  629. assert queue_item.vibration_cali is False, "default_vibration_cali=false must flow through"
  630. assert queue_item.layer_inspect is True, "default_layer_inspect=true must flow through"
  631. assert queue_item.timelapse is True, "default_timelapse=true must flow through"
  632. @pytest.mark.asyncio
  633. async def test_add_to_print_queue_falls_back_to_schema_defaults_when_unset(self, tmp_path):
  634. """#1235 fallback: when no workflow setting is in the DB, the queue
  635. item should use the AppSettings (Pydantic) defaults — same values
  636. the user sees in the workflow page on a fresh install.
  637. """
  638. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  639. added_items = []
  640. mock_db = AsyncMock()
  641. mock_db.add = MagicMock(side_effect=added_items.append)
  642. mock_db.commit = AsyncMock()
  643. mock_session_factory = MagicMock()
  644. mock_session_ctx = AsyncMock()
  645. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  646. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  647. mock_session_factory.return_value = mock_session_ctx
  648. inst = VirtualPrinterInstance(
  649. vp_id=23,
  650. name="FreshInstallDefaults",
  651. mode="queue",
  652. model="C12",
  653. access_code="12345678",
  654. serial_suffix="391800023",
  655. auto_dispatch=True,
  656. base_dir=tmp_path,
  657. session_factory=mock_session_factory,
  658. )
  659. file_path = tmp_path / "test.3mf"
  660. file_path.write_bytes(b"fake3mf")
  661. mock_archive = MagicMock()
  662. mock_archive.id = 1
  663. mock_archive.print_name = "test"
  664. with (
  665. patch(
  666. "backend.app.api.routes.settings.get_setting",
  667. new_callable=AsyncMock,
  668. return_value=None, # No settings → fall back to schema defaults
  669. ),
  670. patch(
  671. "backend.app.services.archive.ArchiveService.archive_print",
  672. new_callable=AsyncMock,
  673. return_value=mock_archive,
  674. ),
  675. ):
  676. await inst._add_to_print_queue(file_path, "192.168.1.100")
  677. assert len(added_items) == 1
  678. queue_item = added_items[0]
  679. # These must match the AppSettings (Pydantic) defaults in schemas/settings.py
  680. assert queue_item.bed_levelling is True
  681. assert queue_item.flow_cali is False
  682. assert queue_item.vibration_cali is True
  683. assert queue_item.layer_inspect is False
  684. assert queue_item.timelapse is False
  685. @pytest.mark.asyncio
  686. async def test_add_to_print_queue_inherits_slicer_print_options(self, tmp_path):
  687. """#1403: VP-queue items used to fall back to `default_timelapse` even
  688. though the slicer's MQTT `project_file` command carries the user's
  689. actual choice. Capture-via-`on_print_command` flow lets the user's
  690. slicer toggle reach the queue item.
  691. Settings here have timelapse OFF; the slicer's MQTT capture has it ON.
  692. After the fix the queue item must reflect the slicer's choice.
  693. """
  694. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  695. added_items = []
  696. mock_db = AsyncMock()
  697. mock_db.add = MagicMock(side_effect=added_items.append)
  698. mock_db.commit = AsyncMock()
  699. mock_session_factory = MagicMock()
  700. mock_session_ctx = AsyncMock()
  701. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  702. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  703. mock_session_factory.return_value = mock_session_ctx
  704. inst = VirtualPrinterInstance(
  705. vp_id=24,
  706. name="SlicerInherits",
  707. mode="queue",
  708. model="C12",
  709. access_code="12345678",
  710. serial_suffix="391800024",
  711. auto_dispatch=True,
  712. base_dir=tmp_path,
  713. session_factory=mock_session_factory,
  714. )
  715. file_path = tmp_path / "test.3mf"
  716. file_path.write_bytes(b"fake3mf")
  717. # Pre-populate the capture as if MQTT `project_file` arrived already.
  718. # Settings (below) deliberately have timelapse OFF — only the slicer
  719. # capture should drive the resulting queue item.
  720. await inst.on_print_command(
  721. file_path.name,
  722. {
  723. "command": "project_file",
  724. "timelapse": True,
  725. "bed_leveling": False, # Note: MQTT field is single-L `bed_leveling`
  726. "flow_cali": True,
  727. "vibration_cali": False,
  728. "layer_inspect": True,
  729. },
  730. )
  731. settings_map = {
  732. "virtual_printer_archive_name_source": None,
  733. "default_bed_levelling": "true",
  734. "default_flow_cali": "false",
  735. "default_vibration_cali": "true",
  736. "default_layer_inspect": "false",
  737. "default_timelapse": "false",
  738. }
  739. async def fake_get_setting(_db, key):
  740. return settings_map.get(key)
  741. mock_archive = MagicMock()
  742. mock_archive.id = 1
  743. mock_archive.print_name = "test"
  744. with (
  745. patch(
  746. "backend.app.api.routes.settings.get_setting",
  747. new=fake_get_setting,
  748. ),
  749. patch(
  750. "backend.app.services.archive.ArchiveService.archive_print",
  751. new_callable=AsyncMock,
  752. return_value=mock_archive,
  753. ),
  754. ):
  755. await inst._add_to_print_queue(file_path, "192.168.1.100")
  756. assert len(added_items) == 1
  757. queue_item = added_items[0]
  758. assert queue_item.timelapse is True, "Slicer's timelapse=True must override settings.default_timelapse=False"
  759. assert queue_item.bed_levelling is False, "Slicer's bed_leveling=False must override default_bed_levelling=True"
  760. assert queue_item.flow_cali is True
  761. assert queue_item.vibration_cali is False
  762. assert queue_item.layer_inspect is True
  763. # Capture is consumed — no lingering state for the next print of the same name.
  764. assert file_path.name not in inst._slicer_print_options
  765. @pytest.mark.asyncio
  766. async def test_add_to_print_queue_coerces_slicer_integer_zero_one(self, tmp_path):
  767. """#1403: H-family firmwares carry calibration flags as integers
  768. (0/1) rather than booleans. The capture must coerce both shapes so
  769. H-family-sliced jobs through the VP queue work the same as P1/X1.
  770. """
  771. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  772. added_items = []
  773. mock_db = AsyncMock()
  774. mock_db.add = MagicMock(side_effect=added_items.append)
  775. mock_db.commit = AsyncMock()
  776. mock_session_factory = MagicMock()
  777. mock_session_ctx = AsyncMock()
  778. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  779. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  780. mock_session_factory.return_value = mock_session_ctx
  781. inst = VirtualPrinterInstance(
  782. vp_id=25,
  783. name="SlicerIntegers",
  784. mode="queue",
  785. model="C12",
  786. access_code="12345678",
  787. serial_suffix="391800025",
  788. auto_dispatch=True,
  789. base_dir=tmp_path,
  790. session_factory=mock_session_factory,
  791. )
  792. file_path = tmp_path / "test.3mf"
  793. file_path.write_bytes(b"fake3mf")
  794. await inst.on_print_command(
  795. file_path.name,
  796. {"command": "project_file", "timelapse": 1, "bed_leveling": 0, "flow_cali": 1},
  797. )
  798. mock_archive = MagicMock()
  799. mock_archive.id = 1
  800. mock_archive.print_name = "test"
  801. with (
  802. patch(
  803. "backend.app.api.routes.settings.get_setting",
  804. new_callable=AsyncMock,
  805. return_value=None,
  806. ),
  807. patch(
  808. "backend.app.services.archive.ArchiveService.archive_print",
  809. new_callable=AsyncMock,
  810. return_value=mock_archive,
  811. ),
  812. ):
  813. await inst._add_to_print_queue(file_path, "192.168.1.100")
  814. assert len(added_items) == 1
  815. queue_item = added_items[0]
  816. assert queue_item.timelapse is True, "integer 1 must coerce to True"
  817. assert queue_item.bed_levelling is False, "integer 0 must coerce to False"
  818. assert queue_item.flow_cali is True
  819. @pytest.mark.asyncio
  820. async def test_add_to_print_queue_populates_required_filament_types(self, tmp_path):
  821. """#1188: VP queue-mode used to create PrintQueueItems with no
  822. filament fields, so the scheduler fell through to model-only matching
  823. and dispatched onto whatever printer was free regardless of loaded
  824. colour. ``required_filament_types`` is populated unconditionally
  825. (cheap, helps the scheduler validate type even without
  826. ``force_color_match``) — pin that contract here."""
  827. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  828. added_items = []
  829. mock_db = AsyncMock()
  830. mock_db.add = MagicMock(side_effect=added_items.append)
  831. mock_db.commit = AsyncMock()
  832. mock_session_factory = MagicMock()
  833. mock_session_ctx = AsyncMock()
  834. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  835. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  836. mock_session_factory.return_value = mock_session_ctx
  837. inst = VirtualPrinterInstance(
  838. vp_id=21,
  839. name="Reqs",
  840. mode="queue",
  841. model="C12",
  842. access_code="12345678",
  843. serial_suffix="391800021",
  844. auto_dispatch=True,
  845. queue_force_color_match=False, # off → only required_filament_types
  846. base_dir=tmp_path,
  847. session_factory=mock_session_factory,
  848. )
  849. file_path = tmp_path / "multi.3mf"
  850. _write_3mf_with_filaments(
  851. file_path,
  852. [
  853. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "12.3"},
  854. {"id": "2", "type": "PETG", "color": "#000000", "used_g": "4.5"},
  855. # used_g=0 → not actually consumed by this plate, must be ignored
  856. {"id": "3", "type": "ABS", "color": "#FF0000", "used_g": "0"},
  857. ],
  858. plate_index=1,
  859. )
  860. mock_archive = MagicMock()
  861. mock_archive.id = 1
  862. mock_archive.print_name = "multi"
  863. with (
  864. patch(
  865. "backend.app.api.routes.settings.get_setting",
  866. new_callable=AsyncMock,
  867. return_value=None,
  868. ),
  869. patch(
  870. "backend.app.services.archive.ArchiveService.archive_print",
  871. new_callable=AsyncMock,
  872. return_value=mock_archive,
  873. ),
  874. ):
  875. await inst._add_to_print_queue(file_path, "192.168.1.100")
  876. assert len(added_items) == 1
  877. queue_item = added_items[0]
  878. # Type-only fallback always populated. Sorted, deduped, no zero-use ABS.
  879. assert queue_item.required_filament_types is not None
  880. assert json.loads(queue_item.required_filament_types) == ["PETG", "PLA"]
  881. # Setting off → no force_color_match overrides leaked.
  882. assert queue_item.filament_overrides is None
  883. @pytest.mark.asyncio
  884. async def test_add_to_print_queue_force_color_match_writes_overrides(self, tmp_path):
  885. """#1188 core fix: when the per-VP ``queue_force_color_match`` toggle
  886. is on, every consumed slot lands as a ``filament_overrides`` entry
  887. with ``force_color_match: true``. This is the field the scheduler
  888. keys on (``print_scheduler.py:512``) — without it, slot-by-slot
  889. type+color matching never runs."""
  890. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  891. added_items = []
  892. mock_db = AsyncMock()
  893. mock_db.add = MagicMock(side_effect=added_items.append)
  894. mock_db.commit = AsyncMock()
  895. mock_session_factory = MagicMock()
  896. mock_session_ctx = AsyncMock()
  897. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  898. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  899. mock_session_factory.return_value = mock_session_ctx
  900. inst = VirtualPrinterInstance(
  901. vp_id=22,
  902. name="ForceColor",
  903. mode="queue",
  904. model="C12",
  905. access_code="12345678",
  906. serial_suffix="391800022",
  907. auto_dispatch=True,
  908. queue_force_color_match=True, # on
  909. base_dir=tmp_path,
  910. session_factory=mock_session_factory,
  911. )
  912. file_path = tmp_path / "forced.3mf"
  913. _write_3mf_with_filaments(
  914. file_path,
  915. [
  916. {"id": "1", "type": "PLA", "color": "#FFFFFF", "used_g": "10.0"},
  917. {"id": "2", "type": "PLA", "color": "#FF00FF", "used_g": "5.0"},
  918. ],
  919. plate_index=1,
  920. )
  921. mock_archive = MagicMock()
  922. mock_archive.id = 1
  923. mock_archive.print_name = "forced"
  924. with (
  925. patch(
  926. "backend.app.api.routes.settings.get_setting",
  927. new_callable=AsyncMock,
  928. return_value=None,
  929. ),
  930. patch(
  931. "backend.app.services.archive.ArchiveService.archive_print",
  932. new_callable=AsyncMock,
  933. return_value=mock_archive,
  934. ),
  935. ):
  936. await inst._add_to_print_queue(file_path, "192.168.1.100")
  937. assert len(added_items) == 1
  938. queue_item = added_items[0]
  939. assert queue_item.filament_overrides is not None
  940. overrides = json.loads(queue_item.filament_overrides)
  941. assert overrides == [
  942. {"slot_id": 1, "type": "PLA", "color": "#FFFFFF", "force_color_match": True},
  943. {"slot_id": 2, "type": "PLA", "color": "#FF00FF", "force_color_match": True},
  944. ]
  945. # required_filament_types still populated alongside overrides.
  946. assert json.loads(queue_item.required_filament_types) == ["PLA"]
  947. @pytest.mark.asyncio
  948. async def test_add_to_print_queue_force_color_match_skips_when_3mf_unparseable(self, tmp_path):
  949. """A malformed or fake-bytes 3MF must not crash the upload path —
  950. we just write the queue item with no filament fields and let the
  951. scheduler fall back to model-only matching (the pre-#1188 default).
  952. Regression guard for the existing fake-bytes happy-path tests."""
  953. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  954. added_items = []
  955. mock_db = AsyncMock()
  956. mock_db.add = MagicMock(side_effect=added_items.append)
  957. mock_db.commit = AsyncMock()
  958. mock_session_factory = MagicMock()
  959. mock_session_ctx = AsyncMock()
  960. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  961. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  962. mock_session_factory.return_value = mock_session_ctx
  963. inst = VirtualPrinterInstance(
  964. vp_id=23,
  965. name="Unparseable",
  966. mode="queue",
  967. model="C12",
  968. access_code="12345678",
  969. serial_suffix="391800023",
  970. auto_dispatch=True,
  971. queue_force_color_match=True,
  972. base_dir=tmp_path,
  973. session_factory=mock_session_factory,
  974. )
  975. file_path = tmp_path / "bad.3mf"
  976. file_path.write_bytes(b"not a real 3mf zip")
  977. mock_archive = MagicMock()
  978. mock_archive.id = 1
  979. mock_archive.print_name = "bad"
  980. with (
  981. patch(
  982. "backend.app.api.routes.settings.get_setting",
  983. new_callable=AsyncMock,
  984. return_value=None,
  985. ),
  986. patch(
  987. "backend.app.services.archive.ArchiveService.archive_print",
  988. new_callable=AsyncMock,
  989. return_value=mock_archive,
  990. ),
  991. ):
  992. await inst._add_to_print_queue(file_path, "192.168.1.100")
  993. assert len(added_items) == 1
  994. queue_item = added_items[0]
  995. # No filament data extractable → both fields stay None (graceful
  996. # fallback to model-only scheduling).
  997. assert queue_item.required_filament_types is None
  998. assert queue_item.filament_overrides is None
  999. # ========================================================================
  1000. # Tests for archive_name_source setting (#1152)
  1001. # ========================================================================
  1002. @pytest.mark.asyncio
  1003. @pytest.mark.parametrize(
  1004. ("setting_value", "expected_prefer_filename"),
  1005. [
  1006. ("filename", True),
  1007. ("metadata", False),
  1008. (None, False), # Default when setting unset
  1009. ("", False), # Defensive: empty string is not "filename"
  1010. ],
  1011. )
  1012. async def test_archive_file_passes_prefer_filename_per_setting(
  1013. self, tmp_path, setting_value, expected_prefer_filename
  1014. ):
  1015. """_archive_file reads `virtual_printer_archive_name_source` and forwards
  1016. prefer_filename_for_name=True only when it equals 'filename' (#1152)."""
  1017. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1018. mock_db = AsyncMock()
  1019. mock_session_factory = MagicMock()
  1020. mock_session_ctx = AsyncMock()
  1021. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1022. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1023. mock_session_factory.return_value = mock_session_ctx
  1024. inst = VirtualPrinterInstance(
  1025. vp_id=20,
  1026. name="NameSource",
  1027. mode="archive",
  1028. model="C11",
  1029. access_code="12345678",
  1030. serial_suffix="391800020",
  1031. base_dir=tmp_path,
  1032. session_factory=mock_session_factory,
  1033. )
  1034. file_path = tmp_path / "user-renamed-job.3mf"
  1035. file_path.write_bytes(b"fake3mf")
  1036. mock_archive = MagicMock()
  1037. mock_archive.id = 1
  1038. mock_archive.print_name = "user-renamed-job"
  1039. archive_print_mock = AsyncMock(return_value=mock_archive)
  1040. with (
  1041. patch(
  1042. "backend.app.api.routes.settings.get_setting",
  1043. new_callable=AsyncMock,
  1044. return_value=setting_value,
  1045. ),
  1046. patch(
  1047. "backend.app.services.archive.ArchiveService.archive_print",
  1048. archive_print_mock,
  1049. ),
  1050. ):
  1051. await inst._archive_file(file_path, "192.168.1.100")
  1052. assert archive_print_mock.await_count == 1
  1053. kwargs = archive_print_mock.await_args.kwargs
  1054. assert kwargs.get("prefer_filename_for_name") is expected_prefer_filename
  1055. # ========================================================================
  1056. # Tests for failure-path cleanup (#audit-R2-1)
  1057. # ========================================================================
  1058. #
  1059. # All three file handlers (_archive_file, _queue_file, _add_to_print_queue)
  1060. # previously only popped _pending_files and unlinked the temp file on the
  1061. # success branch. Failure paths leaked the marker (blocking same-name
  1062. # retries via the FTP layer) and the temp file on disk. The cleanup must
  1063. # ALWAYS run, even when archival / queue insert raises.
  1064. @pytest.mark.asyncio
  1065. async def test_archive_file_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1066. """When the archive layer raises, `_pending_files[filename]` must still
  1067. be popped and the temp file must be unlinked. Otherwise the FTP layer's
  1068. same-name retry guard would silently reject the slicer's next attempt
  1069. and the upload_dir would accumulate ghost files."""
  1070. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1071. mock_db = AsyncMock()
  1072. mock_session_factory = MagicMock()
  1073. mock_session_ctx = AsyncMock()
  1074. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1075. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1076. mock_session_factory.return_value = mock_session_ctx
  1077. inst = VirtualPrinterInstance(
  1078. vp_id=40,
  1079. name="ArchiveFailCleanup",
  1080. mode="archive",
  1081. model="C12",
  1082. access_code="12345678",
  1083. serial_suffix="391800040",
  1084. base_dir=tmp_path,
  1085. session_factory=mock_session_factory,
  1086. )
  1087. file_path = tmp_path / "cleanup-archive.3mf"
  1088. file_path.write_bytes(b"fake3mf")
  1089. inst._pending_files[file_path.name] = file_path
  1090. with (
  1091. patch(
  1092. "backend.app.api.routes.settings.get_setting",
  1093. new_callable=AsyncMock,
  1094. return_value=None,
  1095. ),
  1096. patch(
  1097. "backend.app.services.archive.ArchiveService.archive_print",
  1098. new_callable=AsyncMock,
  1099. side_effect=RuntimeError("archive blew up"),
  1100. ),
  1101. ):
  1102. await inst._archive_file(file_path, "192.168.1.100")
  1103. assert file_path.name not in inst._pending_files
  1104. assert not file_path.exists()
  1105. @pytest.mark.asyncio
  1106. async def test_queue_file_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1107. """Same invariant for _queue_file: a DB error during PendingUpload
  1108. insert must not leak the in-flight marker or the temp file."""
  1109. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1110. mock_db = AsyncMock()
  1111. # Commit raises — emulating a DB connectivity error.
  1112. mock_db.add = MagicMock()
  1113. mock_db.commit = AsyncMock(side_effect=RuntimeError("db unreachable"))
  1114. mock_session_factory = MagicMock()
  1115. mock_session_ctx = AsyncMock()
  1116. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1117. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1118. mock_session_factory.return_value = mock_session_ctx
  1119. inst = VirtualPrinterInstance(
  1120. vp_id=41,
  1121. name="QueueFailCleanup",
  1122. mode="review",
  1123. model="C12",
  1124. access_code="12345678",
  1125. serial_suffix="391800041",
  1126. base_dir=tmp_path,
  1127. session_factory=mock_session_factory,
  1128. )
  1129. file_path = tmp_path / "cleanup-queue.3mf"
  1130. file_path.write_bytes(b"fake3mf")
  1131. inst._pending_files[file_path.name] = file_path
  1132. await inst._queue_file(file_path, "192.168.1.100")
  1133. assert file_path.name not in inst._pending_files
  1134. assert not file_path.exists()
  1135. @pytest.mark.asyncio
  1136. async def test_add_to_print_queue_failure_path_pops_pending_and_unlinks(self, tmp_path):
  1137. """Same invariant for _add_to_print_queue: a DB error or archive
  1138. failure must not leak the in-flight marker or the temp file."""
  1139. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1140. mock_db = AsyncMock()
  1141. mock_db.add = MagicMock()
  1142. mock_db.commit = AsyncMock()
  1143. mock_db.execute = AsyncMock(side_effect=RuntimeError("queue insert blew up"))
  1144. mock_session_factory = MagicMock()
  1145. mock_session_ctx = AsyncMock()
  1146. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1147. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1148. mock_session_factory.return_value = mock_session_ctx
  1149. inst = VirtualPrinterInstance(
  1150. vp_id=42,
  1151. name="DispatchFailCleanup",
  1152. mode="queue",
  1153. model="C12",
  1154. access_code="12345678",
  1155. serial_suffix="391800042",
  1156. auto_dispatch=True,
  1157. base_dir=tmp_path,
  1158. session_factory=mock_session_factory,
  1159. )
  1160. file_path = tmp_path / "cleanup-dispatch.3mf"
  1161. file_path.write_bytes(b"fake3mf")
  1162. inst._pending_files[file_path.name] = file_path
  1163. with patch(
  1164. "backend.app.api.routes.settings.get_setting",
  1165. new_callable=AsyncMock,
  1166. return_value=None,
  1167. ):
  1168. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1169. assert file_path.name not in inst._pending_files
  1170. assert not file_path.exists()
  1171. # ========================================================================
  1172. # Test for position=MAX+1 (audit-R2)
  1173. # ========================================================================
  1174. @pytest.mark.asyncio
  1175. async def test_add_to_print_queue_position_picks_max_plus_one(self, tmp_path):
  1176. """VP-queue items previously got hardcoded `position=1`, colliding
  1177. with existing items at position 1 and producing non-deterministic
  1178. execution order. Now the position is chosen by `MAX(position)+1`
  1179. against the target queue, matching the canonical `POST /print-queue/`
  1180. path."""
  1181. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1182. # Capture the inserted PrintQueueItem so we can assert on .position.
  1183. added_items: list = []
  1184. class _RecordingDb:
  1185. def __init__(self):
  1186. self.add = lambda item: added_items.append(item)
  1187. self.commit = AsyncMock()
  1188. async def execute(self, query): # noqa: ARG002
  1189. """Return a stub result whose `.scalar()` reports the existing
  1190. MAX(position) for the target. Returning 7 means the new item
  1191. should land at 8."""
  1192. result = MagicMock()
  1193. result.scalar = MagicMock(return_value=7)
  1194. return result
  1195. mock_db = _RecordingDb()
  1196. mock_session_factory = MagicMock()
  1197. mock_session_ctx = AsyncMock()
  1198. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1199. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1200. mock_session_factory.return_value = mock_session_ctx
  1201. inst = VirtualPrinterInstance(
  1202. vp_id=43,
  1203. name="PositionMaxPlusOne",
  1204. mode="queue",
  1205. model="C12",
  1206. access_code="12345678",
  1207. serial_suffix="391800043",
  1208. target_printer_id=99,
  1209. auto_dispatch=True,
  1210. base_dir=tmp_path,
  1211. session_factory=mock_session_factory,
  1212. )
  1213. file_path = tmp_path / "next-position.3mf"
  1214. file_path.write_bytes(b"fake3mf")
  1215. mock_archive = MagicMock()
  1216. mock_archive.id = 555
  1217. mock_archive.printer_id = None
  1218. mock_archive.filename = "next-position.3mf"
  1219. mock_archive.print_name = "next-position"
  1220. mock_archive.status = "archived"
  1221. with (
  1222. patch(
  1223. "backend.app.api.routes.settings.get_setting",
  1224. new_callable=AsyncMock,
  1225. return_value=None,
  1226. ),
  1227. patch(
  1228. "backend.app.services.archive.ArchiveService.archive_print",
  1229. new_callable=AsyncMock,
  1230. return_value=mock_archive,
  1231. ),
  1232. patch(
  1233. "backend.app.core.websocket.ws_manager.send_archive_created",
  1234. new_callable=AsyncMock,
  1235. ),
  1236. ):
  1237. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1238. # One queue item was added.
  1239. assert len(added_items) == 1
  1240. queue_item = added_items[0]
  1241. # Position = max(7) + 1 = 8 — NOT the legacy hardcoded 1.
  1242. assert queue_item.position == 8
  1243. @pytest.mark.asyncio
  1244. async def test_add_to_print_queue_multi_plate_send_all_enqueues_one_per_plate(self, tmp_path):
  1245. """#1733: BambuStudio / OrcaSlicer "Send All" of a multi-plate project
  1246. uploads ONE 3MF containing every plate. Pre-fix only the first plate
  1247. index was extracted and one queue item was created; plates 2..N were
  1248. silently dropped. Post-fix every `<plate>` block in `slice_info.config`
  1249. produces its own PrintQueueItem with the correct ``plate_id``, sharing
  1250. the same backing archive, with consecutive positions for plate-order
  1251. execution.
  1252. """
  1253. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1254. added_items: list = []
  1255. class _RecordingDb:
  1256. def __init__(self):
  1257. # Capture inserted items as they're added; assign a fake .id
  1258. # on flush so the manager's logger doesn't see None.
  1259. self._next_id = 1000
  1260. def _add(item):
  1261. added_items.append(item)
  1262. self.add = _add
  1263. self.commit = AsyncMock()
  1264. async def execute(self, query): # noqa: ARG002
  1265. """Return MAX(position) = 0 so plate items land at 1, 2, 3."""
  1266. result = MagicMock()
  1267. result.scalar = MagicMock(return_value=0)
  1268. return result
  1269. async def flush(self):
  1270. # Mimic the FK populate so queue_item.id is available after add().
  1271. for item in added_items:
  1272. if getattr(item, "id", None) is None:
  1273. item.id = self._next_id
  1274. self._next_id += 1
  1275. mock_db = _RecordingDb()
  1276. mock_session_factory = MagicMock()
  1277. mock_session_ctx = AsyncMock()
  1278. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1279. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1280. mock_session_factory.return_value = mock_session_ctx
  1281. inst = VirtualPrinterInstance(
  1282. vp_id=44,
  1283. name="MultiPlateSendAll",
  1284. mode="queue",
  1285. model="O1D", # H2D — matches the live VP H2D-1 Proxy in #1733
  1286. access_code="12345678",
  1287. serial_suffix="391800044",
  1288. target_printer_id=1,
  1289. auto_dispatch=False, # manual_start, mirrors the live VP
  1290. base_dir=tmp_path,
  1291. session_factory=mock_session_factory,
  1292. )
  1293. # Build a 3MF with three plates baked into slice_info.config —
  1294. # mirrors what BambuStudio / OrcaSlicer's "Send All" puts on the wire.
  1295. file_path = tmp_path / "Cube.gcode.3mf"
  1296. _write_3mf_with_filaments(
  1297. file_path, [{"id": 1, "type": "PLA", "color": "#000000", "used_g": "15.61"}], plate_index=1
  1298. )
  1299. # Append plate 2 and 3 blocks to slice_info.config to mimic Send All.
  1300. with zipfile.ZipFile(file_path, "r") as zf:
  1301. existing = zf.read("Metadata/slice_info.config").decode()
  1302. # Inject two additional <plate> blocks (indices 2 and 3) inside <config>.
  1303. multi_plate_config = existing.replace(
  1304. "</config>",
  1305. (
  1306. '<plate><metadata key="index" value="2"/>'
  1307. '<filament id="2" type="PETG" color="#FB0207" used_g="14.45"/>'
  1308. "</plate>"
  1309. '<plate><metadata key="index" value="3"/>'
  1310. '<filament id="3" type="PLA" color="#FFFFFF" used_g="12.10"/>'
  1311. "</plate>"
  1312. "</config>"
  1313. ),
  1314. )
  1315. # Repack the zip with the expanded slice_info.config.
  1316. import io as _io
  1317. buf = _io.BytesIO()
  1318. with zipfile.ZipFile(file_path, "r") as src, zipfile.ZipFile(buf, "w") as dst:
  1319. for name in src.namelist():
  1320. if name == "Metadata/slice_info.config":
  1321. dst.writestr(name, multi_plate_config)
  1322. else:
  1323. dst.writestr(name, src.read(name))
  1324. # Plate-2 and plate-3 gcode payloads so `extract_filament_requirements`
  1325. # has something to read for each — contents irrelevant, presence matters.
  1326. dst.writestr("Metadata/plate_2.gcode", "; plate 2 gcode\n")
  1327. dst.writestr("Metadata/plate_3.gcode", "; plate 3 gcode\n")
  1328. file_path.write_bytes(buf.getvalue())
  1329. mock_archive = MagicMock()
  1330. mock_archive.id = 999
  1331. mock_archive.printer_id = None
  1332. mock_archive.filename = "Cube.gcode.3mf"
  1333. mock_archive.print_name = "Cube"
  1334. mock_archive.status = "archived"
  1335. with (
  1336. patch(
  1337. "backend.app.api.routes.settings.get_setting",
  1338. new_callable=AsyncMock,
  1339. return_value=None,
  1340. ),
  1341. patch(
  1342. "backend.app.services.archive.ArchiveService.archive_print",
  1343. new_callable=AsyncMock,
  1344. return_value=mock_archive,
  1345. ),
  1346. patch(
  1347. "backend.app.core.websocket.ws_manager.send_archive_created",
  1348. new_callable=AsyncMock,
  1349. ),
  1350. ):
  1351. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1352. # Three queue items, one per plate, with the correct plate_id and
  1353. # consecutive positions starting at MAX(position)+1 = 1.
  1354. assert len(added_items) == 3, f"Expected 3 queue items for 3-plate Send All, got {len(added_items)}"
  1355. plate_ids = [q.plate_id for q in added_items]
  1356. assert plate_ids == [1, 2, 3], f"plate_ids should preserve slice_info order, got {plate_ids}"
  1357. positions = [q.position for q in added_items]
  1358. assert positions == [1, 2, 3], f"positions should be consecutive, got {positions}"
  1359. archive_ids = {q.archive_id for q in added_items}
  1360. assert archive_ids == {999}, f"All queue items must share the single backing archive, got {archive_ids}"
  1361. # auto_dispatch=False on the VP → every item is manual_start.
  1362. assert all(q.manual_start for q in added_items)
  1363. @pytest.mark.asyncio
  1364. async def test_add_to_print_queue_captures_nozzle_mapping(self, tmp_path):
  1365. """#1780: BambuStudio's project_file for H2C rack-swap (O1C2) sends
  1366. per-filament physical nozzle position IDs in `nozzle_mapping`. VP
  1367. intake must store it as a JSON string on the queue item so the
  1368. dispatcher can replay it. Without this the H2C firmware falls back
  1369. to "last matching nozzle" auto-pick and ignores the user's slicer
  1370. choice.
  1371. """
  1372. import json as _json
  1373. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1374. added_items = []
  1375. mock_db = AsyncMock()
  1376. mock_db.add = MagicMock(side_effect=added_items.append)
  1377. mock_db.commit = AsyncMock()
  1378. mock_session_factory = MagicMock()
  1379. mock_session_ctx = AsyncMock()
  1380. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1381. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1382. mock_session_factory.return_value = mock_session_ctx
  1383. inst = VirtualPrinterInstance(
  1384. vp_id=42,
  1385. name="H2CRack",
  1386. mode="queue",
  1387. model="O1C2",
  1388. access_code="12345678",
  1389. serial_suffix="391800042",
  1390. base_dir=tmp_path,
  1391. session_factory=mock_session_factory,
  1392. )
  1393. file_path = tmp_path / "test.3mf"
  1394. file_path.write_bytes(b"fake3mf")
  1395. # Pre-populate as if BS's project_file arrived. Wire shape matches
  1396. # BambuStudio's PrintJob params: nozzle_mapping = 32-entry array of
  1397. # per-filament physical nozzle position IDs (verified via H2C wire
  1398. # capture). The slicer-side `nozzles_info` field that the original
  1399. # #1780 attempt also looked for was never actually sent — it has
  1400. # been dropped from the capture path entirely.
  1401. await inst.on_print_command(
  1402. file_path.name,
  1403. {
  1404. "command": "project_file",
  1405. "nozzle_mapping": [16, -1, -1, 1, -1, -1, -1, -1],
  1406. },
  1407. )
  1408. mock_archive = MagicMock()
  1409. mock_archive.id = 1
  1410. mock_archive.print_name = "test"
  1411. with (
  1412. patch(
  1413. "backend.app.api.routes.settings.get_setting",
  1414. new_callable=AsyncMock,
  1415. return_value=None,
  1416. ),
  1417. patch(
  1418. "backend.app.services.archive.ArchiveService.archive_print",
  1419. new_callable=AsyncMock,
  1420. return_value=mock_archive,
  1421. ),
  1422. ):
  1423. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1424. assert len(added_items) == 1
  1425. item = added_items[0]
  1426. assert item.nozzle_mapping is not None
  1427. assert _json.loads(item.nozzle_mapping) == [16, -1, -1, 1, -1, -1, -1, -1]
  1428. @pytest.mark.asyncio
  1429. async def test_add_to_print_queue_no_nozzle_mapping_when_slicer_omits(self, tmp_path):
  1430. """#1780: every model other than O1C2 sends no nozzle_mapping — the
  1431. queue item must carry NULL, not an empty list. NULL is what the
  1432. dispatch layer keys off of to skip the injection entirely on non-
  1433. rack-swap printers.
  1434. """
  1435. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1436. added_items = []
  1437. mock_db = AsyncMock()
  1438. mock_db.add = MagicMock(side_effect=added_items.append)
  1439. mock_db.commit = AsyncMock()
  1440. mock_session_factory = MagicMock()
  1441. mock_session_ctx = AsyncMock()
  1442. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1443. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1444. mock_session_factory.return_value = mock_session_ctx
  1445. inst = VirtualPrinterInstance(
  1446. vp_id=43,
  1447. name="NotH2C",
  1448. mode="queue",
  1449. model="C11",
  1450. access_code="12345678",
  1451. serial_suffix="391800043",
  1452. base_dir=tmp_path,
  1453. session_factory=mock_session_factory,
  1454. )
  1455. file_path = tmp_path / "test.3mf"
  1456. file_path.write_bytes(b"fake3mf")
  1457. # X1C-style slicer command — no nozzle fields.
  1458. await inst.on_print_command(
  1459. file_path.name,
  1460. {"command": "project_file", "timelapse": False, "bed_leveling": True},
  1461. )
  1462. mock_archive = MagicMock()
  1463. mock_archive.id = 1
  1464. mock_archive.print_name = "test"
  1465. with (
  1466. patch(
  1467. "backend.app.api.routes.settings.get_setting",
  1468. new_callable=AsyncMock,
  1469. return_value=None,
  1470. ),
  1471. patch(
  1472. "backend.app.services.archive.ArchiveService.archive_print",
  1473. new_callable=AsyncMock,
  1474. return_value=mock_archive,
  1475. ),
  1476. ):
  1477. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1478. assert len(added_items) == 1
  1479. item = added_items[0]
  1480. assert item.nozzle_mapping is None
  1481. @pytest.mark.asyncio
  1482. async def test_add_to_print_queue_nozzle_pick_replicated_across_plates(self, tmp_path, monkeypatch):
  1483. """#1780 × #1697/#1188: a multi-plate Send All from BS must stamp the
  1484. same nozzle_mapping on every plate's queue item, not only the first.
  1485. Mirrors the per-plate stamping for gcode_injection,
  1486. filament_overrides, etc.
  1487. """
  1488. import json as _json
  1489. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1490. added_items = []
  1491. mock_db = AsyncMock()
  1492. mock_db.add = MagicMock(side_effect=added_items.append)
  1493. mock_db.flush = AsyncMock()
  1494. mock_db.commit = AsyncMock()
  1495. mock_db.execute = AsyncMock()
  1496. mock_db.execute.return_value.scalar.return_value = None
  1497. mock_session_factory = MagicMock()
  1498. mock_session_ctx = AsyncMock()
  1499. mock_session_ctx.__aenter__ = AsyncMock(return_value=mock_db)
  1500. mock_session_ctx.__aexit__ = AsyncMock(return_value=False)
  1501. mock_session_factory.return_value = mock_session_ctx
  1502. inst = VirtualPrinterInstance(
  1503. vp_id=44,
  1504. name="H2CMultiPlate",
  1505. mode="queue",
  1506. model="O1C2",
  1507. access_code="12345678",
  1508. serial_suffix="391800044",
  1509. base_dir=tmp_path,
  1510. session_factory=mock_session_factory,
  1511. )
  1512. file_path = tmp_path / "test.3mf"
  1513. file_path.write_bytes(b"fake3mf")
  1514. # Force 3 plates so the queue loop runs three times.
  1515. monkeypatch.setattr(inst, "_extract_plate_ids", lambda _p: [1, 2, 3])
  1516. await inst.on_print_command(
  1517. file_path.name,
  1518. {
  1519. "command": "project_file",
  1520. "nozzle_mapping": [16, 0],
  1521. },
  1522. )
  1523. mock_archive = MagicMock()
  1524. mock_archive.id = 1
  1525. mock_archive.print_name = "test"
  1526. with (
  1527. patch(
  1528. "backend.app.api.routes.settings.get_setting",
  1529. new_callable=AsyncMock,
  1530. return_value=None,
  1531. ),
  1532. patch(
  1533. "backend.app.services.archive.ArchiveService.archive_print",
  1534. new_callable=AsyncMock,
  1535. return_value=mock_archive,
  1536. ),
  1537. ):
  1538. await inst._add_to_print_queue(file_path, "192.168.1.100")
  1539. assert len(added_items) == 3
  1540. for item in added_items:
  1541. assert _json.loads(item.nozzle_mapping) == [16, 0]
  1542. class TestVirtualPrinterManager:
  1543. """Tests for VirtualPrinterManager orchestrator."""
  1544. @pytest.fixture
  1545. def manager(self):
  1546. """Create a VirtualPrinterManager instance."""
  1547. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  1548. return VirtualPrinterManager()
  1549. def test_manager_starts_empty(self, manager):
  1550. """Verify manager starts with no instances."""
  1551. assert len(manager._instances) == 0
  1552. assert manager.is_enabled is False
  1553. def test_manager_get_status_empty(self, manager):
  1554. """Verify get_status returns disabled state when no instances."""
  1555. status = manager.get_status()
  1556. assert status["enabled"] is False
  1557. assert status["running"] is False
  1558. assert status["mode"] == "archive"
  1559. def test_manager_is_enabled_with_instance(self, manager, tmp_path):
  1560. """Verify is_enabled is True when instances exist."""
  1561. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1562. inst = VirtualPrinterInstance(
  1563. vp_id=1,
  1564. name="Test",
  1565. mode="archive",
  1566. model="C11",
  1567. access_code="12345678",
  1568. serial_suffix="391800001",
  1569. base_dir=tmp_path,
  1570. )
  1571. manager._instances[1] = inst
  1572. assert manager.is_enabled is True
  1573. @pytest.mark.asyncio
  1574. async def test_manager_remove_instance_server(self, manager, tmp_path):
  1575. """Verify remove_instance stops and removes a server-mode instance."""
  1576. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1577. inst = VirtualPrinterInstance(
  1578. vp_id=1,
  1579. name="Test",
  1580. mode="archive",
  1581. model="C11",
  1582. access_code="12345678",
  1583. serial_suffix="391800001",
  1584. base_dir=tmp_path,
  1585. )
  1586. inst.stop_server = AsyncMock()
  1587. manager._instances[1] = inst
  1588. await manager.remove_instance(1)
  1589. assert 1 not in manager._instances
  1590. inst.stop_server.assert_called_once()
  1591. @pytest.mark.asyncio
  1592. async def test_manager_remove_instance_proxy(self, manager, tmp_path):
  1593. """Verify remove_instance stops proxy-mode instance."""
  1594. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1595. inst = VirtualPrinterInstance(
  1596. vp_id=2,
  1597. name="Proxy",
  1598. mode="proxy",
  1599. model="C11",
  1600. access_code="",
  1601. serial_suffix="391800002",
  1602. target_printer_ip="192.168.1.100",
  1603. base_dir=tmp_path,
  1604. )
  1605. inst.stop_proxy = AsyncMock()
  1606. manager._instances[2] = inst
  1607. await manager.remove_instance(2)
  1608. assert 2 not in manager._instances
  1609. inst.stop_proxy.assert_called_once()
  1610. def test_manager_get_status_with_instance(self, manager, tmp_path):
  1611. """Verify legacy get_status returns first instance data."""
  1612. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1613. inst = VirtualPrinterInstance(
  1614. vp_id=1,
  1615. name="Bambuddy",
  1616. mode="archive",
  1617. model="C11",
  1618. access_code="12345678",
  1619. serial_suffix="391800001",
  1620. base_dir=tmp_path,
  1621. )
  1622. mock_task = MagicMock(done=MagicMock(return_value=False))
  1623. inst._tasks = [mock_task]
  1624. inst._pending_files = {"file1.3mf": Path("/tmp/file1.3mf")} # nosec B108
  1625. manager._instances[1] = inst
  1626. status = manager.get_status()
  1627. assert status["enabled"] is True
  1628. assert status["running"] is True
  1629. assert status["mode"] == "archive"
  1630. assert status["name"] == "Bambuddy"
  1631. assert status["serial"] == "01S00A391800001"
  1632. assert status["model"] == "C11"
  1633. assert status["model_name"] == "P1P"
  1634. assert status["pending_files"] == 1
  1635. def test_manager_get_all_status(self, manager, tmp_path):
  1636. """Verify get_all_status returns status for all instances."""
  1637. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1638. for i in range(1, 3):
  1639. inst = VirtualPrinterInstance(
  1640. vp_id=i,
  1641. name=f"VP{i}",
  1642. mode="archive",
  1643. model="C11",
  1644. access_code="12345678",
  1645. serial_suffix=f"39180000{i}",
  1646. base_dir=tmp_path,
  1647. )
  1648. manager._instances[i] = inst
  1649. statuses = manager.get_all_status()
  1650. assert len(statuses) == 2
  1651. assert statuses[0]["name"] == "VP1"
  1652. assert statuses[1]["name"] == "VP2"
  1653. @pytest.mark.asyncio
  1654. async def test_manager_stop_all(self, manager, tmp_path):
  1655. """Verify stop_all removes all instances."""
  1656. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1657. for i in range(1, 3):
  1658. inst = VirtualPrinterInstance(
  1659. vp_id=i,
  1660. name=f"VP{i}",
  1661. mode="archive",
  1662. model="C11",
  1663. access_code="12345678",
  1664. serial_suffix=f"39180000{i}",
  1665. base_dir=tmp_path,
  1666. )
  1667. inst.stop_server = AsyncMock()
  1668. manager._instances[i] = inst
  1669. await manager.stop_all()
  1670. assert len(manager._instances) == 0
  1671. # ========================================================================
  1672. # Tests for sync_from_db config change detection
  1673. # ========================================================================
  1674. def _make_db_vp(self, **overrides):
  1675. """Create a mock VirtualPrinter DB object."""
  1676. defaults = {
  1677. "id": 1,
  1678. "name": "TestVP",
  1679. "enabled": True,
  1680. "mode": "archive",
  1681. "model": "C11",
  1682. "access_code": "12345678",
  1683. "serial_suffix": "391800001",
  1684. "bind_ip": "",
  1685. "remote_interface_ip": "",
  1686. "target_printer_id": None,
  1687. "auto_dispatch": True,
  1688. "tailscale_disabled": True, # Opt-in default (#1070 UX fix)
  1689. "queue_force_color_match": False, # default — must be explicit so MagicMock truthiness doesn't trip the change detector
  1690. "gcode_injection": False, # same reason as above
  1691. "position": 0,
  1692. }
  1693. defaults.update(overrides)
  1694. vp = MagicMock()
  1695. for k, v in defaults.items():
  1696. setattr(vp, k, v)
  1697. return vp
  1698. def _setup_sync_mocks(self, manager, enabled_vps, tmp_path):
  1699. """Wire up session_factory mock for sync_from_db."""
  1700. mock_result = MagicMock()
  1701. mock_result.scalars.return_value.all.return_value = enabled_vps
  1702. mock_db = AsyncMock()
  1703. mock_db.execute = AsyncMock(return_value=mock_result)
  1704. mock_db.__aenter__ = AsyncMock(return_value=mock_db)
  1705. mock_db.__aexit__ = AsyncMock(return_value=False)
  1706. manager._session_factory = MagicMock(return_value=mock_db)
  1707. manager._base_dir = tmp_path
  1708. @pytest.mark.asyncio
  1709. async def test_sync_from_db_restarts_on_mode_change(self, manager, tmp_path):
  1710. """Verify sync_from_db restarts VP when mode changes."""
  1711. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1712. inst = VirtualPrinterInstance(
  1713. vp_id=1,
  1714. name="TestVP",
  1715. mode="archive",
  1716. model="C11",
  1717. access_code="12345678",
  1718. serial_suffix="391800001",
  1719. base_dir=tmp_path,
  1720. )
  1721. inst.stop_server = AsyncMock()
  1722. manager._instances[1] = inst
  1723. # DB says mode changed to "review"
  1724. db_vp = self._make_db_vp(mode="review")
  1725. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1726. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1727. # Patch VirtualPrinterInstance to prevent actual start
  1728. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1729. mock_new = MagicMock()
  1730. mock_new.start_server = AsyncMock()
  1731. MockInst.return_value = mock_new
  1732. await manager.sync_from_db()
  1733. mock_remove.assert_called_once_with(1)
  1734. @pytest.mark.asyncio
  1735. async def test_sync_from_db_restarts_on_access_code_change(self, manager, tmp_path):
  1736. """Verify sync_from_db restarts VP when access_code changes."""
  1737. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1738. inst = VirtualPrinterInstance(
  1739. vp_id=1,
  1740. name="TestVP",
  1741. mode="archive",
  1742. model="C11",
  1743. access_code="12345678",
  1744. serial_suffix="391800001",
  1745. base_dir=tmp_path,
  1746. )
  1747. inst.stop_server = AsyncMock()
  1748. manager._instances[1] = inst
  1749. db_vp = self._make_db_vp(access_code="newcode99")
  1750. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1751. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1752. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1753. mock_new = MagicMock()
  1754. mock_new.start_server = AsyncMock()
  1755. MockInst.return_value = mock_new
  1756. await manager.sync_from_db()
  1757. mock_remove.assert_called_once_with(1)
  1758. @pytest.mark.asyncio
  1759. async def test_sync_from_db_skips_unchanged_instance(self, manager, tmp_path):
  1760. """Verify sync_from_db does NOT restart when config is identical."""
  1761. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1762. inst = VirtualPrinterInstance(
  1763. vp_id=1,
  1764. name="TestVP",
  1765. mode="archive",
  1766. model="C11",
  1767. access_code="12345678",
  1768. serial_suffix="391800001",
  1769. base_dir=tmp_path,
  1770. )
  1771. manager._instances[1] = inst
  1772. # DB matches running config exactly
  1773. db_vp = self._make_db_vp()
  1774. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1775. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1776. await manager.sync_from_db()
  1777. mock_remove.assert_not_called()
  1778. @pytest.mark.asyncio
  1779. async def test_sync_from_db_restarts_on_bind_ip_change(self, manager, tmp_path):
  1780. """Verify sync_from_db restarts VP when bind_ip changes."""
  1781. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1782. inst = VirtualPrinterInstance(
  1783. vp_id=1,
  1784. name="TestVP",
  1785. mode="archive",
  1786. model="C11",
  1787. access_code="12345678",
  1788. serial_suffix="391800001",
  1789. bind_ip="192.168.1.10",
  1790. base_dir=tmp_path,
  1791. )
  1792. inst.stop_server = AsyncMock()
  1793. manager._instances[1] = inst
  1794. db_vp = self._make_db_vp(bind_ip="192.168.1.20")
  1795. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1796. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1797. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1798. mock_new = MagicMock()
  1799. mock_new.start_server = AsyncMock()
  1800. MockInst.return_value = mock_new
  1801. await manager.sync_from_db()
  1802. mock_remove.assert_called_once_with(1)
  1803. @pytest.mark.asyncio
  1804. async def test_sync_from_db_restarts_on_model_change(self, manager, tmp_path):
  1805. """Verify sync_from_db restarts VP when model changes."""
  1806. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1807. inst = VirtualPrinterInstance(
  1808. vp_id=1,
  1809. name="TestVP",
  1810. mode="archive",
  1811. model="C11",
  1812. access_code="12345678",
  1813. serial_suffix="391800001",
  1814. base_dir=tmp_path,
  1815. )
  1816. inst.stop_server = AsyncMock()
  1817. manager._instances[1] = inst
  1818. db_vp = self._make_db_vp(model="C12")
  1819. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1820. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1821. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1822. mock_new = MagicMock()
  1823. mock_new.start_server = AsyncMock()
  1824. MockInst.return_value = mock_new
  1825. await manager.sync_from_db()
  1826. mock_remove.assert_called_once_with(1)
  1827. @pytest.mark.asyncio
  1828. async def test_sync_from_db_does_not_restart_on_tailscale_toggle(self, manager, tmp_path):
  1829. """Flipping tailscale_disabled is purely informational — must NOT trigger a restart.
  1830. Cert provisioning was removed; the toggle only governs whether the VP card surfaces
  1831. the host's Tailscale IP/FQDN to the user. No service needs to reload, so changing
  1832. it through sync_from_db should leave any running instance untouched.
  1833. """
  1834. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1835. inst = VirtualPrinterInstance(
  1836. vp_id=1,
  1837. name="TestVP",
  1838. mode="archive",
  1839. model="C11",
  1840. access_code="12345678",
  1841. serial_suffix="391800001",
  1842. tailscale_disabled=False,
  1843. base_dir=tmp_path,
  1844. )
  1845. inst.stop_server = AsyncMock()
  1846. manager._instances[1] = inst
  1847. db_vp = self._make_db_vp(tailscale_disabled=True)
  1848. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1849. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1850. await manager.sync_from_db()
  1851. mock_remove.assert_not_called()
  1852. @pytest.mark.asyncio
  1853. async def test_sync_from_db_restarts_on_gcode_injection_toggle(self, manager, tmp_path):
  1854. """Toggling gcode_injection in the DB must restart the running instance.
  1855. Without this, the in-memory ``self.gcode_injection`` keeps its old value
  1856. and ``_add_to_print_queue`` stamps the stale flag on every new queue
  1857. item — so disabling injection in the UI silently has no effect until
  1858. the process restarts.
  1859. """
  1860. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  1861. inst = VirtualPrinterInstance(
  1862. vp_id=1,
  1863. name="TestVP",
  1864. mode="archive",
  1865. model="C11",
  1866. access_code="12345678",
  1867. serial_suffix="391800001",
  1868. gcode_injection=True,
  1869. base_dir=tmp_path,
  1870. )
  1871. inst.stop_server = AsyncMock()
  1872. manager._instances[1] = inst
  1873. db_vp = self._make_db_vp(gcode_injection=False)
  1874. self._setup_sync_mocks(manager, [db_vp], tmp_path)
  1875. with patch.object(manager, "remove_instance", new_callable=AsyncMock) as mock_remove:
  1876. with patch("backend.app.services.virtual_printer.manager.VirtualPrinterInstance") as MockInst:
  1877. mock_new = MagicMock()
  1878. mock_new.start_server = AsyncMock()
  1879. MockInst.return_value = mock_new
  1880. await manager.sync_from_db()
  1881. mock_remove.assert_called_once_with(1)
  1882. class TestFTPSession:
  1883. """Tests for FTP session handling."""
  1884. @pytest.fixture
  1885. def mock_reader(self):
  1886. """Create a mock StreamReader."""
  1887. reader = AsyncMock()
  1888. return reader
  1889. @pytest.fixture
  1890. def mock_writer(self):
  1891. """Create a mock StreamWriter."""
  1892. writer = MagicMock()
  1893. writer.get_extra_info = MagicMock(return_value=("192.168.1.100", 12345))
  1894. writer.write = MagicMock()
  1895. writer.drain = AsyncMock()
  1896. writer.close = MagicMock()
  1897. writer.wait_closed = AsyncMock()
  1898. writer.is_closing = MagicMock(return_value=False)
  1899. return writer
  1900. @pytest.fixture
  1901. def ssl_context(self):
  1902. """Create a mock SSL context."""
  1903. return MagicMock()
  1904. @pytest.fixture
  1905. def session(self, mock_reader, mock_writer, ssl_context, tmp_path):
  1906. """Create an FTPSession instance."""
  1907. from backend.app.services.virtual_printer.ftp_server import FTPSession
  1908. return FTPSession(
  1909. reader=mock_reader,
  1910. writer=mock_writer,
  1911. upload_dir=tmp_path,
  1912. access_code="12345678",
  1913. ssl_context=ssl_context,
  1914. on_file_received=None,
  1915. )
  1916. # ========================================================================
  1917. # Tests for authentication
  1918. # ========================================================================
  1919. @pytest.mark.asyncio
  1920. async def test_user_command_accepts_bblp(self, session):
  1921. """Verify USER command accepts bblp user."""
  1922. await session.cmd_USER("bblp")
  1923. assert session.username == "bblp"
  1924. @pytest.mark.asyncio
  1925. async def test_pass_command_authenticates(self, session):
  1926. """Verify PASS command authenticates with correct code."""
  1927. session.username = "bblp"
  1928. await session.cmd_PASS("12345678")
  1929. assert session.authenticated is True
  1930. @pytest.mark.asyncio
  1931. async def test_pass_command_rejects_wrong_code(self, session):
  1932. """Verify PASS command rejects wrong access code."""
  1933. session.username = "bblp"
  1934. await session.cmd_PASS("wrongcode")
  1935. assert session.authenticated is False
  1936. # ========================================================================
  1937. # Tests for FTP commands
  1938. # ========================================================================
  1939. @pytest.mark.asyncio
  1940. async def test_syst_command(self, session):
  1941. """Verify SYST returns UNIX type."""
  1942. await session.cmd_SYST("")
  1943. session.writer.write.assert_called()
  1944. call_args = session.writer.write.call_args[0][0].decode()
  1945. assert "215" in call_args
  1946. assert "UNIX" in call_args
  1947. @pytest.mark.asyncio
  1948. async def test_pwd_command_requires_auth(self, session):
  1949. """Verify PWD requires authentication."""
  1950. session.authenticated = False
  1951. await session.cmd_PWD("")
  1952. call_args = session.writer.write.call_args[0][0].decode()
  1953. assert "530" in call_args
  1954. @pytest.mark.asyncio
  1955. async def test_pwd_command_when_authenticated(self, session):
  1956. """Verify PWD returns root directory when authenticated."""
  1957. session.authenticated = True
  1958. await session.cmd_PWD("")
  1959. call_args = session.writer.write.call_args[0][0].decode()
  1960. assert "257" in call_args
  1961. @pytest.mark.asyncio
  1962. async def test_type_command_sets_binary(self, session):
  1963. """Verify TYPE I sets binary mode."""
  1964. session.authenticated = True
  1965. await session.cmd_TYPE("I")
  1966. assert session.transfer_type == "I"
  1967. @pytest.mark.asyncio
  1968. async def test_pbsz_command(self, session):
  1969. """Verify PBSZ returns success."""
  1970. await session.cmd_PBSZ("0")
  1971. call_args = session.writer.write.call_args[0][0].decode()
  1972. assert "200" in call_args
  1973. @pytest.mark.asyncio
  1974. async def test_prot_command_accepts_p(self, session):
  1975. """Verify PROT P is accepted."""
  1976. await session.cmd_PROT("P")
  1977. call_args = session.writer.write.call_args[0][0].decode()
  1978. assert "200" in call_args
  1979. @pytest.mark.asyncio
  1980. async def test_quit_command(self, session):
  1981. """Verify QUIT sends goodbye and raises CancelledError."""
  1982. with pytest.raises(asyncio.CancelledError):
  1983. await session.cmd_QUIT("")
  1984. class TestSSDPServer:
  1985. """Tests for Virtual Printer SSDP server."""
  1986. @pytest.fixture
  1987. def ssdp_server(self):
  1988. """Create a VirtualPrinterSSDPServer instance."""
  1989. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  1990. return VirtualPrinterSSDPServer(
  1991. serial="TEST123",
  1992. name="TestPrinter",
  1993. model="BL-P001",
  1994. )
  1995. # ========================================================================
  1996. # Tests for SSDP response
  1997. # ========================================================================
  1998. def test_build_notify_message(self, ssdp_server):
  1999. """Verify NOTIFY packet contains required headers."""
  2000. # Set a known IP for testing
  2001. ssdp_server._local_ip = "192.168.1.100"
  2002. message = ssdp_server._build_notify_message()
  2003. assert b"NOTIFY" in message
  2004. assert b"DevName.bambu.com: TestPrinter" in message
  2005. assert b"USN: TEST123" in message
  2006. def test_build_response_message(self, ssdp_server):
  2007. """Verify response packet contains required headers."""
  2008. # Set a known IP for testing
  2009. ssdp_server._local_ip = "192.168.1.100"
  2010. message = ssdp_server._build_response_message()
  2011. assert b"HTTP/1.1 200 OK" in message
  2012. assert b"DevName.bambu.com: TestPrinter" in message
  2013. assert b"USN: TEST123" in message
  2014. def test_ssdp_server_uses_correct_model(self, ssdp_server):
  2015. """Verify SSDP server uses the provided model."""
  2016. ssdp_server._local_ip = "192.168.1.100"
  2017. message = ssdp_server._build_notify_message()
  2018. assert b"DevModel.bambu.com: BL-P001" in message
  2019. # ========================================================================
  2020. # Tests for advertise_ip parameter
  2021. # ========================================================================
  2022. def test_advertise_ip_sets_local_ip(self):
  2023. """Verify advertise_ip overrides auto-detection."""
  2024. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  2025. server = VirtualPrinterSSDPServer(
  2026. serial="TEST123",
  2027. name="TestPrinter",
  2028. model="BL-P001",
  2029. advertise_ip="10.0.0.50",
  2030. )
  2031. assert server._local_ip == "10.0.0.50"
  2032. def test_advertise_ip_empty_string_uses_auto_detect(self):
  2033. """Verify empty advertise_ip falls back to auto-detection."""
  2034. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  2035. server = VirtualPrinterSSDPServer(
  2036. serial="TEST123",
  2037. name="TestPrinter",
  2038. model="BL-P001",
  2039. advertise_ip="",
  2040. )
  2041. assert server._local_ip is None
  2042. def test_advertise_ip_in_notify_message(self):
  2043. """Verify NOTIFY message uses the advertise_ip."""
  2044. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  2045. server = VirtualPrinterSSDPServer(
  2046. serial="TEST123",
  2047. name="TestPrinter",
  2048. model="BL-P001",
  2049. advertise_ip="10.0.0.50",
  2050. )
  2051. message = server._build_notify_message()
  2052. assert b"Location: 10.0.0.50" in message
  2053. def test_advertise_ip_in_response_message(self):
  2054. """Verify M-SEARCH response uses the advertise_ip."""
  2055. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  2056. server = VirtualPrinterSSDPServer(
  2057. serial="TEST123",
  2058. name="TestPrinter",
  2059. model="BL-P001",
  2060. advertise_ip="10.0.0.50",
  2061. )
  2062. message = server._build_response_message()
  2063. assert b"Location: 10.0.0.50" in message
  2064. def test_default_no_advertise_ip(self):
  2065. """Verify default constructor has None local_ip (auto-detect)."""
  2066. from backend.app.services.virtual_printer.ssdp_server import VirtualPrinterSSDPServer
  2067. server = VirtualPrinterSSDPServer()
  2068. assert server._local_ip is None
  2069. class TestCertificateService:
  2070. """Tests for TLS certificate generation."""
  2071. @pytest.fixture
  2072. def cert_service(self, tmp_path):
  2073. """Create a CertificateService instance."""
  2074. from backend.app.services.virtual_printer.certificate import CertificateService
  2075. return CertificateService(cert_dir=tmp_path, serial="TEST123")
  2076. def test_generate_certificates(self, cert_service, tmp_path):
  2077. """Verify certificates are generated correctly."""
  2078. cert_path, key_path = cert_service.generate_certificates()
  2079. assert cert_path.exists()
  2080. assert key_path.exists()
  2081. # Verify certificate content
  2082. cert_content = cert_path.read_text()
  2083. assert "BEGIN CERTIFICATE" in cert_content
  2084. key_content = key_path.read_text()
  2085. assert "BEGIN" in key_content and "KEY" in key_content
  2086. def test_certificates_reused_if_exist(self, cert_service):
  2087. """Verify existing certificates are reused."""
  2088. # First generation
  2089. cert_path1, key_path1 = cert_service.generate_certificates()
  2090. mtime1 = cert_path1.stat().st_mtime
  2091. # Second call should reuse (via ensure_certificates)
  2092. cert_path2, key_path2 = cert_service.ensure_certificates()
  2093. mtime2 = cert_path2.stat().st_mtime
  2094. assert mtime1 == mtime2 # File wasn't regenerated
  2095. def test_delete_certificates(self, cert_service):
  2096. """Verify certificates can be deleted."""
  2097. cert_service.generate_certificates()
  2098. assert cert_service.cert_path.exists()
  2099. assert cert_service.key_path.exists()
  2100. cert_service.delete_certificates()
  2101. assert not cert_service.cert_path.exists()
  2102. assert not cert_service.key_path.exists()
  2103. def test_ensure_creates_if_not_exist(self, cert_service):
  2104. """Verify ensure_certificates generates if not existing."""
  2105. assert not cert_service.cert_path.exists()
  2106. cert_path, key_path = cert_service.ensure_certificates()
  2107. assert cert_path.exists()
  2108. assert key_path.exists()
  2109. class TestBindServer:
  2110. """Tests for BindServer (port 3002 bind/detect protocol)."""
  2111. @pytest.fixture
  2112. def bind_server(self):
  2113. """Create a BindServer instance."""
  2114. from backend.app.services.virtual_printer.bind_server import BindServer
  2115. return BindServer(
  2116. serial="09400A391800001",
  2117. model="O1D",
  2118. name="Bambuddy",
  2119. )
  2120. def test_build_frame(self, bind_server):
  2121. """Verify frame building produces correct format."""
  2122. payload = {"login": {"command": "detect"}}
  2123. frame = bind_server._build_frame(payload)
  2124. # Header: 0xA5A5
  2125. assert frame[:2] == b"\xa5\xa5"
  2126. # Trailer: 0xA7A7
  2127. assert frame[-2:] == b"\xa7\xa7"
  2128. # Length field is total message size (LE uint16)
  2129. import struct
  2130. total_len = struct.unpack_from("<H", frame, 2)[0]
  2131. assert total_len == len(frame)
  2132. # JSON payload is between header and trailer
  2133. import json
  2134. json_bytes = frame[4:-2]
  2135. parsed = json.loads(json_bytes)
  2136. assert parsed == payload
  2137. def test_parse_frame_valid(self, bind_server):
  2138. """Verify valid frame parsing extracts JSON correctly."""
  2139. import json
  2140. import struct
  2141. payload = {"login": {"command": "detect", "sequence_id": "20000"}}
  2142. json_bytes = json.dumps(payload, separators=(",", ":")).encode()
  2143. total_len = 4 + len(json_bytes) + 2
  2144. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + json_bytes + b"\xa7\xa7"
  2145. result = bind_server._parse_frame(frame)
  2146. assert result is not None
  2147. assert result["login"]["command"] == "detect"
  2148. assert result["login"]["sequence_id"] == "20000"
  2149. def test_parse_frame_invalid_header(self, bind_server):
  2150. """Verify invalid header returns None."""
  2151. result = bind_server._parse_frame(b"\xbb\xbb\x06\x00{}\xa7\xa7")
  2152. assert result is None
  2153. def test_parse_frame_invalid_trailer(self, bind_server):
  2154. """Verify invalid trailer returns None."""
  2155. result = bind_server._parse_frame(b"\xa5\xa5\x06\x00{}\xbb\xbb")
  2156. assert result is None
  2157. def test_parse_frame_too_short(self, bind_server):
  2158. """Verify short data returns None."""
  2159. result = bind_server._parse_frame(b"\xa5\xa5\x00")
  2160. assert result is None
  2161. def test_parse_frame_invalid_json(self, bind_server):
  2162. """Verify invalid JSON returns None."""
  2163. import struct
  2164. bad_json = b"not json"
  2165. total_len = 4 + len(bad_json) + 2
  2166. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  2167. result = bind_server._parse_frame(frame)
  2168. assert result is None
  2169. def test_build_frame_roundtrip(self, bind_server):
  2170. """Verify build_frame output can be parsed back."""
  2171. payload = {
  2172. "login": {
  2173. "bind": "free",
  2174. "command": "detect",
  2175. "connect": "lan",
  2176. "dev_cap": 1,
  2177. "id": "09400A391800001",
  2178. "model": "O1D",
  2179. "name": "Bambuddy",
  2180. "sequence_id": 3021,
  2181. "version": "01.00.00.00",
  2182. }
  2183. }
  2184. frame = bind_server._build_frame(payload)
  2185. parsed = bind_server._parse_frame(frame)
  2186. assert parsed is not None
  2187. assert parsed["login"]["id"] == "09400A391800001"
  2188. assert parsed["login"]["model"] == "O1D"
  2189. assert parsed["login"]["name"] == "Bambuddy"
  2190. assert parsed["login"]["bind"] == "free"
  2191. def test_bind_server_stores_config(self, bind_server):
  2192. """Verify bind server stores serial, model, name."""
  2193. assert bind_server.serial == "09400A391800001"
  2194. assert bind_server.model == "O1D"
  2195. assert bind_server.name == "Bambuddy"
  2196. assert bind_server.version == "01.00.00.00"
  2197. def test_bind_server_custom_version(self):
  2198. """Verify custom firmware version is stored."""
  2199. from backend.app.services.virtual_printer.bind_server import BindServer
  2200. server = BindServer(
  2201. serial="TEST123",
  2202. model="C13",
  2203. name="Test",
  2204. version="02.03.04.05",
  2205. )
  2206. assert server.version == "02.03.04.05"
  2207. def test_bind_ports_constant(self):
  2208. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  2209. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  2210. assert 3000 in BIND_PORTS
  2211. assert 3002 in BIND_PORTS
  2212. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  2213. """Verify bind server starts with empty servers list."""
  2214. assert bind_server._servers == []
  2215. assert bind_server._running is False
  2216. class TestSlicerProxyManager:
  2217. """Tests for SlicerProxyManager (proxy mode)."""
  2218. @pytest.fixture
  2219. def proxy_manager(self, tmp_path):
  2220. """Create a SlicerProxyManager instance."""
  2221. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  2222. # Create dummy cert files
  2223. cert_path = tmp_path / "cert.pem"
  2224. key_path = tmp_path / "key.pem"
  2225. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  2226. # Split string to avoid pre-commit hook false positive on test data
  2227. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  2228. return SlicerProxyManager(
  2229. target_host="192.168.1.100",
  2230. cert_path=cert_path,
  2231. key_path=key_path,
  2232. )
  2233. def test_proxy_manager_initializes_ports(self, proxy_manager):
  2234. """Verify proxy manager has correct port constants."""
  2235. # FTP proxy uses privileged port 990 to match what Bambu Studio expects
  2236. assert proxy_manager.LOCAL_FTP_PORT == 990
  2237. assert proxy_manager.LOCAL_MQTT_PORT == 8883
  2238. assert proxy_manager.PRINTER_FTP_PORT == 990
  2239. assert proxy_manager.PRINTER_MQTT_PORT == 8883
  2240. assert proxy_manager.PRINTER_FILE_TRANSFER_PORT == 6000
  2241. assert proxy_manager.PRINTER_RTSP_PORT == 322
  2242. # Auxiliary ports: undocumented proprietary ports for A1/P1S etc.
  2243. assert proxy_manager.PRINTER_AUX_PORTS == [2024, 2025, 2026]
  2244. # Bind ports: both 3000 and 3002 for slicer compatibility
  2245. assert proxy_manager.PRINTER_BIND_PORTS == [3000, 3002]
  2246. # FTP data port range for transparent EPSV proxying
  2247. assert proxy_manager.FTP_DATA_PORT_MIN == 50000
  2248. assert proxy_manager.FTP_DATA_PORT_MAX == 50100
  2249. def test_proxy_manager_stores_target_host(self, proxy_manager):
  2250. """Verify proxy manager stores target host."""
  2251. assert proxy_manager.target_host == "192.168.1.100"
  2252. def test_get_status_before_start(self, proxy_manager):
  2253. """Verify get_status returns zeros before start."""
  2254. status = proxy_manager.get_status()
  2255. assert status["running"] is False
  2256. assert status["ftp_connections"] == 0
  2257. assert status["mqtt_connections"] == 0
  2258. @pytest.mark.asyncio
  2259. async def test_proxy_start_creates_transparent_proxies(self, tmp_path):
  2260. """Verify start() uses TCPProxy for FTP/FileTransfer/RTSP and TLSProxy only for MQTT.
  2261. The transparent proxy architecture preserves end-to-end TLS between
  2262. slicer and printer for all protocols except MQTT, which must be
  2263. TLS-terminated to rewrite the printer's IP in MQTT payloads.
  2264. """
  2265. from unittest.mock import AsyncMock, patch
  2266. from backend.app.services.virtual_printer.tcp_proxy import (
  2267. SlicerProxyManager,
  2268. TCPProxy,
  2269. TLSProxy,
  2270. )
  2271. cert_path = tmp_path / "cert.pem"
  2272. key_path = tmp_path / "key.pem"
  2273. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  2274. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  2275. mgr = SlicerProxyManager(
  2276. target_host="192.168.1.100",
  2277. cert_path=cert_path,
  2278. key_path=key_path,
  2279. bind_address="10.0.0.1",
  2280. )
  2281. # Mock asyncio.create_task and asyncio.gather to prevent actual server start
  2282. with (
  2283. patch("asyncio.create_task") as mock_create_task,
  2284. patch("asyncio.gather", new_callable=AsyncMock),
  2285. patch.object(SlicerProxyManager, "_log_activity"),
  2286. ):
  2287. mock_create_task.return_value = MagicMock()
  2288. # start() will create proxies then try to gather tasks — we just
  2289. # need to verify the proxy types after creation.
  2290. # Trigger start but let gather return immediately.
  2291. await mgr.start()
  2292. # FTP, FileTransfer, RTSP should be TCPProxy (transparent)
  2293. assert isinstance(mgr._ftp_proxy, TCPProxy), "FTP should be TCPProxy (transparent)"
  2294. assert isinstance(mgr._file_transfer_proxy, TCPProxy), "FileTransfer should be TCPProxy"
  2295. assert isinstance(mgr._rtsp_proxy, TCPProxy), "RTSP should be TCPProxy"
  2296. # MQTT should be TLSProxy (TLS-terminated for IP rewriting)
  2297. assert isinstance(mgr._mqtt_proxy, TLSProxy), "MQTT should be TLSProxy (TLS-terminated)"
  2298. # Auxiliary ports (2024-2026) should be TCPProxy (transparent)
  2299. assert len(mgr._aux_proxies) == 3, "Should have 3 aux port proxies"
  2300. for ap in mgr._aux_proxies:
  2301. assert isinstance(ap, TCPProxy), "Aux proxies should be TCPProxy"
  2302. assert mgr._aux_proxies[0].listen_port == 2024
  2303. assert mgr._aux_proxies[0].target_port == 2024
  2304. assert mgr._aux_proxies[2].listen_port == 2026
  2305. # FTP data ports should be pre-created as TCPProxy instances
  2306. assert len(mgr._ftp_data_proxies) == 101 # 50000-50100 inclusive
  2307. for dp in mgr._ftp_data_proxies:
  2308. assert isinstance(dp, TCPProxy), "FTP data proxies should be TCPProxy"
  2309. # Verify FTP data proxies target the same port on the printer
  2310. first_dp = mgr._ftp_data_proxies[0]
  2311. assert first_dp.listen_port == 50000
  2312. assert first_dp.target_port == 50000
  2313. assert first_dp.target_host == "192.168.1.100"
  2314. last_dp = mgr._ftp_data_proxies[-1]
  2315. assert last_dp.listen_port == 50100
  2316. assert last_dp.target_port == 50100
  2317. def test_proxy_manager_mqtt_has_ip_rewriting(self, tmp_path):
  2318. """Verify MQTT proxy is configured with IP rewriting when bind_address is set."""
  2319. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  2320. cert_path = tmp_path / "cert.pem"
  2321. key_path = tmp_path / "key.pem"
  2322. cert_path.write_text("-----BEGIN CERTIFICATE-----\ntest\n-----END CERTIFICATE-----")
  2323. key_path.write_text("-----BEGIN " + "PRIVATE KEY-----\ntest\n-----END " + "PRIVATE KEY-----")
  2324. mgr = SlicerProxyManager(
  2325. target_host="192.168.1.100",
  2326. cert_path=cert_path,
  2327. key_path=key_path,
  2328. bind_address="10.0.0.1",
  2329. )
  2330. # Before start, proxies are None — verify constructor stores rewrite config
  2331. assert mgr.bind_address == "10.0.0.1"
  2332. assert mgr.target_host == "192.168.1.100"
  2333. class TestSSDPProxy:
  2334. """Tests for SSDPProxy (cross-network SSDP relay)."""
  2335. @pytest.fixture
  2336. def ssdp_proxy(self):
  2337. """Create an SSDPProxy instance."""
  2338. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2339. return SSDPProxy(
  2340. local_interface_ip="192.168.1.100",
  2341. remote_interface_ip="10.0.0.100",
  2342. target_printer_ip="192.168.1.50",
  2343. )
  2344. def test_ssdp_proxy_stores_interface_ips(self, ssdp_proxy):
  2345. """Verify SSDPProxy stores interface IPs correctly."""
  2346. assert ssdp_proxy.local_interface_ip == "192.168.1.100"
  2347. assert ssdp_proxy.remote_interface_ip == "10.0.0.100"
  2348. assert ssdp_proxy.target_printer_ip == "192.168.1.50"
  2349. def test_rewrite_ssdp_location(self, ssdp_proxy):
  2350. """Verify SSDP Location header is rewritten to remote interface IP."""
  2351. original_packet = b"NOTIFY * HTTP/1.1\r\nLocation: 192.168.1.50\r\nDevName.bambu.com: TestPrinter\r\n\r\n"
  2352. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  2353. # Location should be changed to remote interface IP
  2354. assert b"Location: 10.0.0.100" in rewritten
  2355. assert b"Location: 192.168.1.50" not in rewritten
  2356. # Other headers should be preserved
  2357. assert b"DevName.bambu.com: TestPrinter" in rewritten
  2358. def test_rewrite_ssdp_location_case_insensitive(self, ssdp_proxy):
  2359. """Verify SSDP Location rewrite is case insensitive."""
  2360. original_packet = b"NOTIFY * HTTP/1.1\r\nlocation: 192.168.1.50\r\n\r\n"
  2361. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  2362. assert b"10.0.0.100" in rewritten
  2363. def test_rewrite_ssdp_location_no_match(self, ssdp_proxy):
  2364. """Verify packet without Location header is returned unchanged."""
  2365. original_packet = b"NOTIFY * HTTP/1.1\r\nDevName.bambu.com: Test\r\n\r\n"
  2366. rewritten = ssdp_proxy._rewrite_ssdp(original_packet)
  2367. # No Location header, but _rewrite_ssdp logs a warning and returns as-is
  2368. assert b"DevName.bambu.com: Test" in rewritten
  2369. def test_parse_ssdp_message(self, ssdp_proxy):
  2370. """Verify SSDP message parsing extracts headers."""
  2371. packet = (
  2372. b"NOTIFY * HTTP/1.1\r\n"
  2373. b"Location: 192.168.1.50\r\n"
  2374. b"DevName.bambu.com: TestPrinter\r\n"
  2375. b"DevModel.bambu.com: BL-P001\r\n"
  2376. b"\r\n"
  2377. )
  2378. headers = ssdp_proxy._parse_ssdp_message(packet)
  2379. assert headers["location"] == "192.168.1.50"
  2380. assert headers["devname.bambu.com"] == "TestPrinter"
  2381. assert headers["devmodel.bambu.com"] == "BL-P001"
  2382. class TestVirtualPrinterManagerDirectories:
  2383. """Tests for VirtualPrinterManager directory management."""
  2384. def test_ensure_base_directories_creates_subdirs(self, tmp_path):
  2385. """Verify _ensure_base_directories creates required base directories."""
  2386. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  2387. manager = VirtualPrinterManager()
  2388. manager._base_dir = tmp_path / "virtual_printer"
  2389. manager._ensure_base_directories()
  2390. assert (tmp_path / "virtual_printer").exists()
  2391. assert (tmp_path / "virtual_printer" / "uploads").exists()
  2392. assert (tmp_path / "virtual_printer" / "certs").exists()
  2393. def test_ensure_base_directories_handles_permission_error(self, tmp_path, caplog):
  2394. """Verify _ensure_base_directories logs error on permission failure."""
  2395. import logging
  2396. from backend.app.services.virtual_printer.manager import VirtualPrinterManager
  2397. manager = VirtualPrinterManager()
  2398. vp_dir = tmp_path / "virtual_printer"
  2399. manager._base_dir = vp_dir
  2400. original_mkdir = type(vp_dir).mkdir
  2401. def mock_mkdir(self, *args, **kwargs):
  2402. if "virtual_printer" in str(self):
  2403. raise PermissionError("Permission denied")
  2404. return original_mkdir(self, *args, **kwargs)
  2405. with caplog.at_level(logging.ERROR), patch.object(type(vp_dir), "mkdir", mock_mkdir):
  2406. manager._ensure_base_directories()
  2407. assert "Permission denied" in caplog.text
  2408. def test_instance_creates_per_vp_directories(self, tmp_path):
  2409. """Verify VirtualPrinterInstance creates per-VP upload and cert dirs."""
  2410. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2411. VirtualPrinterInstance(
  2412. vp_id=42,
  2413. name="Test",
  2414. mode="archive",
  2415. model="C11",
  2416. access_code="12345678",
  2417. serial_suffix="391800042",
  2418. base_dir=tmp_path,
  2419. )
  2420. assert (tmp_path / "uploads" / "42").exists()
  2421. assert (tmp_path / "uploads" / "42" / "cache").exists()
  2422. assert (tmp_path / "certs" / "42").exists()
  2423. class TestVirtualPrinterInstanceProxyMode:
  2424. """Tests for VirtualPrinterInstance proxy mode."""
  2425. @pytest.fixture
  2426. def proxy_instance(self, tmp_path):
  2427. """Create a proxy-mode VirtualPrinterInstance."""
  2428. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2429. return VirtualPrinterInstance(
  2430. vp_id=10,
  2431. name="ProxyTest",
  2432. mode="proxy",
  2433. model="C11",
  2434. access_code="",
  2435. serial_suffix="391800010",
  2436. target_printer_ip="192.168.1.100",
  2437. target_printer_serial="01P00A000000001",
  2438. base_dir=tmp_path,
  2439. )
  2440. def test_proxy_instance_properties(self, proxy_instance):
  2441. """Verify proxy instance stores config correctly."""
  2442. assert proxy_instance.is_proxy is True
  2443. assert proxy_instance.mode == "proxy"
  2444. assert proxy_instance.target_printer_ip == "192.168.1.100"
  2445. assert proxy_instance.target_printer_serial == "01P00A000000001"
  2446. def test_proxy_instance_does_not_require_access_code(self, proxy_instance):
  2447. """Verify proxy mode can have empty access code."""
  2448. assert proxy_instance.access_code == ""
  2449. def test_get_status_proxy_includes_proxy_fields(self, proxy_instance):
  2450. """Verify get_status includes proxy fields when proxy is active."""
  2451. mock_proxy = MagicMock()
  2452. mock_proxy.get_status.return_value = {
  2453. "running": True,
  2454. "ftp_port": 990,
  2455. "mqtt_port": 8883,
  2456. "ftp_connections": 1,
  2457. "mqtt_connections": 2,
  2458. "target_host": "192.168.1.100",
  2459. }
  2460. proxy_instance._proxy = mock_proxy
  2461. status = proxy_instance.get_status()
  2462. assert "proxy" in status
  2463. assert status["proxy"]["ftp_port"] == 990
  2464. assert status["proxy"]["mqtt_connections"] == 2
  2465. def test_proxy_instance_stores_remote_interface(self, tmp_path):
  2466. """Verify proxy instance stores remote_interface_ip."""
  2467. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2468. inst = VirtualPrinterInstance(
  2469. vp_id=11,
  2470. name="Proxy2",
  2471. mode="proxy",
  2472. model="C11",
  2473. access_code="",
  2474. serial_suffix="391800011",
  2475. target_printer_ip="192.168.1.100",
  2476. remote_interface_ip="10.0.0.50",
  2477. base_dir=tmp_path,
  2478. )
  2479. assert inst.remote_interface_ip == "10.0.0.50"
  2480. class TestVirtualPrinterInstanceIPOverride:
  2481. """Tests for remote_interface_ip and bind_ip on VirtualPrinterInstance."""
  2482. @pytest.fixture
  2483. def instance_with_remote_ip(self, tmp_path):
  2484. """Create an instance with remote_interface_ip set."""
  2485. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2486. return VirtualPrinterInstance(
  2487. vp_id=20,
  2488. name="IPTest",
  2489. mode="archive",
  2490. model="BL-P001",
  2491. access_code="12345678",
  2492. serial_suffix="391800020",
  2493. bind_ip="192.168.1.50",
  2494. remote_interface_ip="10.0.0.50",
  2495. base_dir=tmp_path,
  2496. )
  2497. def test_instance_stores_bind_ip(self, instance_with_remote_ip):
  2498. """Verify bind_ip is stored."""
  2499. assert instance_with_remote_ip.bind_ip == "192.168.1.50"
  2500. def test_instance_stores_remote_interface_ip(self, instance_with_remote_ip):
  2501. """Verify remote_interface_ip is stored."""
  2502. assert instance_with_remote_ip.remote_interface_ip == "10.0.0.50"
  2503. def test_generate_certificates_includes_remote_and_bind_ip(self, instance_with_remote_ip):
  2504. """Verify generate_certificates passes remote_interface_ip and bind_ip as SANs."""
  2505. with (
  2506. patch.object(instance_with_remote_ip._cert_service, "delete_printer_certificate"),
  2507. patch.object(
  2508. instance_with_remote_ip._cert_service,
  2509. "generate_certificates",
  2510. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2511. ) as mock_gen,
  2512. ):
  2513. instance_with_remote_ip.generate_certificates()
  2514. mock_gen.assert_called_once_with(additional_ips=["10.0.0.50", "192.168.1.50"])
  2515. def test_generate_certificates_no_remote_ip(self, tmp_path):
  2516. """Verify generate_certificates passes only bind_ip when no remote_interface_ip."""
  2517. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2518. inst = VirtualPrinterInstance(
  2519. vp_id=21,
  2520. name="NoRemote",
  2521. mode="archive",
  2522. model="BL-P001",
  2523. access_code="12345678",
  2524. serial_suffix="391800021",
  2525. bind_ip="192.168.1.50",
  2526. base_dir=tmp_path,
  2527. )
  2528. with (
  2529. patch.object(inst._cert_service, "delete_printer_certificate"),
  2530. patch.object(
  2531. inst._cert_service,
  2532. "generate_certificates",
  2533. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2534. ) as mock_gen,
  2535. ):
  2536. inst.generate_certificates()
  2537. mock_gen.assert_called_once_with(additional_ips=["192.168.1.50"])
  2538. def test_generate_certificates_no_ips(self, tmp_path):
  2539. """Verify generate_certificates passes None when no IPs configured."""
  2540. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2541. inst = VirtualPrinterInstance(
  2542. vp_id=22,
  2543. name="NoIPs",
  2544. mode="archive",
  2545. model="BL-P001",
  2546. access_code="12345678",
  2547. serial_suffix="391800022",
  2548. base_dir=tmp_path,
  2549. )
  2550. with (
  2551. patch.object(inst._cert_service, "delete_printer_certificate"),
  2552. patch.object(
  2553. inst._cert_service,
  2554. "generate_certificates",
  2555. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2556. ) as mock_gen,
  2557. ):
  2558. inst.generate_certificates()
  2559. mock_gen.assert_called_once_with(additional_ips=None)
  2560. class TestBindServer:
  2561. """Tests for the BindServer (port 3002 bind/detect protocol)."""
  2562. @pytest.fixture
  2563. def bind_server(self):
  2564. """Create a BindServer instance."""
  2565. from backend.app.services.virtual_printer.bind_server import BindServer
  2566. return BindServer(
  2567. serial="01S00C000000001",
  2568. model="BL-P001",
  2569. name="Bambuddy",
  2570. )
  2571. def test_build_frame(self, bind_server):
  2572. """Verify frame format: 0xA5A5 + len(u16le) + JSON + 0xA7A7."""
  2573. payload = {"login": {"command": "detect"}}
  2574. frame = bind_server._build_frame(payload)
  2575. assert frame[:2] == b"\xa5\xa5"
  2576. assert frame[-2:] == b"\xa7\xa7"
  2577. # Length field is total message size
  2578. import struct
  2579. total_len = struct.unpack_from("<H", frame, 2)[0]
  2580. assert total_len == len(frame)
  2581. # JSON payload is between header and trailer
  2582. import json
  2583. json_bytes = frame[4:-2]
  2584. parsed = json.loads(json_bytes)
  2585. assert parsed == payload
  2586. def test_parse_frame_valid(self, bind_server):
  2587. """Verify valid frame parsing."""
  2588. frame = bind_server._build_frame({"login": {"command": "detect", "sequence_id": "20000"}})
  2589. result = bind_server._parse_frame(frame)
  2590. assert result is not None
  2591. assert result["login"]["command"] == "detect"
  2592. assert result["login"]["sequence_id"] == "20000"
  2593. def test_parse_frame_invalid_header(self, bind_server):
  2594. """Verify invalid header returns None."""
  2595. frame = b"\xb5\xb5\x10\x00" + b'{"login":{}}' + b"\xa7\xa7"
  2596. assert bind_server._parse_frame(frame) is None
  2597. def test_parse_frame_invalid_trailer(self, bind_server):
  2598. """Verify invalid trailer returns None."""
  2599. frame = b"\xa5\xa5\x10\x00" + b'{"login":{}}' + b"\xb7\xb7"
  2600. assert bind_server._parse_frame(frame) is None
  2601. def test_parse_frame_too_short(self, bind_server):
  2602. """Verify short data returns None."""
  2603. assert bind_server._parse_frame(b"\xa5\xa5\x00") is None
  2604. assert bind_server._parse_frame(b"") is None
  2605. def test_parse_frame_invalid_json(self, bind_server):
  2606. """Verify invalid JSON returns None."""
  2607. import struct
  2608. bad_json = b"not json"
  2609. total_len = 4 + len(bad_json) + 2
  2610. frame = b"\xa5\xa5" + struct.pack("<H", total_len) + bad_json + b"\xa7\xa7"
  2611. assert bind_server._parse_frame(frame) is None
  2612. def test_build_frame_roundtrip(self, bind_server):
  2613. """Verify build then parse roundtrip."""
  2614. original = {"login": {"bind": "free", "command": "detect", "id": "01S00C000000001"}}
  2615. frame = bind_server._build_frame(original)
  2616. parsed = bind_server._parse_frame(frame)
  2617. assert parsed == original
  2618. def test_bind_server_stores_config(self, bind_server):
  2619. """Verify config is stored correctly."""
  2620. assert bind_server.serial == "01S00C000000001"
  2621. assert bind_server.model == "BL-P001"
  2622. assert bind_server.name == "Bambuddy"
  2623. assert bind_server.version == "01.00.00.00"
  2624. def test_bind_server_custom_version(self):
  2625. """Verify custom firmware version is stored."""
  2626. from backend.app.services.virtual_printer.bind_server import BindServer
  2627. server = BindServer(
  2628. serial="01S00C000000001",
  2629. model="BL-P001",
  2630. name="Bambuddy",
  2631. version="01.09.00.10",
  2632. )
  2633. assert server.version == "01.09.00.10"
  2634. def test_bind_ports_includes_both(self):
  2635. """Verify BIND_PORTS includes both 3000 and 3002 for slicer compatibility."""
  2636. from backend.app.services.virtual_printer.bind_server import BIND_PORTS
  2637. assert 3000 in BIND_PORTS
  2638. assert 3002 in BIND_PORTS
  2639. def test_bind_server_initializes_empty_servers_list(self, bind_server):
  2640. """Verify bind server starts with empty servers list."""
  2641. assert bind_server._servers == []
  2642. assert bind_server._running is False
  2643. @pytest.mark.asyncio
  2644. async def test_start_server_creates_bind_server(self, tmp_path):
  2645. """Verify start_server creates BindServer with correct params."""
  2646. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2647. inst = VirtualPrinterInstance(
  2648. vp_id=99,
  2649. name="Bambuddy",
  2650. mode="archive",
  2651. model="BL-P001",
  2652. access_code="12345678",
  2653. serial_suffix="391800099",
  2654. bind_ip="192.168.1.50",
  2655. base_dir=tmp_path,
  2656. )
  2657. # Each mocked child service exposes a real asyncio.Event for the
  2658. # readiness barrier added in start_server (set on instantiation so
  2659. # the barrier returns immediately in tests).
  2660. ready_event = asyncio.Event()
  2661. ready_event.set()
  2662. def with_ready(*_args, **_kwargs):
  2663. child = MagicMock()
  2664. child.ready = ready_event
  2665. return child
  2666. with (
  2667. patch(
  2668. "backend.app.services.virtual_printer.manager.VirtualPrinterSSDPServer",
  2669. side_effect=with_ready,
  2670. ),
  2671. patch(
  2672. "backend.app.services.virtual_printer.manager.VirtualPrinterFTPServer",
  2673. side_effect=with_ready,
  2674. ),
  2675. patch(
  2676. "backend.app.services.virtual_printer.manager.SimpleMQTTServer",
  2677. side_effect=with_ready,
  2678. ),
  2679. patch(
  2680. "backend.app.services.virtual_printer.manager.BindServer",
  2681. side_effect=with_ready,
  2682. ) as mock_bind_cls,
  2683. patch.object(inst._cert_service, "delete_printer_certificate"),
  2684. patch.object(
  2685. inst._cert_service,
  2686. "generate_certificates",
  2687. return_value=(Path("/tmp/cert.pem"), Path("/tmp/key.pem")), # nosec B108
  2688. ),
  2689. ):
  2690. await inst.start_server()
  2691. mock_bind_cls.assert_called_once_with(
  2692. serial=inst.serial,
  2693. model="BL-P001",
  2694. name="Bambuddy",
  2695. bind_address="192.168.1.50",
  2696. cert_path=Path("/tmp/cert.pem"), # nosec B108
  2697. key_path=Path("/tmp/key.pem"), # nosec B108
  2698. )
  2699. class TestResolveModelCodes:
  2700. """Tests for model code resolution (display name → SSDP code)."""
  2701. def test_display_name_to_model_code_maps_all_models(self):
  2702. """Verify reverse mapping covers all VIRTUAL_PRINTER_MODELS entries."""
  2703. from backend.app.services.virtual_printer.manager import DISPLAY_NAME_TO_MODEL_CODE, VIRTUAL_PRINTER_MODELS
  2704. for _code, display_name in VIRTUAL_PRINTER_MODELS.items():
  2705. assert display_name in DISPLAY_NAME_TO_MODEL_CODE
  2706. # For non-duplicate display names, should map back to a valid code
  2707. assert DISPLAY_NAME_TO_MODEL_CODE[display_name] in VIRTUAL_PRINTER_MODELS
  2708. def test_resolve_printer_model_with_ssdp_code(self):
  2709. """SSDP codes pass through unchanged."""
  2710. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2711. assert _resolve_printer_model("BL-P001") == "BL-P001"
  2712. assert _resolve_printer_model("O1D") == "O1D"
  2713. assert _resolve_printer_model("N2S") == "N2S"
  2714. def test_resolve_printer_model_with_display_name(self):
  2715. """Display names resolve to SSDP codes."""
  2716. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2717. assert _resolve_printer_model("X1C") == "BL-P001"
  2718. assert _resolve_printer_model("H2D") == "O1D"
  2719. assert _resolve_printer_model("A1") == "N2S"
  2720. assert _resolve_printer_model("P1S") == "C12"
  2721. def test_resolve_printer_model_with_none_or_unknown(self):
  2722. """None and unknown values return None."""
  2723. from backend.app.api.routes.virtual_printers import _resolve_printer_model
  2724. assert _resolve_printer_model(None) is None
  2725. assert _resolve_printer_model("UnknownModel") is None
  2726. class TestMqttIpRewrite:
  2727. """Tests for TLSProxy._rewrite_mqtt_ip() MQTT packet IP rewriting."""
  2728. @staticmethod
  2729. def _build_mqtt_publish(topic: str, payload: bytes) -> bytes:
  2730. """Build a minimal MQTT PUBLISH packet."""
  2731. # PUBLISH fixed header: type 3, no flags
  2732. topic_bytes = topic.encode("utf-8")
  2733. # Variable header: topic length (2 bytes) + topic
  2734. var_header = len(topic_bytes).to_bytes(2, "big") + topic_bytes
  2735. body = var_header + payload
  2736. # Encode remaining length
  2737. remaining = len(body)
  2738. header = bytearray([0x30]) # PUBLISH, QoS 0
  2739. while True:
  2740. encoded_byte = remaining % 128
  2741. remaining //= 128
  2742. if remaining > 0:
  2743. encoded_byte |= 0x80
  2744. header.append(encoded_byte)
  2745. if remaining == 0:
  2746. break
  2747. return bytes(header) + body
  2748. @staticmethod
  2749. def _build_mqtt_pingreq() -> bytes:
  2750. """Build an MQTT PINGREQ packet (2 bytes, no payload)."""
  2751. return b"\xc0\x00"
  2752. def test_rewrite_ip_in_publish(self):
  2753. """IP string in PUBLISH payload is rewritten."""
  2754. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2755. payload = b'{"rtsp_url":"rtsps://192.168.1.100:322/live"}'
  2756. packet = self._build_mqtt_publish("device/status", payload)
  2757. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  2758. assert b"10.0.0.1" in result
  2759. assert b"192.168.1.100" not in result
  2760. def test_no_rewrite_when_ip_absent(self):
  2761. """Packets without the target IP are passed through unchanged."""
  2762. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2763. payload = b'{"status":"idle"}'
  2764. packet = self._build_mqtt_publish("device/status", payload)
  2765. result, buf = TLSProxy._rewrite_mqtt_ip(packet, b"192.168.1.100", b"10.0.0.1", bytearray())
  2766. assert result == packet
  2767. def test_non_publish_packets_unchanged(self):
  2768. """Non-PUBLISH packets (e.g. PINGREQ) are never rewritten."""
  2769. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2770. pingreq = self._build_mqtt_pingreq()
  2771. result, buf = TLSProxy._rewrite_mqtt_ip(pingreq, b"192.168.1.100", b"10.0.0.1", bytearray())
  2772. assert result == pingreq
  2773. def test_rewrite_preserves_packet_framing(self):
  2774. """Rewritten packet has valid MQTT remaining length."""
  2775. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2776. # Use IPs of different lengths to test length re-encoding
  2777. old_ip = b"192.168.255.133" # 15 bytes
  2778. new_ip = b"10.0.0.1" # 8 bytes
  2779. payload = b'{"ip":"192.168.255.133"}'
  2780. packet = self._build_mqtt_publish("device/status", payload)
  2781. result, buf = TLSProxy._rewrite_mqtt_ip(packet, old_ip, new_ip, bytearray())
  2782. # Parse the result to verify framing
  2783. assert result[0] == 0x30 # PUBLISH header byte
  2784. # Decode remaining length
  2785. pos = 1
  2786. remaining = 0
  2787. multiplier = 1
  2788. while True:
  2789. b = result[pos]
  2790. pos += 1
  2791. remaining += (b & 0x7F) * multiplier
  2792. multiplier *= 128
  2793. if (b & 0x80) == 0:
  2794. break
  2795. # Remaining length should match actual data
  2796. assert pos + remaining == len(result)
  2797. assert new_ip in result
  2798. def test_incomplete_packet_buffered(self):
  2799. """Incomplete packet at end of chunk is buffered for next call."""
  2800. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2801. payload = b'{"ip":"192.168.1.100"}'
  2802. packet = self._build_mqtt_publish("device/status", payload)
  2803. # Split packet in the middle
  2804. half = len(packet) // 2
  2805. chunk1 = packet[:half]
  2806. chunk2 = packet[half:]
  2807. result1, buf = TLSProxy._rewrite_mqtt_ip(chunk1, b"192.168.1.100", b"10.0.0.1", bytearray())
  2808. # First chunk should be buffered (incomplete packet)
  2809. assert len(buf) > 0
  2810. result2, buf = TLSProxy._rewrite_mqtt_ip(chunk2, b"192.168.1.100", b"10.0.0.1", buf)
  2811. # Second chunk completes the packet, IP should be rewritten
  2812. combined = result1 + result2
  2813. assert b"10.0.0.1" in combined
  2814. assert b"192.168.1.100" not in combined
  2815. def test_multiple_packets_in_one_chunk(self):
  2816. """Multiple MQTT packets in a single chunk are all processed."""
  2817. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2818. payload1 = b'{"ip":"192.168.1.100"}'
  2819. payload2 = b'{"other":"data"}'
  2820. packet1 = self._build_mqtt_publish("topic1", payload1)
  2821. packet2 = self._build_mqtt_publish("topic2", payload2)
  2822. combined = packet1 + packet2
  2823. result, buf = TLSProxy._rewrite_mqtt_ip(combined, b"192.168.1.100", b"10.0.0.1", bytearray())
  2824. assert b"10.0.0.1" in result
  2825. assert b"192.168.1.100" not in result
  2826. # Second packet should still be present
  2827. assert b"other" in result
  2828. def test_extra_replacements(self):
  2829. """Extra replacement pairs (e.g. integer IP) are also applied."""
  2830. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2831. payload = b'{"net":{"info":[{"ip":2248124608}]}}'
  2832. packet = self._build_mqtt_publish("device/status", payload)
  2833. result, buf = TLSProxy._rewrite_mqtt_ip(
  2834. packet,
  2835. b"NOMATCH",
  2836. b"NOREPLACE",
  2837. bytearray(),
  2838. extra_replacements=[(b"2248124608", b"285190336")],
  2839. )
  2840. assert b"285190336" in result
  2841. assert b"2248124608" not in result
  2842. class TestIpToLeIntBytes:
  2843. """Tests for TLSProxy._ip_to_le_int_bytes() integer IP conversion."""
  2844. def test_converts_ip_to_le_int(self):
  2845. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2846. assert TLSProxy._ip_to_le_int_bytes("192.168.255.133") == b"2248124608"
  2847. assert TLSProxy._ip_to_le_int_bytes("192.168.255.16") == b"285190336"
  2848. assert TLSProxy._ip_to_le_int_bytes("10.0.0.1") == b"16777226"
  2849. def test_roundtrip(self):
  2850. """Verify the integer converts back to the correct IP."""
  2851. import struct
  2852. from backend.app.services.virtual_printer.tcp_proxy import TLSProxy
  2853. for ip in ["192.168.1.1", "10.0.0.1", "172.16.0.100", "192.168.255.133"]:
  2854. le_int = int(TLSProxy._ip_to_le_int_bytes(ip))
  2855. parts = ip.split(".")
  2856. expected = struct.unpack("<I", bytes(int(p) for p in parts))[0]
  2857. assert le_int == expected
  2858. class TestSSDPProxyName:
  2859. """Tests for SSDPProxy VP name rewriting."""
  2860. @pytest.fixture
  2861. def ssdp_proxy_with_name(self):
  2862. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2863. return SSDPProxy(
  2864. local_interface_ip="192.168.1.100",
  2865. remote_interface_ip="10.0.0.100",
  2866. target_printer_ip="192.168.1.50",
  2867. name="H2D-1 Proxy",
  2868. )
  2869. @pytest.fixture
  2870. def ssdp_proxy_without_name(self):
  2871. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy
  2872. return SSDPProxy(
  2873. local_interface_ip="192.168.1.100",
  2874. remote_interface_ip="10.0.0.100",
  2875. target_printer_ip="192.168.1.50",
  2876. )
  2877. def test_rewrite_uses_configured_name(self, ssdp_proxy_with_name):
  2878. """When name is set, DevName is replaced entirely."""
  2879. 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"
  2880. rewritten = ssdp_proxy_with_name._rewrite_ssdp(packet)
  2881. assert b"DevName.bambu.com: H2D-1 Proxy" in rewritten
  2882. assert b"RealPrinter" not in rewritten
  2883. def test_rewrite_appends_proxy_without_name(self, ssdp_proxy_without_name):
  2884. """When no name is set, ' - Proxy' is appended to the real name."""
  2885. 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"
  2886. rewritten = ssdp_proxy_without_name._rewrite_ssdp(packet)
  2887. assert b"DevName.bambu.com: RealPrinter - Proxy" in rewritten
  2888. class TestVPProjectFileStashKey:
  2889. """Regression: `on_print_command` MUST stash slicer options under the
  2890. FTP filename (`data["file"]`, with extension), NOT under `filename`
  2891. (the slicer's `subtask_name`, bare).
  2892. #1780 root cause (real bundle, 2026-06-21): BambuStudio sends
  2893. `subtask_name = "Model_Name"` (bare) and `file = "Model_Name.gcode.3mf"`
  2894. (with extension). `_add_to_print_queue` looks up the stash under
  2895. `file_path.name` from the FTP receive side, which always has the
  2896. extension. If the stash uses `subtask_name`, lookup misses → every
  2897. captured slicer field (bed_leveling, flow_cali, vibration_cali,
  2898. layer_inspect, timelapse, nozzle_mapping) silently falls back to
  2899. settings defaults on every Bambu Studio "Send" upload.
  2900. `filename` (subtask_name) must still flow to `_schedule_finish_release`
  2901. untouched — push_status echoes it back as gcode_file / subtask_name and
  2902. the slicer matches against its own local subtask_name there. So
  2903. `on_print_command` keeps `filename` for state-feedback but derives the
  2904. stash key from `data["file"]`.
  2905. """
  2906. @pytest.fixture
  2907. def instance(self, tmp_path):
  2908. from backend.app.services.virtual_printer.manager import VirtualPrinterInstance
  2909. return VirtualPrinterInstance(
  2910. vp_id=99,
  2911. name="StashKeyTest",
  2912. mode="queue",
  2913. model="O1C2",
  2914. access_code="12345678",
  2915. serial_suffix="999999999",
  2916. base_dir=tmp_path,
  2917. )
  2918. @pytest.mark.asyncio
  2919. async def test_stash_key_uses_file_field_not_subtask_name(self, instance):
  2920. """BambuStudio's real wire shape: `subtask_name` ≠ `file`.
  2921. on_print_command must stash under `data["file"]` so the FTP-side
  2922. `_add_to_print_queue` lookup matches.
  2923. """
  2924. # mqtt_server.py:_handle_publish hands the bare subtask_name as
  2925. # `filename` and the full print_data body as `data`. The FTP filename
  2926. # lives in `data["file"]`.
  2927. await instance.on_print_command(
  2928. "Filament_Track_Switch_Holder", # subtask_name (bare)
  2929. {
  2930. "command": "project_file",
  2931. "subtask_name": "Filament_Track_Switch_Holder",
  2932. "file": "Filament_Track_Switch_Holder.gcode.3mf",
  2933. "nozzle_mapping": [16, -1, -1, 1],
  2934. },
  2935. )
  2936. # Stash MUST be under the FTP filename, not the bare subtask_name.
  2937. # `_add_to_print_queue` does `_slicer_print_options.pop(file_path.name, None)`
  2938. # where file_path.name == "Filament_Track_Switch_Holder.gcode.3mf".
  2939. assert "Filament_Track_Switch_Holder.gcode.3mf" in instance._slicer_print_options
  2940. assert "Filament_Track_Switch_Holder" not in instance._slicer_print_options
  2941. # Body must carry nozzle_mapping verbatim.
  2942. stashed = instance._slicer_print_options["Filament_Track_Switch_Holder.gcode.3mf"]
  2943. assert stashed["nozzle_mapping"] == [16, -1, -1, 1]
  2944. @pytest.mark.asyncio
  2945. async def test_stash_key_falls_back_to_filename_when_file_absent(self, instance):
  2946. """Defensive fallback: a slicer that omits the `file` field entirely
  2947. (legacy / non-3MF) must fall back to `filename` (subtask_name), not
  2948. leave the stash unkeyed."""
  2949. await instance.on_print_command(
  2950. "BareName",
  2951. {
  2952. "command": "project_file",
  2953. "subtask_name": "BareName",
  2954. # no "file" field
  2955. },
  2956. )
  2957. assert "BareName" in instance._slicer_print_options
  2958. @pytest.mark.asyncio
  2959. async def test_stash_key_signals_event_under_file_key(self, instance):
  2960. """`_add_to_print_queue` registers a wait-event under `file_path.name`
  2961. when the slicer's project_file arrives late. on_print_command must
  2962. signal THAT event (keyed by the FTP filename), not one keyed by
  2963. subtask_name — else the waiter times out even though the stash is
  2964. present and addressable."""
  2965. import asyncio
  2966. ftp_filename = "Filament_Track_Switch_Holder.gcode.3mf"
  2967. event = asyncio.Event()
  2968. instance._slicer_print_options_events[ftp_filename] = event
  2969. await instance.on_print_command(
  2970. "Filament_Track_Switch_Holder", # bare subtask_name
  2971. {
  2972. "command": "project_file",
  2973. "subtask_name": "Filament_Track_Switch_Holder",
  2974. "file": ftp_filename,
  2975. },
  2976. )
  2977. # Event keyed by FTP filename must fire even though on_print_command
  2978. # was called with the bare subtask_name.
  2979. assert event.is_set()