test_virtual_printer.py 156 KB

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