test_bambu_ftp.py 64 KB

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