test_bambu_ftp.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. """Comprehensive FTP test suite for BambuFTPClient.
  2. Tests against a real mock implicit FTPS server, covering:
  3. - Connection (auth, SSL modes, timeout, caching)
  4. - File listing
  5. - Download (bytes, to_file, 0-byte regression)
  6. - Upload (chunked transfer, progress, error codes)
  7. - Delete
  8. - File size
  9. - Storage info (AVBL, directory scan, diagnose_storage)
  10. - Model-specific behavior (X1C prot_p, A1 prot_c fallback)
  11. - Async wrappers
  12. - Failure injection scenarios (regressions for 0.1.8 bugs)
  13. """
  14. import asyncio
  15. import logging
  16. import socket
  17. import threading
  18. import time
  19. from pathlib import Path
  20. import pytest
  21. from backend.app.services import bambu_ftp
  22. from backend.app.services.bambu_ftp import (
  23. BambuFTPClient,
  24. FileNotOnPrinterError,
  25. cache_3mf_download,
  26. clear_3mf_cache,
  27. delete_file_async,
  28. download_file_async,
  29. download_file_try_paths_async,
  30. get_cached_3mf,
  31. list_files_async,
  32. normalize_3mf_name,
  33. upload_file_async,
  34. with_ftp_retry,
  35. )
  36. # Brief delay to allow pyftpdlib to flush uploaded files to disk.
  37. # Needed because upload_file() skips voidresp() for all models,
  38. # so the server may still be processing the data channel close event.
  39. _UPLOAD_FLUSH_DELAY = 0.3
  40. # ---------------------------------------------------------------------------
  41. # TestConnection
  42. # ---------------------------------------------------------------------------
  43. class TestConnection:
  44. """Tests for FTP connect/disconnect behavior."""
  45. def test_connect_success(self, ftp_client_factory):
  46. """Successful implicit FTPS connection and login."""
  47. client = ftp_client_factory()
  48. assert client.connect() is True
  49. client.disconnect()
  50. def test_connect_wrong_access_code(self, ftp_client_factory):
  51. """Wrong access code returns False."""
  52. client = ftp_client_factory(access_code="wrongcode")
  53. assert client.connect() is False
  54. def test_connect_unreachable_host(self, ftp_server):
  55. """Unreachable host returns False."""
  56. client = BambuFTPClient(
  57. ip_address="192.0.2.1", # TEST-NET, guaranteed unreachable
  58. access_code="12345678",
  59. timeout=1.0,
  60. printer_model="X1C",
  61. )
  62. client.FTP_PORT = ftp_server.port
  63. assert client.connect() is False
  64. def test_connect_timeout(self, ftp_server):
  65. """Very short timeout triggers timeout error."""
  66. client = BambuFTPClient(
  67. ip_address="192.0.2.1",
  68. access_code="12345678",
  69. timeout=0.001, # Extremely short
  70. printer_model="X1C",
  71. )
  72. client.FTP_PORT = ftp_server.port
  73. assert client.connect() is False
  74. def test_disconnect_clean(self, ftp_client_factory):
  75. """Clean disconnect after successful connect."""
  76. client = ftp_client_factory()
  77. client.connect()
  78. client.disconnect()
  79. assert client._ftp is None
  80. def test_disconnect_without_connect(self, ftp_client_factory):
  81. """Disconnect without connect does not raise."""
  82. client = ftp_client_factory()
  83. client.disconnect() # Should not raise
  84. assert client._ftp is None
  85. def test_x1c_uses_prot_p(self, ftp_client_factory):
  86. """X1C model connects with prot_p (protected data channel)."""
  87. client = ftp_client_factory(printer_model="X1C")
  88. assert client.connect() is True
  89. assert client._should_use_prot_c() is False
  90. client.disconnect()
  91. def test_a1_defaults_prot_p(self, ftp_client_factory):
  92. """A1 model defaults to prot_p when no cache exists."""
  93. client = ftp_client_factory(printer_model="A1")
  94. assert client._should_use_prot_c() is False
  95. assert client.connect() is True
  96. client.disconnect()
  97. def test_a1_force_prot_c(self, ftp_client_factory):
  98. """A1 model with force_prot_c uses clear data channel."""
  99. client = ftp_client_factory(printer_model="A1", force_prot_c=True)
  100. assert client._should_use_prot_c() is True
  101. assert client.connect() is True
  102. client.disconnect()
  103. def test_cached_mode_respected(self, ftp_client_factory):
  104. """Cached mode is used on subsequent connections."""
  105. BambuFTPClient.cache_mode("127.0.0.1", "prot_c")
  106. client = ftp_client_factory(printer_model="A1")
  107. assert client._should_use_prot_c() is True
  108. assert client.connect() is True
  109. client.disconnect()
  110. # ---------------------------------------------------------------------------
  111. # TestDisconnectServerGone — isolated class because server.stop() calls
  112. # close_all() which nukes all asyncore sockets globally.
  113. # ---------------------------------------------------------------------------
  114. class TestDisconnectServerGone:
  115. """Test disconnect behavior when the server has stopped."""
  116. def test_disconnect_after_server_gone(self, ftp_certs, tmp_path):
  117. """Disconnect after server has stopped does not raise.
  118. disconnect() catches OSError, ftplib.Error, and EOFError so that
  119. best-effort cleanup never propagates exceptions to the caller.
  120. """
  121. from backend.tests.unit.services.mock_ftp_server import (
  122. MockBambuFTPServer,
  123. )
  124. from .conftest import _find_free_port
  125. cert_path, key_path = ftp_certs
  126. port = _find_free_port()
  127. server = MockBambuFTPServer("127.0.0.1", port, str(tmp_path), cert_path, key_path)
  128. server.start()
  129. client = BambuFTPClient("127.0.0.1", "12345678", timeout=5.0)
  130. client.FTP_PORT = port
  131. client.connect()
  132. server.stop()
  133. # Should not raise — disconnect() catches all connection errors
  134. client.disconnect()
  135. assert client._ftp is None
  136. # ---------------------------------------------------------------------------
  137. # TestListFiles
  138. # ---------------------------------------------------------------------------
  139. class TestListFiles:
  140. """Tests for directory listing."""
  141. def test_list_empty_directory(self, ftp_client_factory):
  142. """Listing an empty directory returns empty list."""
  143. client = ftp_client_factory()
  144. client.connect()
  145. files = client.list_files("/cache")
  146. assert files == []
  147. client.disconnect()
  148. def test_list_directory_with_files(self, ftp_client_factory, ftp_server):
  149. """Files in directory are listed correctly."""
  150. ftp_server.add_file("cache/test.3mf", b"x" * 1024)
  151. ftp_server.add_file("cache/test2.gcode", b"y" * 512)
  152. client = ftp_client_factory()
  153. client.connect()
  154. files = client.list_files("/cache")
  155. names = {f["name"] for f in files}
  156. assert "test.3mf" in names
  157. assert "test2.gcode" in names
  158. client.disconnect()
  159. def test_directories_marked(self, ftp_client_factory, ftp_server):
  160. """Subdirectories are identified with is_directory=True."""
  161. ftp_server.add_directory("model/subdir")
  162. client = ftp_client_factory()
  163. client.connect()
  164. files = client.list_files("/model")
  165. dirs = [f for f in files if f["is_directory"]]
  166. assert len(dirs) >= 1
  167. assert dirs[0]["name"] == "subdir"
  168. client.disconnect()
  169. def test_nonexistent_path_returns_empty(self, ftp_client_factory):
  170. """Listing a nonexistent path returns empty list."""
  171. client = ftp_client_factory()
  172. client.connect()
  173. files = client.list_files("/nonexistent/path")
  174. assert files == []
  175. client.disconnect()
  176. def test_file_sizes_and_paths(self, ftp_client_factory, ftp_server):
  177. """File sizes and full paths are parsed correctly."""
  178. ftp_server.add_file("cache/sized.bin", b"a" * 2048)
  179. client = ftp_client_factory()
  180. client.connect()
  181. files = client.list_files("/cache")
  182. sized = [f for f in files if f["name"] == "sized.bin"]
  183. assert len(sized) == 1
  184. assert sized[0]["size"] == 2048
  185. assert sized[0]["path"] == "/cache/sized.bin"
  186. client.disconnect()
  187. # ---------------------------------------------------------------------------
  188. # TestDownload
  189. # ---------------------------------------------------------------------------
  190. class TestDownload:
  191. """Tests for file download operations."""
  192. def test_download_file_returns_bytes(self, ftp_client_factory, ftp_server):
  193. """download_file() returns file content as bytes."""
  194. content = b"Hello FTP World!"
  195. ftp_server.add_file("cache/hello.txt", content)
  196. client = ftp_client_factory()
  197. client.connect()
  198. result = client.download_file("/cache/hello.txt")
  199. assert result == content
  200. client.disconnect()
  201. def test_download_file_missing(self, ftp_client_factory):
  202. """download_file() returns None for missing file."""
  203. client = ftp_client_factory()
  204. client.connect()
  205. result = client.download_file("/cache/does_not_exist.txt")
  206. assert result is None
  207. client.disconnect()
  208. def test_download_to_file_writes_to_disk(self, ftp_client_factory, ftp_server, tmp_path):
  209. """download_to_file() writes content to local filesystem."""
  210. content = b"Downloaded content"
  211. ftp_server.add_file("cache/dl.bin", content)
  212. local = tmp_path / "output" / "dl.bin"
  213. client = ftp_client_factory()
  214. client.connect()
  215. result = client.download_to_file("/cache/dl.bin", local)
  216. assert result is True
  217. assert local.read_bytes() == content
  218. client.disconnect()
  219. def test_download_to_file_creates_parent_dirs(self, ftp_client_factory, ftp_server, tmp_path):
  220. """download_to_file() creates parent directories automatically."""
  221. ftp_server.add_file("cache/nested.txt", b"nested content")
  222. local = tmp_path / "deep" / "nested" / "path" / "nested.txt"
  223. client = ftp_client_factory()
  224. client.connect()
  225. result = client.download_to_file("/cache/nested.txt", local)
  226. assert result is True
  227. assert local.exists()
  228. client.disconnect()
  229. def test_zero_byte_download_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  230. """0-byte download returns False and cleans up (regression test)."""
  231. ftp_server.add_file("cache/empty.bin", b"")
  232. local = tmp_path / "empty.bin"
  233. client = ftp_client_factory()
  234. client.connect()
  235. result = client.download_to_file("/cache/empty.bin", local)
  236. assert result is False
  237. assert not local.exists()
  238. client.disconnect()
  239. def test_download_to_file_missing_raises_not_on_printer(self, ftp_client_factory, tmp_path):
  240. """Missing file raises FileNotOnPrinterError so callers can short-circuit
  241. the retry loop — 550 means the file isn't there and retrying won't help."""
  242. from backend.app.services.bambu_ftp import FileNotOnPrinterError
  243. local = tmp_path / "missing.bin"
  244. client = ftp_client_factory()
  245. client.connect()
  246. try:
  247. with pytest.raises(FileNotOnPrinterError):
  248. client.download_to_file("/cache/no_such_file.bin", local)
  249. finally:
  250. client.disconnect()
  251. def test_download_large_file(self, ftp_client_factory, ftp_server):
  252. """Large file download (>1MB) works correctly."""
  253. large_content = b"X" * (1024 * 1024 + 500) # ~1MB + 500 bytes
  254. ftp_server.add_file("cache/large.bin", large_content)
  255. client = ftp_client_factory()
  256. client.connect()
  257. result = client.download_file("/cache/large.bin")
  258. assert result == large_content
  259. client.disconnect()
  260. def test_download_not_connected(self):
  261. """download_file() returns None when not connected."""
  262. client = BambuFTPClient("127.0.0.1", "12345678")
  263. assert client.download_file("/cache/test.bin") is None
  264. # ---------------------------------------------------------------------------
  265. # TestUpload
  266. # ---------------------------------------------------------------------------
  267. class TestUpload:
  268. """Tests for file upload operations."""
  269. def test_upload_success(self, ftp_client_factory, ftp_server, tmp_path):
  270. """Successful upload via transfercmd (not storbinary)."""
  271. content = b"Upload test content"
  272. local = tmp_path / "upload.3mf"
  273. local.write_bytes(content)
  274. client = ftp_client_factory()
  275. client.connect()
  276. result = client.upload_file(local, "/cache/upload.3mf")
  277. assert result is True
  278. client.disconnect()
  279. # Verify via fresh connection (upload_file skips voidresp() for all
  280. # models, so the original session can't be reused for download)
  281. time.sleep(_UPLOAD_FLUSH_DELAY)
  282. client2 = ftp_client_factory()
  283. client2.connect()
  284. downloaded = client2.download_file("/cache/upload.3mf")
  285. assert downloaded == content
  286. client2.disconnect()
  287. def test_upload_progress_callback(self, ftp_client_factory, ftp_server, tmp_path):
  288. """Progress callback receives updates during upload."""
  289. content = b"P" * 2048
  290. local = tmp_path / "progress.bin"
  291. local.write_bytes(content)
  292. progress_calls = []
  293. def on_progress(uploaded, total):
  294. progress_calls.append((uploaded, total))
  295. client = ftp_client_factory()
  296. client.connect()
  297. client.upload_file(local, "/cache/progress.bin", on_progress)
  298. assert len(progress_calls) >= 1
  299. # Last call should report full file uploaded
  300. assert progress_calls[-1][0] == len(content)
  301. assert progress_calls[-1][1] == len(content)
  302. client.disconnect()
  303. def test_upload_not_connected(self, tmp_path):
  304. """Upload when not connected returns False."""
  305. local = tmp_path / "test.bin"
  306. local.write_bytes(b"data")
  307. client = BambuFTPClient("127.0.0.1", "12345678")
  308. assert client.upload_file(local, "/cache/test.bin") is False
  309. def test_upload_553_no_sd_card(self, ftp_client_factory, ftp_server, tmp_path):
  310. """553 error (no SD card) returns False."""
  311. ftp_server.inject_failure("STOR", 553, "Could not create file.")
  312. local = tmp_path / "test.bin"
  313. local.write_bytes(b"data")
  314. client = ftp_client_factory()
  315. client.connect()
  316. result = client.upload_file(local, "/cache/test.bin")
  317. assert result is False
  318. client.disconnect()
  319. def test_upload_550_permission_denied(self, ftp_client_factory, ftp_server, tmp_path):
  320. """550 error (permission denied) returns False."""
  321. ftp_server.inject_failure("STOR", 550, "Permission denied.")
  322. local = tmp_path / "test.bin"
  323. local.write_bytes(b"data")
  324. client = ftp_client_factory()
  325. client.connect()
  326. result = client.upload_file(local, "/cache/test.bin")
  327. assert result is False
  328. client.disconnect()
  329. def test_upload_552_storage_full(self, ftp_client_factory, ftp_server, tmp_path):
  330. """552 error (storage full) returns False."""
  331. ftp_server.inject_failure("STOR", 552, "Storage quota exceeded.")
  332. local = tmp_path / "test.bin"
  333. local.write_bytes(b"data")
  334. client = ftp_client_factory()
  335. client.connect()
  336. result = client.upload_file(local, "/cache/test.bin")
  337. assert result is False
  338. client.disconnect()
  339. def test_upload_426_with_intact_file_proceeds(self, ftp_client_factory, ftp_server, tmp_path):
  340. """Some P2S firmware revisions return 426 on voidresp() even when the
  341. file landed fully (TLS data-channel close races the 226). #1417
  342. follow-up — verify via SIZE: when server size matches, proceed with
  343. a warning instead of failing the dispatch.
  344. Pre-#1417 the catch raised unconditionally and the reporter saw 11
  345. retries fail in a row even though every upload was actually
  346. succeeding on the printer side (v0.2.4.1 worked because the prior
  347. proceed-with-warning branch tolerated the noise).
  348. """
  349. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  350. local = tmp_path / "test.bin"
  351. local.write_bytes(b"data" * 256) # 1024 bytes
  352. client = ftp_client_factory()
  353. client.connect()
  354. def raise_426():
  355. raise ftplib.error_temp("426 Failure reading network stream.")
  356. def fake_size(_path):
  357. # Real P2S firmware: voidresp returns 426 but the file IS on
  358. # the SD card at its full size. Mock can't reproduce both
  359. # halves naturally because pyftpdlib only flushes on a clean
  360. # voidresp, so we inject SIZE explicitly to model the
  361. # printer-side state the user observes.
  362. return 1024
  363. client._ftp.voidresp = raise_426
  364. client._ftp.size = fake_size
  365. result = client.upload_file(local, "/cache/test.bin")
  366. assert result is True, "intact file (SIZE match) tolerates 426 noise"
  367. client.disconnect()
  368. def test_upload_426_with_truncated_file_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  369. """The original #1401 fix is preserved: when SIZE confirms the file
  370. isn't on the server at full size (or SIZE itself fails), the upload
  371. must fail so the dispatcher doesn't send a print command for a
  372. partial 3MF."""
  373. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  374. local = tmp_path / "test.bin"
  375. local.write_bytes(b"data" * 256)
  376. client = ftp_client_factory()
  377. client.connect()
  378. def raise_426():
  379. raise ftplib.error_temp("426 Failure reading network stream.")
  380. # Make SIZE report a smaller value — file is genuinely truncated.
  381. def fake_size(_path):
  382. return 100
  383. client._ftp.voidresp = raise_426
  384. client._ftp.size = fake_size
  385. result = client.upload_file(local, "/cache/test.bin")
  386. assert result is False, "truncated file (SIZE mismatch) must fail"
  387. client.disconnect()
  388. def test_upload_426_with_size_check_failing_returns_false(self, ftp_client_factory, ftp_server, tmp_path):
  389. """If SIZE itself fails (e.g. server too broken to answer), assume
  390. the worst and fail — better a retry than a print on a partial file.
  391. """
  392. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  393. local = tmp_path / "test.bin"
  394. local.write_bytes(b"data" * 256)
  395. client = ftp_client_factory()
  396. client.connect()
  397. def raise_426():
  398. raise ftplib.error_temp("426 Failure reading network stream.")
  399. def raise_size(_path):
  400. raise ftplib.error_perm("550 File not found.")
  401. client._ftp.voidresp = raise_426
  402. client._ftp.size = raise_size
  403. result = client.upload_file(local, "/cache/test.bin")
  404. assert result is False
  405. client.disconnect()
  406. def test_upload_bytes_426_with_intact_file_proceeds(self, ftp_client_factory, ftp_server):
  407. """upload_bytes() mirrors the same SIZE-verify logic as upload_file."""
  408. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  409. client = ftp_client_factory()
  410. client.connect()
  411. data = b"x" * 1024
  412. def raise_426():
  413. raise ftplib.error_temp("426 Failure reading network stream.")
  414. def fake_size(_path):
  415. return 1024 # printer-side file matches expected size
  416. client._ftp.voidresp = raise_426
  417. client._ftp.size = fake_size
  418. result = client.upload_bytes(data, "/cache/bytes.bin")
  419. assert result is True
  420. client.disconnect()
  421. def test_upload_bytes_426_with_truncated_file_returns_false(self, ftp_client_factory, ftp_server):
  422. """The truncated branch for upload_bytes()."""
  423. import ftplib # nosec B402 — tests need the real ftplib to construct mock 426 responses
  424. client = ftp_client_factory()
  425. client.connect()
  426. data = b"x" * 1024
  427. def raise_426():
  428. raise ftplib.error_temp("426 Failure reading network stream.")
  429. def fake_size(_path):
  430. return 100
  431. client._ftp.voidresp = raise_426
  432. client._ftp.size = fake_size
  433. result = client.upload_bytes(data, "/cache/bytes.bin")
  434. assert result is False
  435. client.disconnect()
  436. def test_upload_bytes_success(self, ftp_client_factory, ftp_server):
  437. """upload_bytes() writes data to server."""
  438. data = b"Bytes upload content"
  439. client = ftp_client_factory()
  440. client.connect()
  441. result = client.upload_bytes(data, "/cache/bytes.bin")
  442. assert result is True
  443. client.disconnect()
  444. # Verify via fresh connection
  445. time.sleep(_UPLOAD_FLUSH_DELAY)
  446. client2 = ftp_client_factory()
  447. client2.connect()
  448. downloaded = client2.download_file("/cache/bytes.bin")
  449. assert downloaded == data
  450. client2.disconnect()
  451. def test_upload_bytes_failure(self, ftp_client_factory, ftp_server):
  452. """upload_bytes() returns False on STOR failure."""
  453. ftp_server.inject_failure("STOR", 553, "No space.")
  454. client = ftp_client_factory()
  455. client.connect()
  456. result = client.upload_bytes(b"data", "/cache/fail.bin")
  457. assert result is False
  458. client.disconnect()
  459. def test_upload_large_chunked(self, ftp_client_factory, ftp_server, tmp_path):
  460. """Large file upload in chunks completes without error.
  461. Uses 2.5MB to trigger multiple chunks with 64KB CHUNK_SIZE.
  462. Content verification skipped because upload_file() skips
  463. voidresp() for all models, so the server may still be flushing
  464. when we check. The upload result=True confirms the client sent
  465. all chunks without error.
  466. """
  467. content = b"C" * (1024 * 1024 * 2 + 512 * 1024)
  468. local = tmp_path / "large.bin"
  469. local.write_bytes(content)
  470. progress_calls = []
  471. def on_progress(uploaded, total):
  472. progress_calls.append((uploaded, total))
  473. client = ftp_client_factory()
  474. client.connect()
  475. result = client.upload_file(local, "/cache/large.bin", on_progress)
  476. assert result is True
  477. # Verify many chunks were sent (2.5MB / 64KB = 40 chunks)
  478. assert len(progress_calls) >= 38
  479. assert progress_calls[-1][0] == len(content)
  480. client.disconnect()
  481. # ---------------------------------------------------------------------------
  482. # TestDelete
  483. # ---------------------------------------------------------------------------
  484. class TestDelete:
  485. """Tests for file deletion."""
  486. def test_delete_success(self, ftp_client_factory, ftp_server):
  487. """Successful file deletion."""
  488. from backend.app.services.bambu_ftp import DeleteResult
  489. ftp_server.add_file("cache/to_delete.bin", b"delete me")
  490. client = ftp_client_factory()
  491. client.connect()
  492. result = client.delete_file("/cache/to_delete.bin")
  493. assert result == DeleteResult.DELETED
  494. assert not ftp_server.file_exists("cache/to_delete.bin")
  495. client.disconnect()
  496. def test_delete_not_found(self, ftp_client_factory):
  497. """Deleting a nonexistent file returns NOT_FOUND (550, #1721)."""
  498. from backend.app.services.bambu_ftp import DeleteResult
  499. client = ftp_client_factory()
  500. client.connect()
  501. result = client.delete_file("/cache/no_such_file.bin")
  502. assert result == DeleteResult.NOT_FOUND
  503. client.disconnect()
  504. def test_delete_not_connected(self):
  505. """Delete when not connected returns FAILED."""
  506. from backend.app.services.bambu_ftp import DeleteResult
  507. client = BambuFTPClient("127.0.0.1", "12345678")
  508. assert client.delete_file("/cache/test.bin") == DeleteResult.FAILED
  509. # ---------------------------------------------------------------------------
  510. # TestFileSize
  511. # ---------------------------------------------------------------------------
  512. class TestFileSize:
  513. """Tests for get_file_size."""
  514. def test_file_size_correct(self, ftp_client_factory, ftp_server):
  515. """Returns correct file size."""
  516. ftp_server.add_file("cache/sized.bin", b"a" * 4096)
  517. client = ftp_client_factory()
  518. client.connect()
  519. size = client.get_file_size("/cache/sized.bin")
  520. assert size == 4096
  521. client.disconnect()
  522. def test_file_size_missing(self, ftp_client_factory):
  523. """Returns None for missing file."""
  524. client = ftp_client_factory()
  525. client.connect()
  526. size = client.get_file_size("/cache/no_file.bin")
  527. assert size is None
  528. client.disconnect()
  529. def test_file_size_not_connected(self):
  530. """Returns None when not connected."""
  531. client = BambuFTPClient("127.0.0.1", "12345678")
  532. assert client.get_file_size("/cache/test.bin") is None
  533. # ---------------------------------------------------------------------------
  534. # TestStorageInfo
  535. # ---------------------------------------------------------------------------
  536. class TestStorageInfo:
  537. """Tests for storage info and diagnostics."""
  538. def test_avbl_parsed(self, ftp_client_factory, ftp_server):
  539. """AVBL response is parsed for free_bytes."""
  540. ftp_server.set_avbl_bytes(5000000000)
  541. client = ftp_client_factory()
  542. client.connect()
  543. info = client.get_storage_info()
  544. assert info is not None
  545. assert info["free_bytes"] == 5000000000
  546. client.disconnect()
  547. def test_used_bytes_from_scan(self, ftp_client_factory, ftp_server):
  548. """used_bytes calculated from directory scan."""
  549. ftp_server.add_file("cache/file1.bin", b"a" * 1000)
  550. ftp_server.add_file("cache/file2.bin", b"b" * 2000)
  551. client = ftp_client_factory()
  552. client.connect()
  553. info = client.get_storage_info()
  554. assert info is not None
  555. assert info["used_bytes"] >= 3000 # At least these two files
  556. client.disconnect()
  557. def test_storage_info_not_connected(self):
  558. """Returns None when not connected."""
  559. client = BambuFTPClient("127.0.0.1", "12345678")
  560. assert client.get_storage_info() is None
  561. def test_diagnose_storage_success(self, ftp_client_factory, ftp_server):
  562. """diagnose_storage() returns connected=True with working diagnostics."""
  563. client = ftp_client_factory()
  564. client.connect()
  565. diag = client.diagnose_storage()
  566. assert diag["connected"] is True
  567. assert diag["can_list_root"] is True
  568. assert diag["can_list_cache"] is True
  569. assert diag["pwd"] is not None
  570. assert diag["storage_info"] is not None
  571. client.disconnect()
  572. def test_diagnose_storage_not_connected(self):
  573. """diagnose_storage() reports not connected."""
  574. client = BambuFTPClient("127.0.0.1", "12345678")
  575. diag = client.diagnose_storage()
  576. assert diag["connected"] is False
  577. assert "FTP not connected" in diag["errors"]
  578. # ---------------------------------------------------------------------------
  579. # TestModelSpecificBehavior
  580. # ---------------------------------------------------------------------------
  581. class TestModelSpecificBehavior:
  582. """Tests for printer model-specific FTP behavior."""
  583. def test_x1c_upload(self, ftp_client_factory, ftp_server, tmp_path):
  584. """X1C upload with session reuse succeeds."""
  585. content = b"X1C upload data"
  586. local = tmp_path / "x1c.3mf"
  587. local.write_bytes(content)
  588. client = ftp_client_factory(printer_model="X1C")
  589. client.connect()
  590. result = client.upload_file(local, "/cache/x1c.3mf")
  591. assert result is True
  592. client.disconnect()
  593. # Verify via fresh connection
  594. time.sleep(_UPLOAD_FLUSH_DELAY)
  595. client2 = ftp_client_factory(printer_model="X1C")
  596. client2.connect()
  597. downloaded = client2.download_file("/cache/x1c.3mf")
  598. assert downloaded == content
  599. client2.disconnect()
  600. def test_a1_upload_prot_c(self, ftp_client_factory, ftp_server, tmp_path):
  601. """A1 model upload with prot_c succeeds."""
  602. content = b"A1 upload data"
  603. local = tmp_path / "a1.3mf"
  604. local.write_bytes(content)
  605. client = ftp_client_factory(printer_model="A1", force_prot_c=True)
  606. client.connect()
  607. result = client.upload_file(local, "/cache/a1.3mf")
  608. assert result is True
  609. client.disconnect()
  610. # Verify via fresh connection
  611. time.sleep(_UPLOAD_FLUSH_DELAY)
  612. client2 = ftp_client_factory(printer_model="A1", force_prot_c=True)
  613. client2.connect()
  614. downloaded = client2.download_file("/cache/a1.3mf")
  615. assert downloaded == content
  616. client2.disconnect()
  617. def test_a1_mini_upload(self, ftp_client_factory, ftp_server, tmp_path):
  618. """A1 Mini model upload succeeds."""
  619. content = b"A1 Mini data"
  620. local = tmp_path / "a1mini.3mf"
  621. local.write_bytes(content)
  622. client = ftp_client_factory(printer_model="A1 Mini", force_prot_c=True)
  623. client.connect()
  624. result = client.upload_file(local, "/cache/a1mini.3mf")
  625. assert result is True
  626. client.disconnect()
  627. def test_p1s_upload(self, ftp_client_factory, ftp_server, tmp_path):
  628. """P1S model upload with session reuse succeeds."""
  629. content = b"P1S upload data"
  630. local = tmp_path / "p1s.3mf"
  631. local.write_bytes(content)
  632. client = ftp_client_factory(printer_model="P1S")
  633. client.connect()
  634. result = client.upload_file(local, "/cache/p1s.3mf")
  635. assert result is True
  636. client.disconnect()
  637. def test_unknown_model_defaults_prot_p(self, ftp_client_factory):
  638. """Unknown model defaults to prot_p."""
  639. client = ftp_client_factory(printer_model="FuturePrinter3000")
  640. assert client._is_a1_model() is False
  641. assert client._should_use_prot_c() is False
  642. assert client.connect() is True
  643. client.disconnect()
  644. def test_mode_cache_persists_and_clears(self, ftp_client_factory):
  645. """Mode cache works within a test and clears between tests."""
  646. # Cache should be empty at start (autouse fixture clears it)
  647. assert BambuFTPClient._mode_cache == {}
  648. # Connect and cache a mode
  649. BambuFTPClient.cache_mode("127.0.0.1", "prot_p")
  650. assert BambuFTPClient._mode_cache["127.0.0.1"] == "prot_p"
  651. # New client for same IP uses cached mode
  652. client = ftp_client_factory(printer_model="A1")
  653. assert client._get_cached_mode() == "prot_p"
  654. assert client._should_use_prot_c() is False
  655. client.disconnect()
  656. # ---------------------------------------------------------------------------
  657. # TestAsyncWrappers
  658. # ---------------------------------------------------------------------------
  659. class TestAsyncWrappers:
  660. """Tests for async wrapper functions using patch_ftp_port fixture."""
  661. @pytest.mark.asyncio
  662. async def test_upload_file_async_success(self, patch_ftp_port, tmp_path):
  663. """upload_file_async succeeds for X1C."""
  664. content = b"async upload"
  665. local = tmp_path / "async_up.3mf"
  666. local.write_bytes(content)
  667. result = await upload_file_async(
  668. "127.0.0.1",
  669. "12345678",
  670. local,
  671. "/cache/async_up.3mf",
  672. timeout=30.0,
  673. printer_model="X1C",
  674. )
  675. assert result is True
  676. @pytest.mark.asyncio
  677. async def test_upload_file_async_a1_fallback(self, patch_ftp_port, tmp_path):
  678. """upload_file_async tries prot_p then falls back to prot_c for A1."""
  679. content = b"a1 async upload"
  680. local = tmp_path / "a1_async.3mf"
  681. local.write_bytes(content)
  682. # For A1 models, if prot_p succeeds we get True.
  683. # If prot_p fails, it tries prot_c. Either way should succeed
  684. # against our mock server which accepts both.
  685. result = await upload_file_async(
  686. "127.0.0.1",
  687. "12345678",
  688. local,
  689. "/cache/a1_async.3mf",
  690. timeout=30.0,
  691. printer_model="A1",
  692. )
  693. assert result is True
  694. @pytest.mark.asyncio
  695. async def test_download_file_async_success(self, patch_ftp_port, tmp_path):
  696. """download_file_async succeeds."""
  697. server = patch_ftp_port
  698. content = b"async download content"
  699. server.add_file("cache/async_dl.bin", content)
  700. local = tmp_path / "async_dl.bin"
  701. result = await download_file_async(
  702. "127.0.0.1",
  703. "12345678",
  704. "/cache/async_dl.bin",
  705. local,
  706. timeout=30.0,
  707. printer_model="X1C",
  708. )
  709. assert result is True
  710. assert local.read_bytes() == content
  711. @pytest.mark.asyncio
  712. async def test_download_file_async_a1_fallback(self, patch_ftp_port, tmp_path):
  713. """download_file_async falls back for A1 models."""
  714. server = patch_ftp_port
  715. server.add_file("cache/a1_dl.bin", b"a1 data")
  716. local = tmp_path / "a1_dl.bin"
  717. result = await download_file_async(
  718. "127.0.0.1",
  719. "12345678",
  720. "/cache/a1_dl.bin",
  721. local,
  722. timeout=30.0,
  723. printer_model="A1",
  724. )
  725. assert result is True
  726. @pytest.mark.asyncio
  727. async def test_download_file_async_timeout_salvages_completed_zombie(self, tmp_path, monkeypatch):
  728. """Executor thread that completes after wait_for timeout is salvaged.
  729. asyncio.wait_for cannot cancel run_in_executor threads, so the FTP
  730. download may still complete after we give up waiting. If the thread
  731. genuinely finished (signalled via completion["success"] and the file
  732. is on disk), download_file_async should return True rather than False.
  733. Regression for #972: A1 user with 14 MB 3MF hit the hardcoded 60s
  734. timeout, but the download thread finished ~45s later. The successful
  735. file was written to disk but the async wrapper returned False, so the
  736. archive was created as a fallback with no 3MF data.
  737. """
  738. from backend.app.services import bambu_ftp
  739. # Clear mode cache so prot_p path is exercised.
  740. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  741. local = tmp_path / "zombie.bin"
  742. expected_content = b"late arrival but complete"
  743. class FakeClient:
  744. """Connects instantly, download_to_file sleeps past wait_for's
  745. timeout then writes the file and returns True."""
  746. def __init__(self, *args, **kwargs):
  747. pass
  748. def connect(self):
  749. return True
  750. def download_to_file(self, remote_path, local_path):
  751. time.sleep(0.4) # longer than wait_for timeout=0.1
  752. local_path.write_bytes(expected_content)
  753. return True
  754. def disconnect(self):
  755. pass
  756. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  757. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  758. monkeypatch.setattr(FakeClient, "A1_MODELS", {"A1"}, raising=False)
  759. def _noop_cache(ip, mode):
  760. pass
  761. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(_noop_cache), raising=False)
  762. result = await download_file_async(
  763. "127.0.0.1",
  764. "12345678",
  765. "/cache/zombie.bin",
  766. local,
  767. timeout=0.1,
  768. printer_model="X1C",
  769. )
  770. assert result is True
  771. assert local.read_bytes() == expected_content
  772. @pytest.mark.asyncio
  773. async def test_download_file_async_timeout_no_salvage_when_incomplete(self, tmp_path, monkeypatch):
  774. """Timeout returns False when thread has not signalled success.
  775. A partial file on disk (mid-retrbinary) must NOT be mistaken for a
  776. completed download — only the thread's explicit success flag permits
  777. salvage.
  778. """
  779. from backend.app.services import bambu_ftp
  780. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  781. local = tmp_path / "partial.bin"
  782. class FakeClient:
  783. def __init__(self, *args, **kwargs):
  784. pass
  785. def connect(self):
  786. return True
  787. def download_to_file(self, remote_path, local_path):
  788. # Simulate an in-progress partial write that never completes
  789. # within the salvage grace period.
  790. local_path.write_bytes(b"partial...")
  791. time.sleep(2.0)
  792. return True # would complete eventually, but too late
  793. def disconnect(self):
  794. pass
  795. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  796. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  797. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  798. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  799. result = await download_file_async(
  800. "127.0.0.1",
  801. "12345678",
  802. "/cache/partial.bin",
  803. local,
  804. timeout=0.1,
  805. printer_model="X1C",
  806. )
  807. assert result is False
  808. @pytest.mark.asyncio
  809. async def test_download_file_async_timeout_waits_for_slow_zombie(self, tmp_path, monkeypatch):
  810. """A zombie that completes within the 30s grace window is salvaged.
  811. Regression for #1014: on slow WiFi, download_to_file can overshoot the
  812. user's ftp_timeout by 10–30 s without being stuck. The old fixed 0.5 s
  813. post-timeout sleep was too short — it gave up and started attempt 2
  814. while attempt 1's zombie thread kept running, and by the time the zombie
  815. wrote the file to disk with a success flag, attempt 2 had already
  816. reported failure (its own completion dict was still False). The async
  817. wrapper now waits up to min(timeout, 30 s) for the worker thread to
  818. finish before returning, so a slow-but-progressing download salvages.
  819. """
  820. from backend.app.services import bambu_ftp
  821. bambu_ftp.BambuFTPClient._mode_cache.pop("127.0.0.1", None)
  822. local = tmp_path / "slow_zombie.bin"
  823. expected_content = b"finished during grace window"
  824. class FakeClient:
  825. """Mimics a slow FTP: wait_for gives up at 1.0 s but RETR takes
  826. 1.5 s total. Old 0.5 s fixed sleep would have bailed (0.5 < 0.5
  827. extra); new grace = max(min(1.0, 30), 0.5) = 1.0 s covers the
  828. remaining 0.5 s so salvage succeeds."""
  829. def __init__(self, *args, **kwargs):
  830. pass
  831. def connect(self):
  832. return True
  833. def download_to_file(self, remote_path, local_path):
  834. time.sleep(1.5) # wait_for times out at 1.0 s; zombie finishes 0.5 s later
  835. local_path.write_bytes(expected_content)
  836. return True
  837. def disconnect(self):
  838. pass
  839. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  840. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  841. monkeypatch.setattr(FakeClient, "A1_MODELS", set(), raising=False)
  842. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  843. result = await download_file_async(
  844. "127.0.0.1",
  845. "12345678",
  846. "/cache/slow_zombie.bin",
  847. local,
  848. timeout=1.0,
  849. printer_model="X1C",
  850. )
  851. assert result is True
  852. assert local.read_bytes() == expected_content
  853. @pytest.mark.asyncio
  854. async def test_download_file_try_paths_first_succeeds(self, patch_ftp_port, tmp_path):
  855. """download_file_try_paths_async succeeds on first path."""
  856. server = patch_ftp_port
  857. server.add_file("cache/try1.bin", b"first path")
  858. local = tmp_path / "try.bin"
  859. result = await download_file_try_paths_async(
  860. "127.0.0.1",
  861. "12345678",
  862. ["/cache/try1.bin", "/cache/try2.bin"],
  863. local,
  864. printer_model="X1C",
  865. )
  866. assert result is True
  867. assert local.read_bytes() == b"first path"
  868. @pytest.mark.asyncio
  869. async def test_download_file_try_paths_fallback(self, patch_ftp_port, tmp_path):
  870. """download_file_try_paths_async falls back to second path."""
  871. server = patch_ftp_port
  872. server.add_file("cache/second.bin", b"second path")
  873. local = tmp_path / "fallback.bin"
  874. result = await download_file_try_paths_async(
  875. "127.0.0.1",
  876. "12345678",
  877. ["/cache/missing.bin", "/cache/second.bin"],
  878. local,
  879. printer_model="X1C",
  880. )
  881. assert result is True
  882. assert local.read_bytes() == b"second path"
  883. @pytest.mark.asyncio
  884. async def test_list_files_async_success(self, patch_ftp_port):
  885. """list_files_async returns file list."""
  886. server = patch_ftp_port
  887. server.add_file("cache/listed.bin", b"data")
  888. result = await list_files_async(
  889. "127.0.0.1",
  890. "12345678",
  891. "/cache",
  892. timeout=30.0,
  893. printer_model="X1C",
  894. )
  895. names = {f["name"] for f in result}
  896. assert "listed.bin" in names
  897. @pytest.mark.asyncio
  898. async def test_delete_file_async_success(self, patch_ftp_port):
  899. """delete_file_async deletes a file."""
  900. from backend.app.services.bambu_ftp import DeleteResult
  901. server = patch_ftp_port
  902. server.add_file("cache/to_async_del.bin", b"delete me")
  903. result = await delete_file_async(
  904. "127.0.0.1",
  905. "12345678",
  906. "/cache/to_async_del.bin",
  907. printer_model="X1C",
  908. )
  909. assert result == DeleteResult.DELETED
  910. assert not server.file_exists("cache/to_async_del.bin")
  911. @pytest.mark.asyncio
  912. async def test_delete_file_async_not_found(self, patch_ftp_port):
  913. """delete_file_async distinguishes 550 from real failure (#1721)."""
  914. from backend.app.services.bambu_ftp import DeleteResult
  915. result = await delete_file_async(
  916. "127.0.0.1",
  917. "12345678",
  918. "/cache/never_existed.bin",
  919. printer_model="X1C",
  920. )
  921. assert result == DeleteResult.NOT_FOUND
  922. # ---------------------------------------------------------------------------
  923. # TestFailureScenarios
  924. # ---------------------------------------------------------------------------
  925. class TestFailureScenarios:
  926. """Regression tests for known FTP failure modes."""
  927. def test_550_caught_by_broad_except(self, ftp_client_factory, ftp_server, tmp_path):
  928. """550 error_perm is caught by (OSError, ftplib.Error) handler.
  929. Regression: error_perm is a subclass of ftplib.Error, so the
  930. broad except clause in upload_file catches it correctly.
  931. """
  932. ftp_server.inject_failure("STOR", 550, "Permission denied.")
  933. local = tmp_path / "test.bin"
  934. local.write_bytes(b"data")
  935. client = ftp_client_factory()
  936. client.connect()
  937. result = client.upload_file(local, "/cache/test.bin")
  938. assert result is False
  939. client.disconnect()
  940. def test_zero_byte_download_detected(self, ftp_client_factory, ftp_server, tmp_path):
  941. """0-byte download is detected and file is cleaned up.
  942. Regression: Prior to fix, 0-byte downloads were reported as success.
  943. """
  944. ftp_server.add_file("cache/zero.bin", b"")
  945. local = tmp_path / "zero.bin"
  946. client = ftp_client_factory()
  947. client.connect()
  948. result = client.download_to_file("/cache/zero.bin", local)
  949. assert result is False
  950. assert not local.exists()
  951. client.disconnect()
  952. def test_connection_refused_handled(self):
  953. """Connection refused is handled gracefully."""
  954. client = BambuFTPClient("127.0.0.1", "12345678", timeout=2.0)
  955. client.FTP_PORT = 1 # Almost certainly not listening
  956. assert client.connect() is False
  957. def test_auth_failure_530(self, ftp_client_factory, ftp_server):
  958. """530 authentication failure returns False."""
  959. ftp_server.inject_failure("PASS", 530, "Login incorrect.")
  960. client = ftp_client_factory()
  961. result = client.connect()
  962. assert result is False
  963. def test_retr_550_handled(self, ftp_client_factory, ftp_server):
  964. """RETR 550 (file not found) returns None."""
  965. ftp_server.inject_failure("RETR", 550, "File not found.")
  966. ftp_server.add_file("cache/exists.bin", b"data")
  967. client = ftp_client_factory()
  968. client.connect()
  969. result = client.download_file("/cache/exists.bin")
  970. assert result is None
  971. client.disconnect()
  972. def test_cwd_550_handled(self, ftp_client_factory, ftp_server):
  973. """CWD 550 is handled in list_files."""
  974. ftp_server.inject_failure("CWD", 550, "Directory not found.")
  975. client = ftp_client_factory()
  976. client.connect()
  977. result = client.list_files("/nonexistent")
  978. assert result == []
  979. client.disconnect()
  980. def test_stor_553_handled(self, ftp_client_factory, ftp_server, tmp_path):
  981. """STOR 553 (no SD card) handled gracefully."""
  982. ftp_server.inject_failure("STOR", 553, "Could not create file.")
  983. local = tmp_path / "test.bin"
  984. local.write_bytes(b"test")
  985. client = ftp_client_factory()
  986. client.connect()
  987. result = client.upload_file(local, "/cache/test.bin")
  988. assert result is False
  989. client.disconnect()
  990. def test_diagnose_storage_cwd_failure_doesnt_propagate(self, ftp_client_factory, ftp_server):
  991. """diagnose_storage CWD failure doesn't crash the whole operation.
  992. Regression: diagnose_storage() was called in the upload path and
  993. a CWD failure would propagate and crash the upload.
  994. """
  995. ftp_server.inject_failure("CWD", 550, "No such directory.", count=2)
  996. client = ftp_client_factory()
  997. client.connect()
  998. diag = client.diagnose_storage()
  999. # Should still return results (with errors noted)
  1000. assert diag["connected"] is True
  1001. assert len(diag["errors"]) > 0
  1002. client.disconnect()
  1003. def test_failure_injection_count_decrements(self, ftp_client_factory, ftp_server):
  1004. """Failure injection with count decrements and eventually succeeds."""
  1005. ftp_server.add_file("cache/retry.bin", b"data after retry")
  1006. ftp_server.inject_failure("RETR", 550, "Temporary error.", count=1)
  1007. client = ftp_client_factory()
  1008. client.connect()
  1009. # First attempt fails
  1010. result1 = client.download_file("/cache/retry.bin")
  1011. assert result1 is None
  1012. # Second attempt succeeds (failure count exhausted)
  1013. result2 = client.download_file("/cache/retry.bin")
  1014. assert result2 == b"data after retry"
  1015. client.disconnect()
  1016. def test_upload_skips_voidresp(self, ftp_client_factory, ftp_server, tmp_path):
  1017. """Upload returns True without calling voidresp() for any model.
  1018. voidresp() is skipped for all models: A1 printers hang on it,
  1019. H2D printers delay the 226 response by 30+ seconds, and X1C/P1S
  1020. gain nothing from waiting. The file is on the SD card once
  1021. sendall() returns.
  1022. """
  1023. content = b"voidresp test data"
  1024. local = tmp_path / "voidresp_test.3mf"
  1025. local.write_bytes(content)
  1026. for model in ("X1C", "A1", "H2D", None):
  1027. client = ftp_client_factory(printer_model=model)
  1028. client.connect()
  1029. result = client.upload_file(local, "/cache/voidresp_test.3mf")
  1030. assert result is True, f"Upload failed for model={model}"
  1031. client.disconnect()
  1032. # Verify the file is actually on the server
  1033. time.sleep(_UPLOAD_FLUSH_DELAY)
  1034. client2 = ftp_client_factory()
  1035. client2.connect()
  1036. downloaded = client2.download_file("/cache/voidresp_test.3mf")
  1037. assert downloaded == content, f"Content mismatch for model={model}"
  1038. client2.disconnect()
  1039. # ---------------------------------------------------------------------------
  1040. # Short-circuit retries on 550 (#972)
  1041. # ---------------------------------------------------------------------------
  1042. class TestFileNotOnPrinterShortCircuit:
  1043. """FileNotOnPrinterError must bypass the retry budget.
  1044. Before this fix, a 3MF path that wasn't on the printer (550) cost
  1045. `ftp_retry_count + 1` attempts × `ftp_retry_delay` seconds per candidate
  1046. path. With ftp_retry_count=10 and four candidate paths, that's ~22 min
  1047. of dead retries before the real path is tried. #972 in the wild showed
  1048. 48 min of retrying paths that didn't exist.
  1049. """
  1050. async def test_with_ftp_retry_propagates_file_not_on_printer_without_retrying(self):
  1051. """with_ftp_retry raises FileNotOnPrinterError on first attempt.
  1052. Verifies non_retry_exceptions short-circuits before the retry loop
  1053. has a chance to sleep and try again.
  1054. """
  1055. attempts = {"n": 0}
  1056. async def always_missing(*_args, **_kwargs):
  1057. attempts["n"] += 1
  1058. raise FileNotOnPrinterError("/cache/absent.3mf: 550")
  1059. with pytest.raises(FileNotOnPrinterError):
  1060. await with_ftp_retry(
  1061. always_missing,
  1062. max_retries=10,
  1063. retry_delay=0.01,
  1064. operation_name="test 550 short-circuit",
  1065. non_retry_exceptions=(FileNotOnPrinterError,),
  1066. )
  1067. assert attempts["n"] == 1, "550 must not trigger any retry"
  1068. async def test_with_ftp_retry_still_retries_transient_errors(self):
  1069. """Non-550 exceptions continue to retry up to max_retries + 1."""
  1070. attempts = {"n": 0}
  1071. async def flaky(*_args, **_kwargs):
  1072. attempts["n"] += 1
  1073. raise TimeoutError("transient")
  1074. result = await with_ftp_retry(
  1075. flaky,
  1076. max_retries=2,
  1077. retry_delay=0.01,
  1078. operation_name="test transient retries",
  1079. non_retry_exceptions=(FileNotOnPrinterError,),
  1080. )
  1081. assert result is None
  1082. assert attempts["n"] == 3, "Transient errors should retry to exhaustion"
  1083. def test_download_to_file_raises_on_missing_path(self, ftp_client_factory, tmp_path):
  1084. """download_to_file surfaces 550 as FileNotOnPrinterError end-to-end
  1085. against the real mock FTPS server, not just a hand-rolled mock."""
  1086. local = tmp_path / "never_downloaded.3mf"
  1087. client = ftp_client_factory()
  1088. client.connect()
  1089. try:
  1090. with pytest.raises(FileNotOnPrinterError):
  1091. client.download_to_file("/cache/does_not_exist.3mf", local)
  1092. finally:
  1093. client.disconnect()
  1094. assert not local.exists(), "Partial file must be cleaned up on 550"
  1095. # ---------------------------------------------------------------------------
  1096. # 3MF download cache (#972)
  1097. # ---------------------------------------------------------------------------
  1098. class TestThreeMFCache:
  1099. """Cover endpoint and archive flow share downloaded 3MF bytes via this
  1100. cache. Tests isolate themselves with clear_3mf_cache(delete_files=False)
  1101. so they don't clobber each other."""
  1102. def setup_method(self):
  1103. clear_3mf_cache(delete_files=False)
  1104. def teardown_method(self):
  1105. clear_3mf_cache(delete_files=False)
  1106. def test_normalize_collapses_filename_variants(self):
  1107. """Bambu names vary (.3mf, .gcode.3mf, with spaces) — they all map
  1108. to the same cache slot so both flows agree on the key."""
  1109. canonical = normalize_3mf_name("Broly_Legendary.gcode.3mf")
  1110. assert normalize_3mf_name("Broly_Legendary.3mf") == canonical
  1111. assert normalize_3mf_name("Broly_Legendary") == canonical
  1112. # Bambu Studio rewrites spaces to underscores on upload — treat as equal
  1113. assert normalize_3mf_name("Broly Legendary") == canonical
  1114. # Case is also collapsed so keys match across capitalizations
  1115. assert normalize_3mf_name("BROLY_LEGENDARY.3MF") == canonical
  1116. def test_cache_hit_returns_stored_path(self, tmp_path):
  1117. """get_cached_3mf returns the same Path that was put in."""
  1118. f = tmp_path / "Broly.gcode.3mf"
  1119. f.write_bytes(b"fake 3mf content")
  1120. cache_3mf_download(1, "Broly.gcode.3mf", f)
  1121. assert get_cached_3mf(1, "Broly.gcode.3mf") == f
  1122. def test_cache_lookup_uses_normalized_name(self, tmp_path):
  1123. """Caching under .gcode.3mf and querying with bare name still hits."""
  1124. f = tmp_path / "Broly.gcode.3mf"
  1125. f.write_bytes(b"x")
  1126. cache_3mf_download(1, "Broly.gcode.3mf", f)
  1127. assert get_cached_3mf(1, "Broly.3mf") == f
  1128. assert get_cached_3mf(1, "Broly") == f
  1129. def test_cache_miss_on_different_printer(self, tmp_path):
  1130. """Printer id is part of the key — two printers never collide."""
  1131. f = tmp_path / "A.3mf"
  1132. f.write_bytes(b"x")
  1133. cache_3mf_download(1, "A.3mf", f)
  1134. assert get_cached_3mf(2, "A.3mf") is None
  1135. def test_cache_evicts_when_file_deleted(self, tmp_path):
  1136. """Stale entry (file gone) returns None and is dropped from the dict."""
  1137. f = tmp_path / "A.3mf"
  1138. f.write_bytes(b"x")
  1139. cache_3mf_download(1, "A.3mf", f)
  1140. f.unlink()
  1141. assert get_cached_3mf(1, "A.3mf") is None
  1142. # Re-populating after eviction works — no ghost entries remain.
  1143. f.write_bytes(b"y")
  1144. cache_3mf_download(1, "A.3mf", f)
  1145. assert get_cached_3mf(1, "A.3mf") == f
  1146. def test_clear_by_printer_scoped(self, tmp_path, monkeypatch):
  1147. """Clearing one printer leaves the other untouched."""
  1148. from backend.app.core import config as _config
  1149. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path)
  1150. temp_dir = tmp_path / "temp"
  1151. temp_dir.mkdir()
  1152. f1 = temp_dir / "one.3mf"
  1153. f1.write_bytes(b"1")
  1154. f2 = temp_dir / "two.3mf"
  1155. f2.write_bytes(b"2")
  1156. cache_3mf_download(1, "one.3mf", f1)
  1157. cache_3mf_download(2, "two.3mf", f2)
  1158. clear_3mf_cache(1)
  1159. assert get_cached_3mf(1, "one.3mf") is None
  1160. assert get_cached_3mf(2, "two.3mf") == f2
  1161. # clear_3mf_cache defaulted to delete_files=True, so the temp file is gone
  1162. assert not f1.exists()
  1163. assert f2.exists()
  1164. def test_clear_without_deleting_files(self, tmp_path, monkeypatch):
  1165. """delete_files=False leaves files on disk — used by tests."""
  1166. from backend.app.core import config as _config
  1167. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path)
  1168. temp_dir = tmp_path / "temp"
  1169. temp_dir.mkdir()
  1170. f = temp_dir / "keep.3mf"
  1171. f.write_bytes(b"x")
  1172. cache_3mf_download(1, "keep.3mf", f)
  1173. clear_3mf_cache(1, delete_files=False)
  1174. assert get_cached_3mf(1, "keep.3mf") is None
  1175. assert f.exists()
  1176. def test_clear_does_not_delete_persistent_files(self, tmp_path, monkeypatch):
  1177. """Regression for #1212 / "file disappeared overnight" reports.
  1178. Dispatch sites added in #1166 cache the live archive copy and library
  1179. file bytes — paths outside ``archive_dir/temp`` — so /cover can skip
  1180. FTP. Those files are user data; the cache cleanup must never unlink
  1181. them. Pre-fix, ``clear_3mf_cache(printer_id, delete_files=True)`` ran
  1182. on every ``on_print_complete`` and silently destroyed them, leaving a
  1183. DB row whose ``file_path`` pointed at nothing — breaking Reprint and
  1184. View G-code with a 404.
  1185. """
  1186. from backend.app.core import config as _config
  1187. monkeypatch.setattr(_config.settings, "archive_dir", tmp_path / "archive")
  1188. (tmp_path / "archive" / "temp").mkdir(parents=True)
  1189. archive_file = tmp_path / "archive" / "1" / "20260504_wallhooks" / "wallhooks.gcode.3mf"
  1190. archive_file.parent.mkdir(parents=True)
  1191. archive_file.write_bytes(b"archive bytes")
  1192. library_file = tmp_path / "library_files" / "abcd.3mf"
  1193. library_file.parent.mkdir(parents=True)
  1194. library_file.write_bytes(b"library bytes")
  1195. temp_file = tmp_path / "archive" / "temp" / "cover_1_x.3mf"
  1196. temp_file.write_bytes(b"temp bytes")
  1197. cache_3mf_download(1, "wallhooks.gcode.3mf", archive_file)
  1198. cache_3mf_download(1, "library.3mf", library_file)
  1199. cache_3mf_download(1, "cover_1_x.3mf", temp_file)
  1200. clear_3mf_cache(1)
  1201. # All three cache entries are dropped from the dict.
  1202. assert get_cached_3mf(1, "wallhooks.gcode.3mf") is None
  1203. assert get_cached_3mf(1, "library.3mf") is None
  1204. assert get_cached_3mf(1, "cover_1_x.3mf") is None
  1205. # But only the temp file is unlinked — user data survives.
  1206. assert archive_file.exists(), "archive 3mf must not be deleted by cache cleanup"
  1207. assert library_file.exists(), "library 3mf must not be deleted by cache cleanup"
  1208. assert not temp_file.exists(), "temp file should still be cleaned up"
  1209. @pytest.fixture
  1210. def slow_upload_client(monkeypatch):
  1211. """Replace BambuFTPClient with a fake whose upload streams slowly.
  1212. Mirrors the real client's contract for the bits that matter here: it fires
  1213. the progress callback once per chunk and treats a callback exception as
  1214. "stop now" — break out of the send loop, drop the partial file, re-raise.
  1215. The returned dict lets a test see what the worker thread actually did,
  1216. which is the whole point: the #2529 ghost transfer was invisible from the
  1217. event loop's side.
  1218. """
  1219. state = {
  1220. "attempts": 0,
  1221. "concurrent": 0,
  1222. "max_concurrent": 0,
  1223. "completed": False,
  1224. "cancelled": False,
  1225. "deleted": [],
  1226. "chunks": 20,
  1227. "chunk_delay": 0.05,
  1228. }
  1229. lock = threading.Lock()
  1230. class FakeClient:
  1231. def __init__(self, *args, **kwargs):
  1232. pass
  1233. def connect(self):
  1234. return True
  1235. def upload_file(self, local_path, remote_path, progress_callback=None):
  1236. with lock:
  1237. state["attempts"] += 1
  1238. state["concurrent"] += 1
  1239. state["max_concurrent"] = max(state["max_concurrent"], state["concurrent"])
  1240. try:
  1241. total = state["chunks"]
  1242. for sent in range(1, total + 1):
  1243. time.sleep(state["chunk_delay"])
  1244. if progress_callback:
  1245. try:
  1246. progress_callback(sent, total)
  1247. except Exception:
  1248. state["cancelled"] = True
  1249. state["deleted"].append(remote_path)
  1250. raise
  1251. state["completed"] = True
  1252. return True
  1253. finally:
  1254. with lock:
  1255. state["concurrent"] -= 1
  1256. def disconnect(self):
  1257. pass
  1258. monkeypatch.setattr(bambu_ftp, "BambuFTPClient", FakeClient)
  1259. monkeypatch.setattr(FakeClient, "_mode_cache", {}, raising=False)
  1260. monkeypatch.setattr(FakeClient, "A1_MODELS", ("A1", "A1 Mini"), raising=False)
  1261. monkeypatch.setattr(FakeClient, "cache_mode", staticmethod(lambda ip, mode: None), raising=False)
  1262. return state
  1263. # ---------------------------------------------------------------------------
  1264. # TestUploadDeadline (#2529)
  1265. # ---------------------------------------------------------------------------
  1266. class TestUploadDeadline:
  1267. """The upload deadline must be size-aware, and must actually stop the transfer.
  1268. Regression for #2529: a 96 MB 3MF to an A1 over WiFi sustains ~75 KB/s and
  1269. needs ~20 minutes. The old flat 600 s wall-clock cap declared it dead at
  1270. ~70 MB, `asyncio.wait_for` cancelled the *future* but not the executor
  1271. thread — which kept streaming — and `with_ftp_retry` then started a second
  1272. STOR of the same file onto the same printer. The reporter's video shows two
  1273. transfers of the same job climbing in parallel (2% and 72%), and the print
  1274. never landed.
  1275. """
  1276. def test_deadline_scales_with_file_size(self, tmp_path):
  1277. """A big file gets proportionally longer, a small one gets the floor."""
  1278. small = tmp_path / "small.3mf"
  1279. small.write_bytes(b"x" * 1024)
  1280. assert bambu_ftp._upload_deadline(small) == bambu_ftp._UPLOAD_MIN_TIMEOUT
  1281. # The reporter's file. At the 25 KB/s floor rate, 96 MB is ~64 minutes —
  1282. # far above the 600 s that killed it at 72%.
  1283. big = tmp_path / "big.3mf"
  1284. big.write_bytes(b"x" * (96 * 1024 * 1024))
  1285. deadline = bambu_ftp._upload_deadline(big)
  1286. assert deadline > bambu_ftp._UPLOAD_MIN_TIMEOUT
  1287. assert deadline == pytest.approx((96 * 1024 * 1024) / bambu_ftp._UPLOAD_FLOOR_BYTES_PER_SEC)
  1288. def test_deadline_falls_back_to_floor_for_unstatable_file(self, tmp_path):
  1289. assert bambu_ftp._upload_deadline(tmp_path / "nope.3mf") == bambu_ftp._UPLOAD_MIN_TIMEOUT
  1290. @pytest.mark.asyncio
  1291. async def test_timeout_stops_the_worker_thread(self, tmp_path, monkeypatch, slow_upload_client):
  1292. """The transfer stops when the deadline expires, instead of streaming on.
  1293. Mutation check: drop the `cancel.set()` in upload_file_async and the
  1294. worker runs to completion, which is exactly the ghost transfer #2529
  1295. reported.
  1296. """
  1297. state = slow_upload_client
  1298. local = tmp_path / "slow.3mf"
  1299. local.write_bytes(b"x" * 4096)
  1300. with pytest.raises(bambu_ftp.UploadCancelled):
  1301. await upload_file_async("127.0.0.1", "12345678", local, "/cache/slow.3mf", timeout=0.2, printer_model="X1C")
  1302. # The worker noticed the cancel and unwound — it did not run to the end.
  1303. await asyncio.sleep(0.5)
  1304. assert state["cancelled"] is True
  1305. assert state["completed"] is False
  1306. # And it cleaned the partial file off the printer on its way out.
  1307. assert state["deleted"] == ["/cache/slow.3mf"]
  1308. @pytest.mark.asyncio
  1309. async def test_timeout_is_not_retried(self, tmp_path, monkeypatch, slow_upload_client):
  1310. """with_ftp_retry must not start a second transfer after a deadline expiry.
  1311. This is the bug the reporter filmed: attempt 2 began while attempt 1 was
  1312. still sending. One attempt, then a hard failure.
  1313. """
  1314. state = slow_upload_client
  1315. local = tmp_path / "slow.3mf"
  1316. local.write_bytes(b"x" * 4096)
  1317. with pytest.raises(bambu_ftp.UploadCancelled):
  1318. await with_ftp_retry(
  1319. upload_file_async,
  1320. "127.0.0.1",
  1321. "12345678",
  1322. local,
  1323. "/cache/slow.3mf",
  1324. timeout=0.2,
  1325. printer_model="X1C",
  1326. max_retries=3,
  1327. retry_delay=0,
  1328. )
  1329. assert state["attempts"] == 1, "a timed-out upload must not be retried"
  1330. @pytest.mark.asyncio
  1331. async def test_uploads_to_one_printer_are_serialized(self, tmp_path, monkeypatch, slow_upload_client):
  1332. """Two dispatches to the same printer queue up; they never overlap.
  1333. Concurrent STORs of the same remote path leave a corrupt file on the SD
  1334. card and make the printer look like it has a flaky network.
  1335. """
  1336. state = slow_upload_client
  1337. state["chunk_delay"] = 0.05
  1338. local = tmp_path / "slow.3mf"
  1339. local.write_bytes(b"x" * 4096)
  1340. async def _dispatch(name: str) -> bool:
  1341. return await upload_file_async(
  1342. "127.0.0.1", "12345678", local, f"/cache/{name}.3mf", timeout=30.0, printer_model="X1C"
  1343. )
  1344. results = await asyncio.gather(_dispatch("a"), _dispatch("b"))
  1345. assert results == [True, True]
  1346. assert state["attempts"] == 2
  1347. assert state["max_concurrent"] == 1, "two uploads ran against the same printer at once"
  1348. def test_progress_callback_raising_deletes_the_partial_file(self, ftp_client_factory, ftp_root, tmp_path):
  1349. """The cancel path in the real client removes what it already wrote.
  1350. This is the mechanism the deadline now hangs off, exercised end to end
  1351. against the mock FTPS server rather than a fake.
  1352. """
  1353. client = ftp_client_factory()
  1354. assert client.connect() is True
  1355. try:
  1356. local = tmp_path / "cancelme.3mf"
  1357. # Two chunks, so the callback fires while there is a partial file.
  1358. local.write_bytes(b"x" * (BambuFTPClient.CHUNK_SIZE * 2))
  1359. def _stop_after_first_chunk(uploaded: int, total: int) -> None:
  1360. raise bambu_ftp.UploadCancelled("stop")
  1361. with pytest.raises(bambu_ftp.UploadCancelled):
  1362. client.upload_file(local, "/cancelme.3mf", _stop_after_first_chunk)
  1363. finally:
  1364. client.disconnect()
  1365. time.sleep(_UPLOAD_FLUSH_DELAY)
  1366. assert not (Path(ftp_root) / "cancelme.3mf").exists(), "partial file left on the printer"
  1367. # ---------------------------------------------------------------------------
  1368. # TestHandshakeCoolOff
  1369. # ---------------------------------------------------------------------------
  1370. class _PlaintextServer:
  1371. """A socket that accepts on 990 and answers in plaintext, not TLS.
  1372. This is what #2780's printers do once their file service wedges: the TCP
  1373. connect succeeds, so a port probe reports the printer as healthy, and then
  1374. the implicit-FTPS handshake dies on ``WRONG_VERSION_NUMBER`` because the
  1375. first bytes back are an FTP banner rather than a TLS record.
  1376. """
  1377. def __init__(self):
  1378. self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1379. self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1380. self._sock.bind(("127.0.0.1", 0))
  1381. self._sock.listen(8)
  1382. self.port = self._sock.getsockname()[1]
  1383. self.accepts = 0
  1384. self._stop = threading.Event()
  1385. self._thread = threading.Thread(target=self._serve, daemon=True)
  1386. self._thread.start()
  1387. def _serve(self):
  1388. while not self._stop.is_set():
  1389. try:
  1390. conn, _addr = self._sock.accept()
  1391. except OSError:
  1392. return
  1393. self.accepts += 1
  1394. try:
  1395. conn.sendall(b"220 Welcome to the printer.\r\n")
  1396. except OSError:
  1397. pass
  1398. finally:
  1399. conn.close()
  1400. def stop(self):
  1401. self._stop.set()
  1402. self._sock.close()
  1403. self._thread.join(timeout=2)
  1404. @pytest.fixture()
  1405. def plaintext_server():
  1406. server = _PlaintextServer()
  1407. yield server
  1408. server.stop()
  1409. class TestHandshakeCoolOff:
  1410. """A wedged file service must be contacted once, not hundreds of times.
  1411. #2780: an X2D served clean FTPS for five days, flipped, and then failed
  1412. every handshake for eight more. Because each candidate path opened its own
  1413. connection, one reporter's log carried 3511 identical handshake failures.
  1414. """
  1415. def _client(self, server, ip="127.0.0.1"):
  1416. client = BambuFTPClient(ip, "12345678", timeout=5.0, printer_model="P2S")
  1417. client.FTP_PORT = server.port
  1418. return client
  1419. def test_plaintext_answer_on_990_blocks_the_printer(self, plaintext_server, caplog):
  1420. client = self._client(plaintext_server)
  1421. with caplog.at_level(logging.WARNING, logger="backend.app.services.bambu_ftp"):
  1422. assert client.connect() is False
  1423. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is True
  1424. messages = [r.getMessage() for r in caplog.records]
  1425. assert any("WRONG_VERSION_NUMBER" in m for m in messages)
  1426. # The warning has to say more than the error: the port is open, so
  1427. # "unblock port 990" is the wrong reading and the operator needs to
  1428. # know what it actually costs them.
  1429. assert any("covers and timelapses cannot be fetched" in m for m in messages)
  1430. # It must NOT prescribe a restart. It used to, and #2780's reporter
  1431. # power-cycled both affected printers with no effect while a single
  1432. # manual connection to the same printers completed a clean handshake.
  1433. # Naming a remedy that is known not to work is worse than naming none.
  1434. assert not any("restart" in m.lower() for m in messages)
  1435. def test_blocked_printer_is_not_contacted_again(self, plaintext_server):
  1436. self._client(plaintext_server).connect()
  1437. assert plaintext_server.accepts == 1
  1438. for _ in range(5):
  1439. assert self._client(plaintext_server).connect() is False
  1440. # Still one: the cool-off answered without opening a socket.
  1441. assert plaintext_server.accepts == 1
  1442. def test_cooloff_expiry_lets_the_printer_be_retried(self, plaintext_server, monkeypatch):
  1443. monkeypatch.setattr(bambu_ftp, "_HANDSHAKE_COOLOFF_SECONDS", 0.0)
  1444. self._client(plaintext_server).connect()
  1445. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is False
  1446. assert self._client(plaintext_server).connect() is False
  1447. assert plaintext_server.accepts == 2
  1448. def test_block_is_per_printer(self, plaintext_server):
  1449. self._client(plaintext_server).connect()
  1450. assert bambu_ftp.ftps_handshake_blocked("127.0.0.1") is True
  1451. # A second printer that never failed must stay reachable.
  1452. assert bambu_ftp.ftps_handshake_blocked("192.0.2.77") is False
  1453. def test_expired_block_lets_a_recovered_printer_straight_back_in(self, ftp_client_factory):
  1454. """A power-cycled printer is picked up on the next print, not held out.
  1455. The expired entry is also dropped, so the map holds one key per
  1456. currently-wedged printer rather than one per printer this process has
  1457. ever failed against.
  1458. """
  1459. BambuFTPClient._handshake_blocked_until["127.0.0.1"] = time.monotonic() - 1
  1460. client = ftp_client_factory()
  1461. assert client.connect() is True
  1462. client.disconnect()
  1463. assert BambuFTPClient._handshake_blocked_until == {}