test_github_restore.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. """Unit tests for the Git backup restore service (#2656).
  2. Focus is on the per-category appliers: natural-key matching, the deliberate
  3. refusal to reuse the backup's primary keys, old_id -> new_id remapping for
  4. dependent rows, overwrite-vs-skip, the settings credential blocklist, and the
  5. K-profile paths that depend on live printers.
  6. """
  7. from datetime import datetime
  8. from types import SimpleNamespace
  9. from unittest.mock import AsyncMock, MagicMock, patch
  10. import pytest
  11. from sqlalchemy import select
  12. from backend.app.models.archive import PrintArchive
  13. from backend.app.models.settings import Settings
  14. from backend.app.models.spool import Spool
  15. from backend.app.models.spool_usage_history import SpoolUsageHistory
  16. from backend.app.schemas.github_backup import GitHubRestoreRequest, RestoreCategory
  17. from backend.app.services.github_restore import (
  18. ARCHIVES_PATH,
  19. SETTINGS_PATH,
  20. SPOOL_USAGE_PATH,
  21. SPOOLS_PATH,
  22. GitHubRestoreService,
  23. _CategoryTally,
  24. _is_blocked_setting_key,
  25. _parse_dt,
  26. )
  27. def _service() -> GitHubRestoreService:
  28. return GitHubRestoreService()
  29. class TestParseDt:
  30. def test_parses_str_datetime_the_backup_writes(self):
  31. assert _parse_dt("2026-07-27 06:02:05.123456") == datetime(2026, 7, 27, 6, 2, 5, 123456)
  32. def test_parses_iso_with_t_separator(self):
  33. assert _parse_dt("2026-07-27T06:02:05") == datetime(2026, 7, 27, 6, 2, 5)
  34. @pytest.mark.parametrize("value", ["", None, "not a date", 12345, {}])
  35. def test_returns_none_for_junk(self, value):
  36. assert _parse_dt(value) is None
  37. class TestSettingKeyBlocklist:
  38. @pytest.mark.parametrize(
  39. "key",
  40. [
  41. "bambu_cloud_token",
  42. "auth_secret_key",
  43. "ha_token",
  44. "prometheus_token",
  45. "printer_access_code",
  46. "smtp_password",
  47. "some_api_key",
  48. "ftp_passphrase",
  49. "MQTT_SECRET",
  50. ],
  51. )
  52. def test_credential_like_keys_are_blocked(self, key):
  53. assert _is_blocked_setting_key(key) is True
  54. @pytest.mark.parametrize(
  55. "key",
  56. ["low_stock_threshold", "currency", "theme", "local_backup_enabled", "timezone"],
  57. )
  58. def test_ordinary_keys_are_allowed(self, key):
  59. assert _is_blocked_setting_key(key) is False
  60. class TestCategoryTally:
  61. def test_notes_are_deduplicated(self):
  62. tally = _CategoryTally()
  63. tally.note("same")
  64. tally.note("same")
  65. assert tally.notes == ["same"]
  66. def test_notes_are_bounded(self):
  67. tally = _CategoryTally()
  68. for i in range(50):
  69. tally.note(f"note {i}")
  70. assert len(tally.notes) == 20
  71. class TestRestoreRequestSchema:
  72. def test_rejects_empty_category_list(self):
  73. with pytest.raises(ValueError):
  74. GitHubRestoreRequest(categories=[])
  75. def test_deduplicates_categories(self):
  76. request = GitHubRestoreRequest(
  77. categories=[RestoreCategory.SPOOLS, RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  78. )
  79. assert request.categories == [RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  80. def test_defaults_to_head(self):
  81. assert GitHubRestoreRequest(categories=[RestoreCategory.SPOOLS]).ref == "HEAD"
  82. @pytest.mark.parametrize("ref", ["HEAD", "abc1234", "a" * 40])
  83. def test_accepts_valid_refs(self, ref):
  84. assert GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS]).ref == ref
  85. @pytest.mark.parametrize("ref", ["abc", "main", "../etc/passwd", "a" * 41, "zzzzzzz", "abc 123"])
  86. def test_rejects_refs_that_are_not_object_names(self, ref):
  87. with pytest.raises(ValueError):
  88. GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS])
  89. class TestRestoreSettings:
  90. @pytest.mark.asyncio
  91. async def test_inserts_missing_keys(self, db_session):
  92. tally = _CategoryTally()
  93. payload = {"version": "1.0", "settings": {"currency": "EUR", "theme": "dark"}}
  94. await _service()._restore_settings(db_session, payload, overwrite=False, tally=tally)
  95. await db_session.commit()
  96. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  97. assert rows == {"currency": "EUR", "theme": "dark"}
  98. assert tally.restored == 2
  99. @pytest.mark.asyncio
  100. async def test_skips_existing_key_when_overwrite_off(self, db_session):
  101. db_session.add(Settings(key="currency", value="USD"))
  102. await db_session.commit()
  103. tally = _CategoryTally()
  104. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=False, tally=tally)
  105. await db_session.commit()
  106. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  107. assert row.value == "USD"
  108. assert tally.skipped == 1
  109. assert tally.restored == 0
  110. @pytest.mark.asyncio
  111. async def test_overwrites_existing_key_when_enabled(self, db_session):
  112. db_session.add(Settings(key="currency", value="USD"))
  113. await db_session.commit()
  114. tally = _CategoryTally()
  115. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=True, tally=tally)
  116. await db_session.commit()
  117. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  118. assert row.value == "EUR"
  119. assert tally.restored == 1
  120. @pytest.mark.asyncio
  121. async def test_credential_keys_are_never_restored(self, db_session):
  122. """A backup predating the collector's denylist can still contain secrets."""
  123. tally = _CategoryTally()
  124. payload = {"settings": {"currency": "EUR", "bambu_cloud_token": "leaked", "ha_token": "leaked"}}
  125. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  126. await db_session.commit()
  127. keys = {s.key for s in (await db_session.execute(select(Settings))).scalars().all()}
  128. assert keys == {"currency"}
  129. assert tally.skipped == 2
  130. assert any("credential-like" in note for note in tally.notes)
  131. @pytest.mark.asyncio
  132. async def test_missing_payload_is_noted_not_fatal(self, db_session):
  133. tally = _CategoryTally()
  134. await _service()._restore_settings(db_session, None, overwrite=True, tally=tally)
  135. assert tally.restored == 0
  136. assert tally.notes
  137. class TestRestoreSpools:
  138. def _spool_entry(self, **overrides):
  139. entry = {
  140. "id": 41,
  141. "material": "PLA",
  142. "subtype": "Basic",
  143. "color_name": "Jade White",
  144. "brand": "Bambu Lab",
  145. "tag_uid": "AABBCCDD",
  146. "created_at": "2026-01-05 12:00:00",
  147. "weight_used": 120.5,
  148. }
  149. entry.update(overrides)
  150. return entry
  151. @pytest.mark.asyncio
  152. async def test_inserts_without_reusing_backup_id(self, db_session):
  153. """The backup's spool.id belongs to an unrelated row today."""
  154. db_session.add(Spool(material="PETG")) # occupies id 1
  155. await db_session.commit()
  156. tally = _CategoryTally()
  157. payload = {"spools": [self._spool_entry(id=1)]}
  158. await _service()._restore_spools(db_session, payload, None, False, tally, {})
  159. await db_session.commit()
  160. spools = (await db_session.execute(select(Spool))).scalars().all()
  161. assert len(spools) == 2
  162. restored = next(s for s in spools if s.tag_uid == "AABBCCDD")
  163. assert restored.id != 1
  164. assert restored.material == "PLA"
  165. @pytest.mark.asyncio
  166. async def test_matches_existing_spool_by_tag_uid(self, db_session):
  167. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  168. await db_session.commit()
  169. tally = _CategoryTally()
  170. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, False, tally, {})
  171. await db_session.commit()
  172. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  173. assert tally.skipped == 1
  174. @pytest.mark.asyncio
  175. async def test_matches_existing_spool_by_tray_uuid(self, db_session):
  176. db_session.add(Spool(material="PLA", tray_uuid="1234" * 8))
  177. await db_session.commit()
  178. tally = _CategoryTally()
  179. entry = self._spool_entry(tag_uid=None, tray_uuid="1234" * 8)
  180. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  181. await db_session.commit()
  182. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  183. assert tally.skipped == 1
  184. @pytest.mark.asyncio
  185. async def test_matches_tagless_spool_by_descriptive_composite(self, db_session):
  186. """Manually added spools have no tag, so fall back to created_at + description."""
  187. db_session.add(
  188. Spool(
  189. material="PLA",
  190. subtype="Basic",
  191. color_name="Jade White",
  192. brand="Bambu Lab",
  193. created_at=datetime(2026, 1, 5, 12, 0, 0),
  194. )
  195. )
  196. await db_session.commit()
  197. tally = _CategoryTally()
  198. entry = self._spool_entry(tag_uid=None)
  199. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  200. await db_session.commit()
  201. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  202. assert tally.skipped == 1
  203. @pytest.mark.asyncio
  204. async def test_overwrite_updates_matched_spool(self, db_session):
  205. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old", weight_used=0))
  206. await db_session.commit()
  207. tally = _CategoryTally()
  208. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, True, tally, {})
  209. await db_session.commit()
  210. row = (await db_session.execute(select(Spool))).scalar_one()
  211. assert row.color_name == "Jade White"
  212. assert row.weight_used == 120.5
  213. assert tally.restored == 1
  214. @pytest.mark.asyncio
  215. async def test_insert_preserves_created_at_so_repeat_restore_is_idempotent(self, db_session):
  216. """Second restore of the same backup must match, not duplicate."""
  217. service = _service()
  218. payload = {"spools": [self._spool_entry(tag_uid=None)]}
  219. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  220. await db_session.commit()
  221. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  222. await db_session.commit()
  223. spools = (await db_session.execute(select(Spool))).scalars().all()
  224. assert len(spools) == 1
  225. assert spools[0].created_at == datetime(2026, 1, 5, 12, 0, 0)
  226. @pytest.mark.asyncio
  227. async def test_usage_history_spool_id_is_remapped(self, db_session):
  228. """Usage rows must point at the new local spool id, not the backup's."""
  229. tally = _CategoryTally()
  230. inventory = {"spools": [self._spool_entry(id=41)]}
  231. usage = {
  232. "usage_history": [
  233. {
  234. "id": 900,
  235. "spool_id": 41,
  236. "printer_id": None,
  237. "print_name": "benchy.3mf",
  238. "archive_id": None,
  239. "weight_used": 12.0,
  240. "percent_used": 5,
  241. "status": "completed",
  242. "created_at": "2026-02-01 09:00:00",
  243. }
  244. ]
  245. }
  246. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  247. await db_session.commit()
  248. spool = (await db_session.execute(select(Spool))).scalar_one()
  249. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  250. assert row.spool_id == spool.id
  251. assert row.print_name == "benchy.3mf"
  252. @pytest.mark.asyncio
  253. async def test_usage_history_archive_id_is_remapped(self, db_session):
  254. tally = _CategoryTally()
  255. inventory = {"spools": [self._spool_entry(id=41)]}
  256. usage = {
  257. "usage_history": [
  258. {
  259. "spool_id": 41,
  260. "archive_id": 77,
  261. "weight_used": 1.0,
  262. "created_at": "2026-02-01 09:00:00",
  263. }
  264. ]
  265. }
  266. archive = PrintArchive(filename="a.3mf", file_path="", file_size=1)
  267. db_session.add(archive)
  268. await db_session.flush()
  269. await _service()._restore_spools(db_session, inventory, usage, False, tally, {77: archive.id})
  270. await db_session.commit()
  271. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  272. assert row.archive_id == archive.id
  273. @pytest.mark.asyncio
  274. async def test_usage_row_with_unresolvable_spool_is_skipped_and_explained(self, db_session):
  275. tally = _CategoryTally()
  276. usage = {"usage_history": [{"spool_id": 999, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}]}
  277. await _service()._restore_spools(db_session, {"spools": []}, usage, False, tally, {})
  278. await db_session.commit()
  279. assert (await db_session.execute(select(SpoolUsageHistory))).scalars().first() is None
  280. assert tally.skipped == 1
  281. assert any("their spool is not in this backup's spool list" in note for note in tally.notes)
  282. # No remedy is offered, because none exists: overwrite does not change
  283. # which spools land in the map (a skipped spool is mapped anyway), and
  284. # usage history is always restored alongside the spools category.
  285. assert not any("overwrite" in note.lower() for note in tally.notes)
  286. @pytest.mark.asyncio
  287. async def test_usage_resolves_against_a_spool_skipped_because_overwrite_is_off(self, db_session):
  288. """A skipped spool is still mapped, so its usage rows are not "unresolved".
  289. This is why the note above offers no remedy: turning overwrite on would
  290. not rescue anything, and saying so misdescribed which records are lost.
  291. """
  292. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  293. await db_session.commit()
  294. tally = _CategoryTally()
  295. inventory = {"spools": [self._spool_entry(id=41)]}
  296. usage = {
  297. "usage_history": [
  298. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  299. ]
  300. }
  301. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  302. await db_session.commit()
  303. spool = (await db_session.execute(select(Spool))).scalar_one()
  304. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  305. assert row.spool_id == spool.id
  306. assert not any("spool list" in note for note in tally.notes)
  307. @pytest.mark.asyncio
  308. async def test_usage_history_is_not_duplicated_on_repeat_restore(self, db_session):
  309. service = _service()
  310. inventory = {"spools": [self._spool_entry(id=41)]}
  311. usage = {
  312. "usage_history": [
  313. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  314. ]
  315. }
  316. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  317. await db_session.commit()
  318. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  319. await db_session.commit()
  320. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  321. assert len(rows) == 1
  322. @pytest.mark.asyncio
  323. async def test_dangling_printer_id_is_cleared(self, db_session):
  324. tally = _CategoryTally()
  325. inventory = {"spools": [self._spool_entry(id=41)]}
  326. usage = {
  327. "usage_history": [
  328. {"spool_id": 41, "printer_id": 4242, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  329. ]
  330. }
  331. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  332. await db_session.commit()
  333. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  334. assert row.printer_id is None
  335. class TestRestoreArchives:
  336. def _archive_entry(self, **overrides):
  337. entry = {
  338. "id": 77,
  339. "filename": "benchy.3mf",
  340. "file_size": 2048,
  341. "content_hash": "abc123",
  342. "print_name": "Benchy",
  343. "status": "completed",
  344. "started_at": "2026-03-01 10:00:00",
  345. "completed_at": "2026-03-01 11:00:00",
  346. "created_at": "2026-03-01 10:00:00",
  347. "quantity": 1,
  348. "is_favorite": False,
  349. }
  350. entry.update(overrides)
  351. return entry
  352. @pytest.mark.asyncio
  353. async def test_inserts_metadata_only_row_with_empty_file_path(self, db_session):
  354. """print_archives.file_path is NOT NULL but is not in the backup."""
  355. tally = _CategoryTally()
  356. id_map: dict[int, int] = {}
  357. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, id_map)
  358. await db_session.commit()
  359. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  360. assert row.file_path == ""
  361. assert row.filename == "benchy.3mf"
  362. assert row.id != 77
  363. assert id_map == {77: row.id}
  364. assert any("metadata only" in note for note in tally.notes)
  365. @pytest.mark.asyncio
  366. async def test_matches_existing_archive_by_hash_and_start(self, db_session):
  367. db_session.add(
  368. PrintArchive(
  369. filename="benchy.3mf",
  370. file_path="/data/benchy.3mf",
  371. file_size=2048,
  372. content_hash="abc123",
  373. started_at=datetime(2026, 3, 1, 10, 0, 0),
  374. )
  375. )
  376. await db_session.commit()
  377. tally = _CategoryTally()
  378. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  379. await db_session.commit()
  380. rows = (await db_session.execute(select(PrintArchive))).scalars().all()
  381. assert len(rows) == 1
  382. assert rows[0].file_path == "/data/benchy.3mf"
  383. assert tally.skipped == 1
  384. @pytest.mark.asyncio
  385. async def test_falls_back_to_filename_and_start_without_hash(self, db_session):
  386. db_session.add(
  387. PrintArchive(
  388. filename="benchy.3mf",
  389. file_path="/data/benchy.3mf",
  390. file_size=2048,
  391. started_at=datetime(2026, 3, 1, 10, 0, 0),
  392. )
  393. )
  394. await db_session.commit()
  395. tally = _CategoryTally()
  396. entry = self._archive_entry(content_hash=None)
  397. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  398. await db_session.commit()
  399. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  400. assert tally.skipped == 1
  401. @pytest.mark.asyncio
  402. async def test_matches_archive_with_no_started_at_by_hash(self, db_session):
  403. """started_at is NULL for re-sliced archives, so it cannot be required.
  404. Gating both match branches on it meant these rows never matched: every
  405. restore re-inserted them and overwrite mode could never update them.
  406. """
  407. db_session.add(
  408. PrintArchive(
  409. filename="benchy.3mf",
  410. file_path="/data/benchy.3mf",
  411. file_size=2048,
  412. content_hash="abc123",
  413. started_at=None,
  414. )
  415. )
  416. await db_session.commit()
  417. tally = _CategoryTally()
  418. entry = self._archive_entry(started_at=None)
  419. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  420. await db_session.commit()
  421. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  422. assert tally.skipped == 1
  423. @pytest.mark.asyncio
  424. async def test_started_at_still_discriminates_when_present(self, db_session):
  425. """A NULL-tolerant match must not collapse rows that do differ."""
  426. db_session.add(
  427. PrintArchive(
  428. filename="benchy.3mf",
  429. file_path="/data/benchy.3mf",
  430. file_size=2048,
  431. content_hash="abc123",
  432. started_at=datetime(2026, 3, 1, 10, 0, 0),
  433. )
  434. )
  435. await db_session.commit()
  436. tally = _CategoryTally()
  437. # Same file, no start time recorded — a different row, not that one.
  438. entry = self._archive_entry(started_at=None)
  439. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  440. await db_session.commit()
  441. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 2
  442. assert tally.restored == 1
  443. @pytest.mark.asyncio
  444. async def test_soft_deleted_archive_is_not_restored_as_visible(self, db_session):
  445. """A backup keeps soft-deleted rows, so the flag has to survive.
  446. Their row is retained on purpose (stats keep counting the filament and
  447. energy), so without carrying deleted_at a restore turns an archive the
  448. user deleted back into a visible one.
  449. """
  450. tally = _CategoryTally()
  451. entry = self._archive_entry(deleted_at="2026-03-02 08:00:00")
  452. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  453. await db_session.commit()
  454. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  455. assert row.deleted_at == datetime(2026, 3, 2, 8, 0, 0)
  456. assert tally.restored == 1
  457. @pytest.mark.asyncio
  458. async def test_locally_deleted_archive_stays_deleted_without_overwrite(self, db_session):
  459. db_session.add(
  460. PrintArchive(
  461. filename="benchy.3mf",
  462. file_path="",
  463. file_size=2048,
  464. content_hash="abc123",
  465. started_at=datetime(2026, 3, 1, 10, 0, 0),
  466. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  467. )
  468. )
  469. await db_session.commit()
  470. tally = _CategoryTally()
  471. # The backup predates the deletion, so its copy is live.
  472. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  473. await db_session.commit()
  474. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  475. assert row.deleted_at == datetime(2026, 3, 5, 9, 0, 0)
  476. assert tally.skipped == 1
  477. @pytest.mark.asyncio
  478. async def test_overwrite_undeletes_a_locally_deleted_archive_and_says_so(self, db_session):
  479. db_session.add(
  480. PrintArchive(
  481. filename="benchy.3mf",
  482. file_path="",
  483. file_size=2048,
  484. content_hash="abc123",
  485. started_at=datetime(2026, 3, 1, 10, 0, 0),
  486. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  487. )
  488. )
  489. await db_session.commit()
  490. tally = _CategoryTally()
  491. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, True, tally, {})
  492. await db_session.commit()
  493. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  494. assert row.deleted_at is None
  495. assert tally.restored == 1
  496. assert any("visible again" in note for note in tally.notes)
  497. @pytest.mark.asyncio
  498. async def test_overwrite_updates_metadata_but_keeps_local_file_path(self, db_session):
  499. db_session.add(
  500. PrintArchive(
  501. filename="benchy.3mf",
  502. file_path="/data/benchy.3mf",
  503. file_size=2048,
  504. content_hash="abc123",
  505. started_at=datetime(2026, 3, 1, 10, 0, 0),
  506. notes="old",
  507. )
  508. )
  509. await db_session.commit()
  510. tally = _CategoryTally()
  511. entry = self._archive_entry(notes="restored note")
  512. await _service()._restore_archives(db_session, {"archives": [entry]}, True, tally, {})
  513. await db_session.commit()
  514. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  515. assert row.notes == "restored note"
  516. # The 3MF on disk must not be orphaned by a metadata restore.
  517. assert row.file_path == "/data/benchy.3mf"
  518. assert tally.restored == 1
  519. @pytest.mark.asyncio
  520. async def test_dangling_printer_and_project_links_are_cleared(self, db_session):
  521. tally = _CategoryTally()
  522. entry = self._archive_entry(printer_id=4242, project_id=4343)
  523. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  524. await db_session.commit()
  525. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  526. assert row.printer_id is None
  527. assert row.project_id is None
  528. assert any("no longer exist" in note for note in tally.notes)
  529. @pytest.mark.asyncio
  530. async def test_valid_printer_link_is_preserved(self, db_session, printer_factory):
  531. printer = await printer_factory()
  532. tally = _CategoryTally()
  533. entry = self._archive_entry(printer_id=printer.id)
  534. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  535. await db_session.commit()
  536. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  537. assert row.printer_id == printer.id
  538. @pytest.mark.asyncio
  539. async def test_non_dict_entry_counts_as_failed(self, db_session):
  540. tally = _CategoryTally()
  541. await _service()._restore_archives(db_session, {"archives": ["nonsense"]}, False, tally, {})
  542. assert tally.failed == 1
  543. class TestRestoreKprofiles:
  544. @staticmethod
  545. def _live(slot_id, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123"):
  546. """One profile as the printer currently reports it."""
  547. return SimpleNamespace(slot_id=slot_id, filament_id=filament_id, name=name, setting_id=setting_id)
  548. def _client(self, live=None, sent=True):
  549. client = MagicMock()
  550. client.state.connected = True
  551. client.set_kprofiles_batch = MagicMock(return_value=sent)
  552. client.get_kprofiles = AsyncMock(return_value=list(live or []))
  553. return client
  554. def _payload(self, serial="00M09A123456789", nozzle="0.4"):
  555. return {
  556. f"kprofiles/{serial}/{nozzle}.json": {
  557. "version": "1.0",
  558. "printer_serial": serial,
  559. "nozzle_diameter": nozzle,
  560. "profiles": [
  561. {
  562. "slot_id": 0,
  563. "name": "Bambu PLA",
  564. "k_value": "0.020000",
  565. "filament_id": "GFA00",
  566. "nozzle_id": "HS00-0.4",
  567. "extruder_id": 0,
  568. "setting_id": "PFUS123",
  569. }
  570. ],
  571. }
  572. }
  573. @pytest.mark.asyncio
  574. async def test_sends_batch_to_connected_printer(self, db_session, printer_factory):
  575. printer = await printer_factory(serial_number="00M09A123456789")
  576. client = MagicMock()
  577. client.state.connected = True
  578. client.set_kprofiles_batch = MagicMock(return_value=True)
  579. tally = _CategoryTally()
  580. with patch("backend.app.services.github_restore.printer_manager") as manager:
  581. manager.get_client = MagicMock(return_value=client)
  582. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  583. client.set_kprofiles_batch.assert_called_once()
  584. profiles, nozzle = client.set_kprofiles_batch.call_args.args
  585. assert nozzle == "0.4"
  586. assert profiles[0]["name"] == "Bambu PLA"
  587. assert profiles[0]["filament_id"] == "GFA00"
  588. assert tally.restored == 1
  589. assert manager.get_client.call_args.args == (printer.id,)
  590. @pytest.mark.asyncio
  591. async def test_always_warns_to_verify_on_the_printer(self, db_session, printer_factory):
  592. await printer_factory(serial_number="00M09A123456789")
  593. client = self._client()
  594. tally = _CategoryTally()
  595. with patch("backend.app.services.github_restore.printer_manager") as manager:
  596. manager.get_client = MagicMock(return_value=client)
  597. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  598. # The printer does answer extrusion_cali_set, but it reports "fail" on
  599. # writes that land, so the note must not promise either way.
  600. assert any("verify the profiles on the printer" in note for note in tally.notes)
  601. assert not any("without acknowledgement" in note for note in tally.notes)
  602. assert any("always overwrite" in note for note in tally.notes)
  603. # --- cali_idx is resolved live, never taken from the backup -------------
  604. #
  605. # Regression cover for the silent no-op found testing on an X1E: the backup
  606. # stored cali_idx 8151, a Bambuddy edit re-keyed the profile to 4606, and
  607. # the restore aimed extrusion_cali_set at 8151. The printer dropped it and
  608. # the tally still said "1 restored".
  609. @pytest.mark.asyncio
  610. async def test_uses_the_live_cali_idx_not_the_backed_up_slot(self, db_session, printer_factory):
  611. await printer_factory(serial_number="00M09A123456789")
  612. payload = self._payload()
  613. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]["slot_id"] = 8151
  614. client = self._client(live=[self._live(slot_id=4606)])
  615. tally = _CategoryTally()
  616. with patch("backend.app.services.github_restore.printer_manager") as manager:
  617. manager.get_client = MagicMock(return_value=client)
  618. await _service()._restore_kprofiles(db_session, payload, tally)
  619. client.get_kprofiles.assert_awaited_once_with(nozzle_diameter="0.4")
  620. profiles, _ = client.set_kprofiles_batch.call_args.args
  621. assert profiles[0]["cali_idx"] == 4606, "must address the slot that exists now"
  622. assert profiles[0]["cali_idx"] != 8151, "must not reuse the backup's cali_idx"
  623. assert tally.restored == 1
  624. @pytest.mark.asyncio
  625. async def test_matches_on_name_when_setting_id_was_regenerated(self, db_session, printer_factory):
  626. # A delete-then-add edit mints a fresh setting_id, so the name carries
  627. # the match instead.
  628. await printer_factory(serial_number="00M09A123456789")
  629. client = self._client(live=[self._live(slot_id=4606, setting_id="PF9999999999")])
  630. tally = _CategoryTally()
  631. with patch("backend.app.services.github_restore.printer_manager") as manager:
  632. manager.get_client = MagicMock(return_value=client)
  633. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  634. profiles, _ = client.set_kprofiles_batch.call_args.args
  635. assert profiles[0]["cali_idx"] == 4606
  636. # The live setting_id wins: it is what the printer associates with the slot.
  637. assert profiles[0]["setting_id"] == "PF9999999999"
  638. @pytest.mark.asyncio
  639. async def test_unmatched_profile_is_added_rather_than_aimed_at_a_dead_slot(self, db_session, printer_factory):
  640. await printer_factory(serial_number="00M09A123456789")
  641. client = self._client(live=[]) # printer has nothing for this nozzle
  642. tally = _CategoryTally()
  643. with patch("backend.app.services.github_restore.printer_manager") as manager:
  644. manager.get_client = MagicMock(return_value=client)
  645. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  646. profiles, _ = client.set_kprofiles_batch.call_args.args
  647. assert profiles[0]["cali_idx"] == -1, "-1 tells the printer to add a new profile"
  648. assert profiles[0]["setting_id"] == "PFUS123", "falls back to the backed-up preset"
  649. assert any("added as new profiles" in note for note in tally.notes)
  650. @pytest.mark.asyncio
  651. async def test_different_filament_is_not_treated_as_a_match(self, db_session, printer_factory):
  652. # Same slot, different filament — matching on slot alone would clobber
  653. # an unrelated profile.
  654. await printer_factory(serial_number="00M09A123456789")
  655. client = self._client(live=[self._live(slot_id=4606, filament_id="GFB99", name="Bambu PLA")])
  656. tally = _CategoryTally()
  657. with patch("backend.app.services.github_restore.printer_manager") as manager:
  658. manager.get_client = MagicMock(return_value=client)
  659. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  660. profiles, _ = client.set_kprofiles_batch.call_args.args
  661. assert profiles[0]["cali_idx"] == -1
  662. @pytest.mark.asyncio
  663. async def test_unreadable_live_index_degrades_to_adding(self, db_session, printer_factory):
  664. # A failed read must not abort the restore.
  665. await printer_factory(serial_number="00M09A123456789")
  666. client = self._client()
  667. client.get_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt timeout"))
  668. tally = _CategoryTally()
  669. with patch("backend.app.services.github_restore.printer_manager") as manager:
  670. manager.get_client = MagicMock(return_value=client)
  671. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  672. profiles, _ = client.set_kprofiles_batch.call_args.args
  673. assert profiles[0]["cali_idx"] == -1
  674. assert tally.restored == 1
  675. @pytest.mark.asyncio
  676. async def test_sole_profile_for_a_filament_matches_without_setting_id_or_name(self, db_session, printer_factory):
  677. await printer_factory(serial_number="00M09A123456789")
  678. payload = self._payload()
  679. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  680. entry["setting_id"] = None
  681. entry["name"] = ""
  682. client = self._client(live=[self._live(slot_id=4606, setting_id="PFOTHER", name="Renamed")])
  683. tally = _CategoryTally()
  684. with patch("backend.app.services.github_restore.printer_manager") as manager:
  685. manager.get_client = MagicMock(return_value=client)
  686. await _service()._restore_kprofiles(db_session, payload, tally)
  687. profiles, _ = client.set_kprofiles_batch.call_args.args
  688. assert profiles[0]["cali_idx"] == 4606
  689. @pytest.mark.asyncio
  690. async def test_ambiguous_filament_without_discriminator_is_added_not_guessed(self, db_session, printer_factory):
  691. await printer_factory(serial_number="00M09A123456789")
  692. payload = self._payload()
  693. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  694. entry["setting_id"] = None
  695. entry["name"] = ""
  696. client = self._client(live=[self._live(slot_id=1, setting_id="A"), self._live(slot_id=2, setting_id="B")])
  697. tally = _CategoryTally()
  698. with patch("backend.app.services.github_restore.printer_manager") as manager:
  699. manager.get_client = MagicMock(return_value=client)
  700. await _service()._restore_kprofiles(db_session, payload, tally)
  701. profiles, _ = client.set_kprofiles_batch.call_args.args
  702. assert profiles[0]["cali_idx"] == -1, "two candidates and nothing to tell them apart"
  703. @pytest.mark.asyncio
  704. async def test_unknown_serial_is_skipped_with_reason(self, db_session):
  705. tally = _CategoryTally()
  706. with patch("backend.app.services.github_restore.printer_manager"):
  707. await _service()._restore_kprofiles(db_session, self._payload(serial="NOSUCH"), tally)
  708. assert tally.restored == 0
  709. assert tally.skipped == 1
  710. assert any("No printer with serial NOSUCH" in note for note in tally.notes)
  711. @pytest.mark.asyncio
  712. async def test_offline_printer_is_skipped_not_failed(self, db_session, printer_factory):
  713. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  714. client = MagicMock()
  715. client.state.connected = False
  716. tally = _CategoryTally()
  717. with patch("backend.app.services.github_restore.printer_manager") as manager:
  718. manager.get_client = MagicMock(return_value=client)
  719. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  720. assert tally.skipped == 1
  721. assert tally.failed == 0
  722. assert any("not connected" in note for note in tally.notes)
  723. @pytest.mark.asyncio
  724. async def test_no_client_at_all_is_skipped(self, db_session, printer_factory):
  725. await printer_factory(serial_number="00M09A123456789")
  726. tally = _CategoryTally()
  727. with patch("backend.app.services.github_restore.printer_manager") as manager:
  728. manager.get_client = MagicMock(return_value=None)
  729. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  730. assert tally.skipped == 1
  731. @pytest.mark.asyncio
  732. async def test_publish_failure_counts_as_failed(self, db_session, printer_factory):
  733. await printer_factory(serial_number="00M09A123456789")
  734. client = MagicMock()
  735. client.state.connected = True
  736. client.set_kprofiles_batch = MagicMock(return_value=False)
  737. tally = _CategoryTally()
  738. with patch("backend.app.services.github_restore.printer_manager") as manager:
  739. manager.get_client = MagicMock(return_value=client)
  740. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  741. assert tally.failed == 1
  742. assert tally.restored == 0
  743. @pytest.mark.asyncio
  744. async def test_publish_exception_is_contained(self, db_session, printer_factory):
  745. await printer_factory(serial_number="00M09A123456789")
  746. client = MagicMock()
  747. client.state.connected = True
  748. client.set_kprofiles_batch = MagicMock(side_effect=RuntimeError("mqtt down"))
  749. tally = _CategoryTally()
  750. with patch("backend.app.services.github_restore.printer_manager") as manager:
  751. manager.get_client = MagicMock(return_value=client)
  752. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  753. assert tally.failed == 1
  754. @pytest.mark.asyncio
  755. async def test_each_nozzle_is_sent_separately(self, db_session, printer_factory):
  756. await printer_factory(serial_number="00M09A123456789")
  757. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  758. client = MagicMock()
  759. client.state.connected = True
  760. client.set_kprofiles_batch = MagicMock(return_value=True)
  761. tally = _CategoryTally()
  762. with patch("backend.app.services.github_restore.printer_manager") as manager:
  763. manager.get_client = MagicMock(return_value=client)
  764. await _service()._restore_kprofiles(db_session, payload, tally)
  765. assert client.set_kprofiles_batch.call_count == 2
  766. assert {c.args[1] for c in client.set_kprofiles_batch.call_args_list} == {"0.4", "0.8"}
  767. assert tally.restored == 2
  768. @pytest.mark.asyncio
  769. async def test_empty_payload_is_noted(self, db_session):
  770. tally = _CategoryTally()
  771. await _service()._restore_kprofiles(db_session, {}, tally)
  772. assert any("No K-profile data" in note for note in tally.notes)
  773. class TestSoftDeletedArchiveRoundTrip:
  774. """The two halves of the soft-delete fix only work together.
  775. The collector keeps soft-deleted rows on purpose (their stats still count),
  776. so if it doesn't write ``deleted_at`` there is nothing for the restore to
  777. carry across and a deleted archive comes back visible. Covered end to end
  778. because each half looks harmless on its own.
  779. """
  780. @pytest.mark.asyncio
  781. async def test_deleted_at_survives_collect_then_restore(self, db_session):
  782. from backend.app.services.github_backup import github_backup_service
  783. deleted_at = datetime(2026, 3, 5, 9, 0, 0)
  784. db_session.add(
  785. PrintArchive(
  786. filename="trashed.3mf",
  787. file_path="",
  788. file_size=1024,
  789. content_hash="hash-trashed",
  790. started_at=datetime(2026, 3, 1, 10, 0, 0),
  791. deleted_at=deleted_at,
  792. )
  793. )
  794. await db_session.commit()
  795. files: dict = {}
  796. await github_backup_service._collect_archives(db_session, files)
  797. payload = files[ARCHIVES_PATH]
  798. assert payload["archives"][0]["deleted_at"] == str(deleted_at)
  799. # Restore that payload into an instance where the row is gone entirely.
  800. await db_session.execute(PrintArchive.__table__.delete())
  801. await db_session.commit()
  802. tally = _CategoryTally()
  803. await _service()._restore_archives(db_session, payload, False, tally, {})
  804. await db_session.commit()
  805. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  806. assert row.deleted_at == deleted_at, "a deleted archive must not come back visible"
  807. class TestCategoryPathMapping:
  808. def setup_method(self):
  809. self.service = _service()
  810. self.available = [
  811. "backup_metadata.json",
  812. SETTINGS_PATH,
  813. SPOOLS_PATH,
  814. SPOOL_USAGE_PATH,
  815. ARCHIVES_PATH,
  816. "kprofiles/SERIAL1/0.4.json",
  817. "kprofiles/SERIAL1/0.8.json",
  818. "cloud_profiles/filament.json",
  819. ]
  820. def test_spools_includes_usage_history(self):
  821. paths = self.service._category_paths(RestoreCategory.SPOOLS, self.available)
  822. assert paths == [SPOOLS_PATH, SPOOL_USAGE_PATH]
  823. def test_kprofiles_globs_all_serials_and_nozzles(self):
  824. paths = self.service._category_paths(RestoreCategory.KPROFILES, self.available)
  825. assert paths == ["kprofiles/SERIAL1/0.4.json", "kprofiles/SERIAL1/0.8.json"]
  826. def test_absent_paths_are_omitted(self):
  827. paths = self.service._category_paths(RestoreCategory.SETTINGS, ["backup_metadata.json"])
  828. assert paths == []
  829. def test_cloud_profiles_are_not_a_restore_category(self):
  830. assert "cloud_profiles" not in {c.value for c in RestoreCategory}
  831. class TestMutex:
  832. @pytest.mark.asyncio
  833. async def test_restore_refuses_while_a_backup_is_running(self):
  834. service = _service()
  835. with patch("backend.app.services.github_backup.github_backup_service") as backup:
  836. backup.is_running = True
  837. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  838. assert result["success"] is False
  839. assert "backup is currently running" in result["message"]
  840. @pytest.mark.asyncio
  841. async def test_restore_refuses_while_another_restore_is_running(self):
  842. service = _service()
  843. service._running_restore = True
  844. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  845. assert result["success"] is False
  846. assert "restore is already running" in result["message"]
  847. @pytest.mark.asyncio
  848. async def test_backup_refuses_while_a_restore_is_running(self):
  849. from backend.app.services.github_backup import GitHubBackupService
  850. backup_service = GitHubBackupService()
  851. with patch("backend.app.services.github_restore.github_restore_service") as restore:
  852. restore.is_running = True
  853. result = await backup_service.run_backup(1, trigger="manual")
  854. assert result["success"] is False
  855. assert "restore is currently running" in result["message"]
  856. class TestResolveRef:
  857. @pytest.mark.asyncio
  858. async def test_concrete_sha_passes_through_without_an_api_call(self):
  859. service = _service()
  860. service.list_commits = AsyncMock()
  861. config = MagicMock(branch="main")
  862. resolved, error = await service._resolve_ref(config, "abc1234")
  863. assert resolved == "abc1234"
  864. assert error == ""
  865. service.list_commits.assert_not_awaited()
  866. @pytest.mark.asyncio
  867. async def test_head_resolves_to_the_tip_sha(self):
  868. service = _service()
  869. service.list_commits = AsyncMock(
  870. return_value={"success": True, "commits": [{"sha": "tipsha1"}, {"sha": "older"}]}
  871. )
  872. config = MagicMock(branch="main")
  873. resolved, error = await service._resolve_ref(config, "HEAD")
  874. assert resolved == "tipsha1"
  875. assert error == ""
  876. @pytest.mark.asyncio
  877. async def test_empty_history_is_an_error(self):
  878. service = _service()
  879. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  880. config = MagicMock(branch="main")
  881. resolved, error = await service._resolve_ref(config, "HEAD")
  882. assert resolved is None
  883. assert "no commits" in error