test_github_restore.py 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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. _COMPANION_CREDENTIAL_ENV,
  19. _COMPANION_CREDENTIALS,
  20. ARCHIVES_PATH,
  21. SETTINGS_PATH,
  22. SPOOL_USAGE_PATH,
  23. SPOOLS_PATH,
  24. GitHubRestoreService,
  25. _CategoryTally,
  26. _is_blocked_setting_key,
  27. _is_protected_setting_key,
  28. _is_usable_credential,
  29. _parse_dt,
  30. _setting_value_is_true,
  31. _SettingsPlan,
  32. )
  33. def _service() -> GitHubRestoreService:
  34. return GitHubRestoreService()
  35. class TestParseDt:
  36. def test_parses_str_datetime_the_backup_writes(self):
  37. assert _parse_dt("2026-07-27 06:02:05.123456") == datetime(2026, 7, 27, 6, 2, 5, 123456)
  38. def test_parses_iso_with_t_separator(self):
  39. assert _parse_dt("2026-07-27T06:02:05") == datetime(2026, 7, 27, 6, 2, 5)
  40. @pytest.mark.parametrize("value", ["", None, "not a date", 12345, {}])
  41. def test_returns_none_for_junk(self, value):
  42. assert _parse_dt(value) is None
  43. class TestSettingKeyBlocklist:
  44. @pytest.mark.parametrize(
  45. "key",
  46. [
  47. "bambu_cloud_token",
  48. "auth_secret_key",
  49. "ha_token",
  50. "prometheus_token",
  51. "printer_access_code",
  52. "smtp_password",
  53. "some_api_key",
  54. "ftp_passphrase",
  55. "MQTT_SECRET",
  56. ],
  57. )
  58. def test_credential_like_keys_are_blocked(self, key):
  59. assert _is_blocked_setting_key(key) is True
  60. @pytest.mark.parametrize(
  61. "key",
  62. ["low_stock_threshold", "currency", "theme", "local_backup_enabled", "timezone"],
  63. )
  64. def test_ordinary_keys_are_allowed(self, key):
  65. assert _is_blocked_setting_key(key) is False
  66. @pytest.mark.parametrize(
  67. "key",
  68. ["auth_enabled", "advanced_auth_enabled", "local_login_enabled", "setup_completed"],
  69. )
  70. def test_auth_policy_keys_are_protected(self, key):
  71. # Not credential-shaped, so the secret hints never catch them.
  72. assert _is_blocked_setting_key(key) is False
  73. assert _is_protected_setting_key(key) is True
  74. @pytest.mark.parametrize("key", ["currency", "ldap_enabled", "auth_secret_key"])
  75. def test_protected_set_is_only_the_auth_policy_keys(self, key):
  76. assert _is_protected_setting_key(key) is False
  77. class TestCategoryTally:
  78. def test_notes_are_deduplicated(self):
  79. tally = _CategoryTally()
  80. tally.note("same")
  81. tally.note("same")
  82. assert tally.notes == ["same"]
  83. def test_notes_are_bounded(self):
  84. tally = _CategoryTally()
  85. for i in range(50):
  86. tally.note(f"note {i}")
  87. assert len(tally.notes) == 20
  88. class TestRestoreRequestSchema:
  89. def test_rejects_empty_category_list(self):
  90. with pytest.raises(ValueError):
  91. GitHubRestoreRequest(categories=[])
  92. def test_deduplicates_categories(self):
  93. request = GitHubRestoreRequest(
  94. categories=[RestoreCategory.SPOOLS, RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  95. )
  96. assert request.categories == [RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  97. def test_defaults_to_head(self):
  98. assert GitHubRestoreRequest(categories=[RestoreCategory.SPOOLS]).ref == "HEAD"
  99. @pytest.mark.parametrize("ref", ["HEAD", "abc1234", "a" * 40])
  100. def test_accepts_valid_refs(self, ref):
  101. assert GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS]).ref == ref
  102. @pytest.mark.parametrize("ref", ["abc", "main", "../etc/passwd", "a" * 41, "zzzzzzz", "abc 123"])
  103. def test_rejects_refs_that_are_not_object_names(self, ref):
  104. with pytest.raises(ValueError):
  105. GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS])
  106. class TestRestoreSettings:
  107. @pytest.mark.asyncio
  108. async def test_inserts_missing_keys(self, db_session):
  109. tally = _CategoryTally()
  110. payload = {"version": "1.0", "settings": {"currency": "EUR", "theme": "dark"}}
  111. await _service()._restore_settings(db_session, payload, overwrite=False, tally=tally)
  112. await db_session.commit()
  113. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  114. assert rows == {"currency": "EUR", "theme": "dark"}
  115. assert tally.restored == 2
  116. @pytest.mark.asyncio
  117. async def test_skips_existing_key_when_overwrite_off(self, db_session):
  118. db_session.add(Settings(key="currency", value="USD"))
  119. await db_session.commit()
  120. tally = _CategoryTally()
  121. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=False, tally=tally)
  122. await db_session.commit()
  123. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  124. assert row.value == "USD"
  125. assert tally.skipped == 1
  126. assert tally.restored == 0
  127. @pytest.mark.asyncio
  128. async def test_overwrites_existing_key_when_enabled(self, db_session):
  129. db_session.add(Settings(key="currency", value="USD"))
  130. await db_session.commit()
  131. tally = _CategoryTally()
  132. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=True, tally=tally)
  133. await db_session.commit()
  134. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  135. assert row.value == "EUR"
  136. assert tally.restored == 1
  137. @pytest.mark.asyncio
  138. async def test_credential_keys_are_never_restored(self, db_session):
  139. """A backup predating the collector's denylist can still contain secrets."""
  140. tally = _CategoryTally()
  141. payload = {"settings": {"currency": "EUR", "bambu_cloud_token": "leaked", "ha_token": "leaked"}}
  142. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  143. await db_session.commit()
  144. keys = {s.key for s in (await db_session.execute(select(Settings))).scalars().all()}
  145. assert keys == {"currency"}
  146. # Refusals are notes, not tally rows: the preview never counted these
  147. # keys, so counting them here would put the total above what the user
  148. # was shown before they pressed Restore.
  149. assert tally.skipped == 0
  150. assert any("credential-like" in note for note in tally.notes)
  151. @pytest.mark.asyncio
  152. async def test_auth_settings_are_never_restored(self, db_session):
  153. """Restoring auth_enabled=false would disable auth behind the cache's back."""
  154. db_session.add(Settings(key="auth_enabled", value="true"))
  155. db_session.add(Settings(key="local_login_enabled", value="true"))
  156. await db_session.commit()
  157. tally = _CategoryTally()
  158. payload = {
  159. "settings": {
  160. "currency": "EUR",
  161. "auth_enabled": "false",
  162. "advanced_auth_enabled": "false",
  163. "local_login_enabled": "false",
  164. "setup_completed": "false",
  165. }
  166. }
  167. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  168. await db_session.commit()
  169. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  170. assert rows["auth_enabled"] == "true"
  171. assert rows["local_login_enabled"] == "true"
  172. assert "advanced_auth_enabled" not in rows
  173. assert "setup_completed" not in rows
  174. assert rows["currency"] == "EUR"
  175. assert tally.restored == 1
  176. # As above: refused keys are outside the preview's count, so outside the
  177. # tally too.
  178. assert tally.skipped == 0
  179. assert any("authentication setting" in note for note in tally.notes)
  180. @pytest.mark.asyncio
  181. async def test_missing_payload_is_noted_not_fatal(self, db_session):
  182. tally = _CategoryTally()
  183. await _service()._restore_settings(db_session, None, overwrite=True, tally=tally)
  184. assert tally.restored == 0
  185. assert tally.notes
  186. class TestSettingValueIsTrue:
  187. """Only the spellings a reader actually treats as "on" count as on."""
  188. @pytest.mark.parametrize("value", ["true", "TRUE", " True ", True])
  189. def test_on(self, value):
  190. assert _setting_value_is_true(value) is True
  191. @pytest.mark.parametrize("value", ["false", "1", "on", "yes", "", None, False, 0])
  192. def test_off(self, value):
  193. # "1"/"on"/"yes" are deliberately off: no reader in the codebase treats
  194. # them as on, so restoring one cannot switch anything on either.
  195. assert _setting_value_is_true(value) is False
  196. class TestUsableCredential:
  197. @pytest.mark.parametrize("value", ["s3cret", " x "])
  198. def test_present_values_are_usable(self, value):
  199. assert _is_usable_credential(value) is True
  200. @pytest.mark.parametrize("value", [None, "", " "])
  201. def test_absent_or_blank_is_not(self, value):
  202. # A present-but-blank prometheus_token row is exactly the `if token:`
  203. # hole in the metrics route, so it must not count as protection.
  204. assert _is_usable_credential(value) is False
  205. class TestCompanionCredentials:
  206. """Toggles whose safety depends on a credential the restore refuses to write.
  207. ``prometheus_enabled`` is the sharp one. ``/api/v1/metrics`` is a public
  208. route whose only gate is a non-empty ``prometheus_token``, so restoring the
  209. toggle onto an instance that has no token row publishes the entire metrics
  210. body to anyone who can reach the port — and with overwrite *off*, since the
  211. row is missing rather than present. The other four break an integration
  212. rather than open one, but they are the same shape.
  213. """
  214. async def _restore(self, db, tally=None, overwrite=False, **settings) -> _CategoryTally:
  215. tally = tally or _CategoryTally()
  216. await _service()._restore_settings(db, {"settings": settings}, overwrite=overwrite, tally=tally)
  217. await db.commit()
  218. return tally
  219. async def _rows(self, db) -> dict:
  220. return {s.key: s.value for s in (await db.execute(select(Settings))).scalars().all()}
  221. # --- The refusal itself ------------------------------------------------
  222. @pytest.mark.asyncio
  223. async def test_prometheus_toggle_is_refused_when_its_token_was_skipped(self, db_session):
  224. """The headline case: overwrite off, empty database, endpoint stays shut."""
  225. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  226. rows = await self._rows(db_session)
  227. assert rows == {"currency": "EUR"}
  228. assert any("prometheus_enabled" in note and "switched off" in note for note in tally.notes)
  229. @pytest.mark.asyncio
  230. @pytest.mark.parametrize("toggle,credential", sorted(_COMPANION_CREDENTIALS.items()))
  231. async def test_every_pair_refuses_its_toggle(self, db_session, toggle, credential, monkeypatch):
  232. monkeypatch.delenv("HA_TOKEN", raising=False)
  233. await self._restore(db_session, **{toggle: "true", credential: "s3cret"})
  234. assert toggle not in await self._rows(db_session)
  235. @pytest.mark.asyncio
  236. async def test_ha_toggle_is_refused_when_the_environment_has_no_token(self, db_session, monkeypatch):
  237. monkeypatch.delenv("HA_TOKEN", raising=False)
  238. await self._restore(db_session, ha_enabled="true", ha_token="s3cret", ha_url="http://ha.local")
  239. rows = await self._rows(db_session)
  240. assert "ha_enabled" not in rows
  241. assert rows["ha_url"] == "http://ha.local"
  242. @pytest.mark.asyncio
  243. async def test_a_blank_local_credential_row_is_not_usable(self, db_session):
  244. db_session.add(Settings(key="prometheus_token", value=""))
  245. await db_session.commit()
  246. await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  247. assert "prometheus_enabled" not in await self._rows(db_session)
  248. @pytest.mark.asyncio
  249. @pytest.mark.parametrize("value", ["TRUE", " True ", True])
  250. async def test_true_is_refused_however_it_is_spelled(self, db_session, value):
  251. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  252. assert "prometheus_enabled" not in await self._rows(db_session)
  253. # --- Ruling 3: the tally counts what the preview counted ---------------
  254. @pytest.mark.asyncio
  255. async def test_refusals_are_not_counted_in_the_tally(self, db_session):
  256. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  257. assert (tally.restored, tally.skipped, tally.failed) == (1, 0, 0)
  258. @pytest.mark.asyncio
  259. async def test_tally_total_equals_the_preview_item_count(self, db_session):
  260. """The ruling, encoded: the user is shown a number, and it has to hold.
  261. Off by three before this change — the two name-based refusals and the
  262. companion one were all counted as ``skipped`` despite never being in the
  263. preview's count.
  264. """
  265. db_session.add(Settings(key="theme", value="light"))
  266. await db_session.commit()
  267. values = {
  268. "currency": "EUR", # inserted -> restored
  269. "theme": "dark", # exists, overwrite off -> skipped
  270. "low_stock_threshold": None, # no value -> skipped
  271. "": "junk", # unusable key -> failed
  272. "bambu_cloud_token": "x", # blocked -> refused
  273. "auth_enabled": "false", # protected -> refused
  274. "prometheus_enabled": "true", # companion -> refused
  275. "prometheus_token": "s3cret", # blocked -> refused
  276. }
  277. item_count, _ = await _service()._count_items(
  278. db_session, RestoreCategory.SETTINGS, {SETTINGS_PATH: {"settings": values}}
  279. )
  280. tally = _CategoryTally()
  281. await _service()._restore_settings(db_session, {"settings": values}, overwrite=False, tally=tally)
  282. await db_session.commit()
  283. assert tally.restored + tally.skipped + tally.failed == item_count
  284. assert (tally.restored, tally.skipped, tally.failed) == (1, 2, 1)
  285. @pytest.mark.asyncio
  286. async def test_preview_count_drops_by_one_when_the_local_credential_is_missing(self, db_session):
  287. parsed = {
  288. SETTINGS_PATH: {"settings": {"currency": "EUR", "prometheus_enabled": "true", "prometheus_token": "s3cret"}}
  289. }
  290. refused_count, refused_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  291. db_session.add(Settings(key="prometheus_token", value="already-set"))
  292. await db_session.commit()
  293. allowed_count, allowed_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  294. assert refused_count == allowed_count - 1
  295. assert "switch(es)" in refused_detail
  296. assert "switch(es)" not in allowed_detail
  297. # --- Controls: over-refusal is the real risk here ----------------------
  298. @pytest.mark.asyncio
  299. async def test_a_usable_local_credential_lets_the_toggle_through(self, db_session):
  300. db_session.add(Settings(key="prometheus_token", value="already-set"))
  301. await db_session.commit()
  302. tally = await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  303. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  304. assert not any("switched off" in note for note in tally.notes)
  305. @pytest.mark.asyncio
  306. async def test_an_anonymous_broker_is_not_a_false_positive(self, db_session):
  307. """mqtt_relay passes an empty password straight through — a real config."""
  308. tally = await self._restore(db_session, mqtt_enabled="true", mqtt_broker="10.0.0.5")
  309. assert (await self._rows(db_session))["mqtt_enabled"] == "true"
  310. assert not any("switched off" in note for note in tally.notes)
  311. @pytest.mark.asyncio
  312. async def test_an_anonymous_ldap_bind_is_not_a_false_positive(self, db_session):
  313. """Same for a backup that carries the key with a blank value."""
  314. tally = await self._restore(db_session, ldap_enabled="true", ldap_bind_password=" ")
  315. assert (await self._rows(db_session))["ldap_enabled"] == "true"
  316. assert not any("switched off" in note for note in tally.notes)
  317. @pytest.mark.asyncio
  318. async def test_turning_a_toggle_off_is_always_written(self, db_session):
  319. await self._restore(db_session, prometheus_enabled="false", prometheus_token="s3cret")
  320. assert (await self._rows(db_session))["prometheus_enabled"] == "false"
  321. @pytest.mark.asyncio
  322. @pytest.mark.parametrize("value", ["1", "on", "yes"])
  323. async def test_spellings_no_reader_treats_as_on_are_written(self, db_session, value):
  324. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  325. assert (await self._rows(db_session))["prometheus_enabled"] == value
  326. @pytest.mark.asyncio
  327. async def test_ha_token_in_the_environment_counts_as_usable(self, db_session, monkeypatch):
  328. monkeypatch.setenv("HA_TOKEN", "from-env")
  329. await self._restore(db_session, ha_enabled="true", ha_token="s3cret")
  330. assert (await self._rows(db_session))["ha_enabled"] == "true"
  331. @pytest.mark.asyncio
  332. async def test_a_toggle_already_on_locally_is_written(self, db_session):
  333. """The exposure pre-dates the restore, so "left switched off" would be a lie."""
  334. db_session.add(Settings(key="prometheus_enabled", value="true"))
  335. await db_session.commit()
  336. tally = await self._restore(db_session, overwrite=True, prometheus_enabled="true", prometheus_token="s3cret")
  337. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  338. assert not any("switched off" in note for note in tally.notes)
  339. # --- The map itself ----------------------------------------------------
  340. def test_every_companion_credential_is_blocked_and_no_toggle_is(self):
  341. """Guards the rule against a future edit to _SECRET_KEY_HINTS.
  342. If a credential stopped being blocked, its toggle would travel with it
  343. and the refusal would be pointless; if a toggle started being blocked,
  344. the pair would never be reached at all.
  345. """
  346. for toggle, credential in _COMPANION_CREDENTIALS.items():
  347. assert _is_blocked_setting_key(credential) is True, credential
  348. assert _is_blocked_setting_key(toggle) is False, toggle
  349. assert _is_protected_setting_key(toggle) is False, toggle
  350. def test_every_environment_override_names_a_companion_credential(self):
  351. assert set(_COMPANION_CREDENTIAL_ENV) <= set(_COMPANION_CREDENTIALS.values())
  352. @pytest.mark.asyncio
  353. async def test_plan_leaves_unusable_key_names_in_no_bucket(self, db_session):
  354. """They are the restore's ``failed``, not a refusal."""
  355. plan = await _service()._plan_settings(db_session, {"": "x", 7: "y", "currency": "EUR"})
  356. assert plan == _SettingsPlan()
  357. class TestRestoreSpools:
  358. def _spool_entry(self, **overrides):
  359. entry = {
  360. "id": 41,
  361. "material": "PLA",
  362. "subtype": "Basic",
  363. "color_name": "Jade White",
  364. "brand": "Bambu Lab",
  365. "tag_uid": "AABBCCDD",
  366. "created_at": "2026-01-05 12:00:00",
  367. "weight_used": 120.5,
  368. }
  369. entry.update(overrides)
  370. return entry
  371. @pytest.mark.asyncio
  372. async def test_inserts_without_reusing_backup_id(self, db_session):
  373. """The backup's spool.id belongs to an unrelated row today."""
  374. db_session.add(Spool(material="PETG")) # occupies id 1
  375. await db_session.commit()
  376. tally = _CategoryTally()
  377. payload = {"spools": [self._spool_entry(id=1)]}
  378. await _service()._restore_spools(db_session, payload, None, False, tally, {})
  379. await db_session.commit()
  380. spools = (await db_session.execute(select(Spool))).scalars().all()
  381. assert len(spools) == 2
  382. restored = next(s for s in spools if s.tag_uid == "AABBCCDD")
  383. assert restored.id != 1
  384. assert restored.material == "PLA"
  385. @pytest.mark.asyncio
  386. async def test_matches_existing_spool_by_tag_uid(self, db_session):
  387. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  388. await db_session.commit()
  389. tally = _CategoryTally()
  390. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, False, tally, {})
  391. await db_session.commit()
  392. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  393. assert tally.skipped == 1
  394. @pytest.mark.asyncio
  395. async def test_matches_existing_spool_by_tray_uuid(self, db_session):
  396. db_session.add(Spool(material="PLA", tray_uuid="1234" * 8))
  397. await db_session.commit()
  398. tally = _CategoryTally()
  399. entry = self._spool_entry(tag_uid=None, tray_uuid="1234" * 8)
  400. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  401. await db_session.commit()
  402. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  403. assert tally.skipped == 1
  404. @pytest.mark.asyncio
  405. async def test_matches_tagless_spool_by_descriptive_composite(self, db_session):
  406. """Manually added spools have no tag, so fall back to created_at + description."""
  407. db_session.add(
  408. Spool(
  409. material="PLA",
  410. subtype="Basic",
  411. color_name="Jade White",
  412. brand="Bambu Lab",
  413. created_at=datetime(2026, 1, 5, 12, 0, 0),
  414. )
  415. )
  416. await db_session.commit()
  417. tally = _CategoryTally()
  418. entry = self._spool_entry(tag_uid=None)
  419. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  420. await db_session.commit()
  421. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  422. assert tally.skipped == 1
  423. @pytest.mark.asyncio
  424. async def test_overwrite_updates_matched_spool(self, db_session):
  425. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old", weight_used=0))
  426. await db_session.commit()
  427. tally = _CategoryTally()
  428. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, True, tally, {})
  429. await db_session.commit()
  430. row = (await db_session.execute(select(Spool))).scalar_one()
  431. assert row.color_name == "Jade White"
  432. assert row.weight_used == 120.5
  433. assert tally.restored == 1
  434. @pytest.mark.asyncio
  435. async def test_insert_preserves_created_at_so_repeat_restore_is_idempotent(self, db_session):
  436. """Second restore of the same backup must match, not duplicate."""
  437. service = _service()
  438. payload = {"spools": [self._spool_entry(tag_uid=None)]}
  439. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  440. await db_session.commit()
  441. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  442. await db_session.commit()
  443. spools = (await db_session.execute(select(Spool))).scalars().all()
  444. assert len(spools) == 1
  445. assert spools[0].created_at == datetime(2026, 1, 5, 12, 0, 0)
  446. @pytest.mark.asyncio
  447. async def test_usage_history_spool_id_is_remapped(self, db_session):
  448. """Usage rows must point at the new local spool id, not the backup's."""
  449. tally = _CategoryTally()
  450. inventory = {"spools": [self._spool_entry(id=41)]}
  451. usage = {
  452. "usage_history": [
  453. {
  454. "id": 900,
  455. "spool_id": 41,
  456. "printer_id": None,
  457. "print_name": "benchy.3mf",
  458. "archive_id": None,
  459. "weight_used": 12.0,
  460. "percent_used": 5,
  461. "status": "completed",
  462. "created_at": "2026-02-01 09:00:00",
  463. }
  464. ]
  465. }
  466. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  467. await db_session.commit()
  468. spool = (await db_session.execute(select(Spool))).scalar_one()
  469. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  470. assert row.spool_id == spool.id
  471. assert row.print_name == "benchy.3mf"
  472. @pytest.mark.asyncio
  473. async def test_usage_history_archive_id_is_remapped(self, db_session):
  474. tally = _CategoryTally()
  475. inventory = {"spools": [self._spool_entry(id=41)]}
  476. usage = {
  477. "usage_history": [
  478. {
  479. "spool_id": 41,
  480. "archive_id": 77,
  481. "weight_used": 1.0,
  482. "created_at": "2026-02-01 09:00:00",
  483. }
  484. ]
  485. }
  486. archive = PrintArchive(filename="a.3mf", file_path="", file_size=1)
  487. db_session.add(archive)
  488. await db_session.flush()
  489. await _service()._restore_spools(db_session, inventory, usage, False, tally, {77: archive.id})
  490. await db_session.commit()
  491. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  492. assert row.archive_id == archive.id
  493. @pytest.mark.asyncio
  494. async def test_usage_row_with_unresolvable_spool_is_skipped_and_explained(self, db_session):
  495. tally = _CategoryTally()
  496. usage = {"usage_history": [{"spool_id": 999, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}]}
  497. await _service()._restore_spools(db_session, {"spools": []}, usage, False, tally, {})
  498. await db_session.commit()
  499. assert (await db_session.execute(select(SpoolUsageHistory))).scalars().first() is None
  500. assert tally.skipped == 1
  501. assert any("their spool is not in this backup's spool list" in note for note in tally.notes)
  502. # No remedy is offered, because none exists: overwrite does not change
  503. # which spools land in the map (a skipped spool is mapped anyway), and
  504. # usage history is always restored alongside the spools category.
  505. assert not any("overwrite" in note.lower() for note in tally.notes)
  506. @pytest.mark.asyncio
  507. async def test_usage_resolves_against_a_spool_skipped_because_overwrite_is_off(self, db_session):
  508. """A skipped spool is still mapped, so its usage rows are not "unresolved".
  509. This is why the note above offers no remedy: turning overwrite on would
  510. not rescue anything, and saying so misdescribed which records are lost.
  511. """
  512. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  513. await db_session.commit()
  514. tally = _CategoryTally()
  515. inventory = {"spools": [self._spool_entry(id=41)]}
  516. usage = {
  517. "usage_history": [
  518. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  519. ]
  520. }
  521. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  522. await db_session.commit()
  523. spool = (await db_session.execute(select(Spool))).scalar_one()
  524. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  525. assert row.spool_id == spool.id
  526. assert not any("spool list" in note for note in tally.notes)
  527. @pytest.mark.asyncio
  528. async def test_usage_history_is_not_duplicated_on_repeat_restore(self, db_session):
  529. service = _service()
  530. inventory = {"spools": [self._spool_entry(id=41)]}
  531. usage = {
  532. "usage_history": [
  533. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  534. ]
  535. }
  536. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  537. await db_session.commit()
  538. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  539. await db_session.commit()
  540. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  541. assert len(rows) == 1
  542. @pytest.mark.asyncio
  543. async def test_dropped_archive_link_is_explained(self, db_session):
  544. """Spools without archives nulls every usage -> archive link, silently."""
  545. tally = _CategoryTally()
  546. inventory = {"spools": [self._spool_entry(id=41)]}
  547. usage = {
  548. "usage_history": [
  549. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"},
  550. {"spool_id": 41, "archive_id": 8, "weight_used": 2.0, "created_at": "2026-02-01 10:00:00"},
  551. {"spool_id": 41, "weight_used": 3.0, "created_at": "2026-02-01 11:00:00"},
  552. ]
  553. }
  554. # Empty archive_id_map: the archives category wasn't selected, so its
  555. # payload was never fetched and there is nothing to match against.
  556. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  557. await db_session.commit()
  558. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  559. assert len(rows) == 3
  560. assert all(row.archive_id is None for row in rows)
  561. # Only the two that had a link to lose are counted.
  562. assert any("2 usage record(s) restored without their print-history link" in n for n in tally.notes)
  563. assert any("select Print archives alongside" in n for n in tally.notes)
  564. @pytest.mark.asyncio
  565. async def test_no_note_when_every_archive_link_resolves(self, db_session):
  566. tally = _CategoryTally()
  567. inventory = {"spools": [self._spool_entry(id=41)]}
  568. usage = {
  569. "usage_history": [
  570. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  571. ]
  572. }
  573. archive = PrintArchive(filename="linked.3mf", file_path="", file_size=1)
  574. db_session.add(archive)
  575. await db_session.flush()
  576. await _service()._restore_spools(db_session, inventory, usage, False, tally, {7: archive.id})
  577. await db_session.commit()
  578. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  579. assert row.archive_id == archive.id
  580. assert not any("print-history link" in note for note in tally.notes)
  581. @pytest.mark.asyncio
  582. async def test_dangling_printer_id_is_cleared(self, db_session):
  583. tally = _CategoryTally()
  584. inventory = {"spools": [self._spool_entry(id=41)]}
  585. usage = {
  586. "usage_history": [
  587. {"spool_id": 41, "printer_id": 4242, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  588. ]
  589. }
  590. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  591. await db_session.commit()
  592. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  593. assert row.printer_id is None
  594. class TestRestoreArchives:
  595. def _archive_entry(self, **overrides):
  596. entry = {
  597. "id": 77,
  598. "filename": "benchy.3mf",
  599. "file_size": 2048,
  600. "content_hash": "abc123",
  601. "print_name": "Benchy",
  602. "status": "completed",
  603. "started_at": "2026-03-01 10:00:00",
  604. "completed_at": "2026-03-01 11:00:00",
  605. "created_at": "2026-03-01 10:00:00",
  606. "quantity": 1,
  607. "is_favorite": False,
  608. }
  609. entry.update(overrides)
  610. return entry
  611. @pytest.mark.asyncio
  612. async def test_inserts_metadata_only_row_with_empty_file_path(self, db_session):
  613. """print_archives.file_path is NOT NULL but is not in the backup."""
  614. tally = _CategoryTally()
  615. id_map: dict[int, int] = {}
  616. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, id_map)
  617. await db_session.commit()
  618. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  619. assert row.file_path == ""
  620. assert row.filename == "benchy.3mf"
  621. assert row.id != 77
  622. assert id_map == {77: row.id}
  623. assert any("metadata only" in note for note in tally.notes)
  624. @pytest.mark.asyncio
  625. async def test_matches_existing_archive_by_hash_and_start(self, db_session):
  626. db_session.add(
  627. PrintArchive(
  628. filename="benchy.3mf",
  629. file_path="/data/benchy.3mf",
  630. file_size=2048,
  631. content_hash="abc123",
  632. started_at=datetime(2026, 3, 1, 10, 0, 0),
  633. )
  634. )
  635. await db_session.commit()
  636. tally = _CategoryTally()
  637. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  638. await db_session.commit()
  639. rows = (await db_session.execute(select(PrintArchive))).scalars().all()
  640. assert len(rows) == 1
  641. assert rows[0].file_path == "/data/benchy.3mf"
  642. assert tally.skipped == 1
  643. @pytest.mark.asyncio
  644. async def test_falls_back_to_filename_and_start_without_hash(self, db_session):
  645. db_session.add(
  646. PrintArchive(
  647. filename="benchy.3mf",
  648. file_path="/data/benchy.3mf",
  649. file_size=2048,
  650. started_at=datetime(2026, 3, 1, 10, 0, 0),
  651. )
  652. )
  653. await db_session.commit()
  654. tally = _CategoryTally()
  655. entry = self._archive_entry(content_hash=None)
  656. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  657. await db_session.commit()
  658. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  659. assert tally.skipped == 1
  660. @pytest.mark.asyncio
  661. async def test_matches_archive_with_no_started_at_by_hash(self, db_session):
  662. """started_at is NULL for re-sliced archives, so it cannot be required.
  663. Gating both match branches on it meant these rows never matched: every
  664. restore re-inserted them and overwrite mode could never update them.
  665. """
  666. db_session.add(
  667. PrintArchive(
  668. filename="benchy.3mf",
  669. file_path="/data/benchy.3mf",
  670. file_size=2048,
  671. content_hash="abc123",
  672. started_at=None,
  673. )
  674. )
  675. await db_session.commit()
  676. tally = _CategoryTally()
  677. entry = self._archive_entry(started_at=None)
  678. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  679. await db_session.commit()
  680. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  681. assert tally.skipped == 1
  682. @pytest.mark.asyncio
  683. async def test_started_at_still_discriminates_when_present(self, db_session):
  684. """A NULL-tolerant match must not collapse rows that do differ."""
  685. db_session.add(
  686. PrintArchive(
  687. filename="benchy.3mf",
  688. file_path="/data/benchy.3mf",
  689. file_size=2048,
  690. content_hash="abc123",
  691. started_at=datetime(2026, 3, 1, 10, 0, 0),
  692. )
  693. )
  694. await db_session.commit()
  695. tally = _CategoryTally()
  696. # Same file, no start time recorded — a different row, not that one.
  697. entry = self._archive_entry(started_at=None)
  698. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  699. await db_session.commit()
  700. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 2
  701. assert tally.restored == 1
  702. @pytest.mark.asyncio
  703. async def test_soft_deleted_archive_is_not_restored_as_visible(self, db_session):
  704. """A backup keeps soft-deleted rows, so the flag has to survive.
  705. Their row is retained on purpose (stats keep counting the filament and
  706. energy), so without carrying deleted_at a restore turns an archive the
  707. user deleted back into a visible one.
  708. """
  709. tally = _CategoryTally()
  710. entry = self._archive_entry(deleted_at="2026-03-02 08:00:00")
  711. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  712. await db_session.commit()
  713. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  714. assert row.deleted_at == datetime(2026, 3, 2, 8, 0, 0)
  715. assert tally.restored == 1
  716. @pytest.mark.asyncio
  717. async def test_locally_deleted_archive_stays_deleted_without_overwrite(self, db_session):
  718. db_session.add(
  719. PrintArchive(
  720. filename="benchy.3mf",
  721. file_path="",
  722. file_size=2048,
  723. content_hash="abc123",
  724. started_at=datetime(2026, 3, 1, 10, 0, 0),
  725. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  726. )
  727. )
  728. await db_session.commit()
  729. tally = _CategoryTally()
  730. # The backup predates the deletion, so its copy is live.
  731. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  732. await db_session.commit()
  733. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  734. assert row.deleted_at == datetime(2026, 3, 5, 9, 0, 0)
  735. assert tally.skipped == 1
  736. @pytest.mark.asyncio
  737. async def test_overwrite_undeletes_a_locally_deleted_archive_and_says_so(self, db_session):
  738. db_session.add(
  739. PrintArchive(
  740. filename="benchy.3mf",
  741. file_path="",
  742. file_size=2048,
  743. content_hash="abc123",
  744. started_at=datetime(2026, 3, 1, 10, 0, 0),
  745. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  746. )
  747. )
  748. await db_session.commit()
  749. tally = _CategoryTally()
  750. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, True, tally, {})
  751. await db_session.commit()
  752. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  753. assert row.deleted_at is None
  754. assert tally.restored == 1
  755. assert any("visible again" in note for note in tally.notes)
  756. @pytest.mark.asyncio
  757. async def test_overwrite_updates_metadata_but_keeps_local_file_path(self, db_session):
  758. db_session.add(
  759. PrintArchive(
  760. filename="benchy.3mf",
  761. file_path="/data/benchy.3mf",
  762. file_size=2048,
  763. content_hash="abc123",
  764. started_at=datetime(2026, 3, 1, 10, 0, 0),
  765. notes="old",
  766. )
  767. )
  768. await db_session.commit()
  769. tally = _CategoryTally()
  770. entry = self._archive_entry(notes="restored note")
  771. await _service()._restore_archives(db_session, {"archives": [entry]}, True, tally, {})
  772. await db_session.commit()
  773. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  774. assert row.notes == "restored note"
  775. # The 3MF on disk must not be orphaned by a metadata restore.
  776. assert row.file_path == "/data/benchy.3mf"
  777. assert tally.restored == 1
  778. @pytest.mark.asyncio
  779. async def test_dangling_printer_and_project_links_are_cleared(self, db_session):
  780. tally = _CategoryTally()
  781. entry = self._archive_entry(printer_id=4242, project_id=4343)
  782. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  783. await db_session.commit()
  784. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  785. assert row.printer_id is None
  786. assert row.project_id is None
  787. assert any("no longer exist" in note for note in tally.notes)
  788. @pytest.mark.asyncio
  789. async def test_valid_printer_link_is_preserved(self, db_session, printer_factory):
  790. printer = await printer_factory()
  791. tally = _CategoryTally()
  792. entry = self._archive_entry(printer_id=printer.id)
  793. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  794. await db_session.commit()
  795. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  796. assert row.printer_id == printer.id
  797. @pytest.mark.asyncio
  798. async def test_non_dict_entry_counts_as_failed(self, db_session):
  799. tally = _CategoryTally()
  800. await _service()._restore_archives(db_session, {"archives": ["nonsense"]}, False, tally, {})
  801. assert tally.failed == 1
  802. class TestRestoreKprofiles:
  803. @staticmethod
  804. def _live(slot_id, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123"):
  805. """One profile as the printer currently reports it."""
  806. return SimpleNamespace(slot_id=slot_id, filament_id=filament_id, name=name, setting_id=setting_id)
  807. def _client(self, live=None, sent=True):
  808. client = MagicMock()
  809. client.state.connected = True
  810. client.set_kprofiles_batch = MagicMock(return_value=sent)
  811. client.get_kprofiles = AsyncMock(return_value=list(live or []))
  812. return client
  813. def _payload(self, serial="00M09A123456789", nozzle="0.4"):
  814. return {
  815. f"kprofiles/{serial}/{nozzle}.json": {
  816. "version": "1.0",
  817. "printer_serial": serial,
  818. "nozzle_diameter": nozzle,
  819. "profiles": [
  820. {
  821. "slot_id": 0,
  822. "name": "Bambu PLA",
  823. "k_value": "0.020000",
  824. "filament_id": "GFA00",
  825. "nozzle_id": "HS00-0.4",
  826. "extruder_id": 0,
  827. "setting_id": "PFUS123",
  828. }
  829. ],
  830. }
  831. }
  832. @pytest.mark.asyncio
  833. async def test_sends_batch_to_connected_printer(self, db_session, printer_factory):
  834. printer = await printer_factory(serial_number="00M09A123456789")
  835. client = MagicMock()
  836. client.state.connected = True
  837. client.set_kprofiles_batch = MagicMock(return_value=True)
  838. tally = _CategoryTally()
  839. with patch("backend.app.services.github_restore.printer_manager") as manager:
  840. manager.get_client = MagicMock(return_value=client)
  841. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  842. client.set_kprofiles_batch.assert_called_once()
  843. profiles, nozzle = client.set_kprofiles_batch.call_args.args
  844. assert nozzle == "0.4"
  845. assert profiles[0]["name"] == "Bambu PLA"
  846. assert profiles[0]["filament_id"] == "GFA00"
  847. assert tally.restored == 1
  848. assert manager.get_client.call_args.args == (printer.id,)
  849. @pytest.mark.asyncio
  850. async def test_always_warns_to_verify_on_the_printer(self, db_session, printer_factory):
  851. await printer_factory(serial_number="00M09A123456789")
  852. client = self._client()
  853. tally = _CategoryTally()
  854. with patch("backend.app.services.github_restore.printer_manager") as manager:
  855. manager.get_client = MagicMock(return_value=client)
  856. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  857. # The printer does answer extrusion_cali_set, but it reports "fail" on
  858. # writes that land, so the note must not promise either way.
  859. assert any("verify the profiles on the printer" in note for note in tally.notes)
  860. assert not any("without acknowledgement" in note for note in tally.notes)
  861. assert any("always overwrite" in note for note in tally.notes)
  862. # --- cali_idx is resolved live, never taken from the backup -------------
  863. #
  864. # Regression cover for the silent no-op found testing on an X1E: the backup
  865. # stored cali_idx 8151, a Bambuddy edit re-keyed the profile to 4606, and
  866. # the restore aimed extrusion_cali_set at 8151. The printer dropped it and
  867. # the tally still said "1 restored".
  868. @pytest.mark.asyncio
  869. async def test_uses_the_live_cali_idx_not_the_backed_up_slot(self, db_session, printer_factory):
  870. await printer_factory(serial_number="00M09A123456789")
  871. payload = self._payload()
  872. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]["slot_id"] = 8151
  873. client = self._client(live=[self._live(slot_id=4606)])
  874. tally = _CategoryTally()
  875. with patch("backend.app.services.github_restore.printer_manager") as manager:
  876. manager.get_client = MagicMock(return_value=client)
  877. await _service()._restore_kprofiles(db_session, payload, tally)
  878. client.get_kprofiles.assert_awaited_once_with(nozzle_diameter="0.4")
  879. profiles, _ = client.set_kprofiles_batch.call_args.args
  880. assert profiles[0]["cali_idx"] == 4606, "must address the slot that exists now"
  881. assert profiles[0]["cali_idx"] != 8151, "must not reuse the backup's cali_idx"
  882. assert tally.restored == 1
  883. @pytest.mark.asyncio
  884. async def test_matches_on_name_when_setting_id_was_regenerated(self, db_session, printer_factory):
  885. # A delete-then-add edit mints a fresh setting_id, so the name carries
  886. # the match instead.
  887. await printer_factory(serial_number="00M09A123456789")
  888. client = self._client(live=[self._live(slot_id=4606, setting_id="PF9999999999")])
  889. tally = _CategoryTally()
  890. with patch("backend.app.services.github_restore.printer_manager") as manager:
  891. manager.get_client = MagicMock(return_value=client)
  892. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  893. profiles, _ = client.set_kprofiles_batch.call_args.args
  894. assert profiles[0]["cali_idx"] == 4606
  895. # The live setting_id wins: it is what the printer associates with the slot.
  896. assert profiles[0]["setting_id"] == "PF9999999999"
  897. @pytest.mark.asyncio
  898. async def test_unmatched_profile_is_added_rather_than_aimed_at_a_dead_slot(self, db_session, printer_factory):
  899. await printer_factory(serial_number="00M09A123456789")
  900. client = self._client(live=[]) # printer has nothing for this nozzle
  901. tally = _CategoryTally()
  902. with patch("backend.app.services.github_restore.printer_manager") as manager:
  903. manager.get_client = MagicMock(return_value=client)
  904. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  905. profiles, _ = client.set_kprofiles_batch.call_args.args
  906. assert profiles[0]["cali_idx"] == -1, "-1 tells the printer to add a new profile"
  907. assert profiles[0]["setting_id"] == "PFUS123", "falls back to the backed-up preset"
  908. assert any("added as new profiles" in note for note in tally.notes)
  909. @pytest.mark.asyncio
  910. async def test_different_filament_is_not_treated_as_a_match(self, db_session, printer_factory):
  911. # Same slot, different filament — matching on slot alone would clobber
  912. # an unrelated profile.
  913. await printer_factory(serial_number="00M09A123456789")
  914. client = self._client(live=[self._live(slot_id=4606, filament_id="GFB99", name="Bambu PLA")])
  915. tally = _CategoryTally()
  916. with patch("backend.app.services.github_restore.printer_manager") as manager:
  917. manager.get_client = MagicMock(return_value=client)
  918. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  919. profiles, _ = client.set_kprofiles_batch.call_args.args
  920. assert profiles[0]["cali_idx"] == -1
  921. @pytest.mark.asyncio
  922. async def test_unreadable_live_index_degrades_to_adding(self, db_session, printer_factory):
  923. # A failed read must not abort the restore.
  924. await printer_factory(serial_number="00M09A123456789")
  925. client = self._client()
  926. client.get_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt timeout"))
  927. tally = _CategoryTally()
  928. with patch("backend.app.services.github_restore.printer_manager") as manager:
  929. manager.get_client = MagicMock(return_value=client)
  930. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  931. profiles, _ = client.set_kprofiles_batch.call_args.args
  932. assert profiles[0]["cali_idx"] == -1
  933. assert tally.restored == 1
  934. @pytest.mark.asyncio
  935. async def test_sole_profile_for_a_filament_matches_without_setting_id_or_name(self, db_session, printer_factory):
  936. await printer_factory(serial_number="00M09A123456789")
  937. payload = self._payload()
  938. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  939. entry["setting_id"] = None
  940. entry["name"] = ""
  941. client = self._client(live=[self._live(slot_id=4606, setting_id="PFOTHER", name="Renamed")])
  942. tally = _CategoryTally()
  943. with patch("backend.app.services.github_restore.printer_manager") as manager:
  944. manager.get_client = MagicMock(return_value=client)
  945. await _service()._restore_kprofiles(db_session, payload, tally)
  946. profiles, _ = client.set_kprofiles_batch.call_args.args
  947. assert profiles[0]["cali_idx"] == 4606
  948. @pytest.mark.asyncio
  949. async def test_ambiguous_filament_without_discriminator_is_added_not_guessed(self, db_session, printer_factory):
  950. await printer_factory(serial_number="00M09A123456789")
  951. payload = self._payload()
  952. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  953. entry["setting_id"] = None
  954. entry["name"] = ""
  955. client = self._client(live=[self._live(slot_id=1, setting_id="A"), self._live(slot_id=2, setting_id="B")])
  956. tally = _CategoryTally()
  957. with patch("backend.app.services.github_restore.printer_manager") as manager:
  958. manager.get_client = MagicMock(return_value=client)
  959. await _service()._restore_kprofiles(db_session, payload, tally)
  960. profiles, _ = client.set_kprofiles_batch.call_args.args
  961. assert profiles[0]["cali_idx"] == -1, "two candidates and nothing to tell them apart"
  962. @pytest.mark.asyncio
  963. async def test_unknown_serial_is_skipped_with_reason(self, db_session):
  964. tally = _CategoryTally()
  965. with patch("backend.app.services.github_restore.printer_manager"):
  966. await _service()._restore_kprofiles(db_session, self._payload(serial="NOSUCH"), tally)
  967. assert tally.restored == 0
  968. assert tally.skipped == 1
  969. assert any("No printer with serial NOSUCH" in note for note in tally.notes)
  970. @pytest.mark.asyncio
  971. async def test_offline_printer_is_skipped_not_failed(self, db_session, printer_factory):
  972. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  973. client = MagicMock()
  974. client.state.connected = False
  975. tally = _CategoryTally()
  976. with patch("backend.app.services.github_restore.printer_manager") as manager:
  977. manager.get_client = MagicMock(return_value=client)
  978. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  979. assert tally.skipped == 1
  980. assert tally.failed == 0
  981. assert any("not connected" in note for note in tally.notes)
  982. @pytest.mark.asyncio
  983. async def test_no_client_at_all_is_skipped(self, db_session, printer_factory):
  984. await printer_factory(serial_number="00M09A123456789")
  985. tally = _CategoryTally()
  986. with patch("backend.app.services.github_restore.printer_manager") as manager:
  987. manager.get_client = MagicMock(return_value=None)
  988. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  989. assert tally.skipped == 1
  990. @pytest.mark.asyncio
  991. async def test_publish_failure_counts_as_failed(self, db_session, printer_factory):
  992. await printer_factory(serial_number="00M09A123456789")
  993. client = MagicMock()
  994. client.state.connected = True
  995. client.set_kprofiles_batch = MagicMock(return_value=False)
  996. tally = _CategoryTally()
  997. with patch("backend.app.services.github_restore.printer_manager") as manager:
  998. manager.get_client = MagicMock(return_value=client)
  999. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1000. assert tally.failed == 1
  1001. assert tally.restored == 0
  1002. @pytest.mark.asyncio
  1003. async def test_publish_exception_is_contained(self, db_session, printer_factory):
  1004. await printer_factory(serial_number="00M09A123456789")
  1005. client = MagicMock()
  1006. client.state.connected = True
  1007. client.set_kprofiles_batch = MagicMock(side_effect=RuntimeError("mqtt down"))
  1008. tally = _CategoryTally()
  1009. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1010. manager.get_client = MagicMock(return_value=client)
  1011. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1012. assert tally.failed == 1
  1013. @pytest.mark.asyncio
  1014. async def test_each_nozzle_is_sent_separately(self, db_session, printer_factory):
  1015. await printer_factory(serial_number="00M09A123456789")
  1016. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  1017. client = MagicMock()
  1018. client.state.connected = True
  1019. client.set_kprofiles_batch = MagicMock(return_value=True)
  1020. tally = _CategoryTally()
  1021. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1022. manager.get_client = MagicMock(return_value=client)
  1023. await _service()._restore_kprofiles(db_session, payload, tally)
  1024. assert client.set_kprofiles_batch.call_count == 2
  1025. assert {c.args[1] for c in client.set_kprofiles_batch.call_args_list} == {"0.4", "0.8"}
  1026. assert tally.restored == 2
  1027. @pytest.mark.asyncio
  1028. async def test_empty_payload_is_noted(self, db_session):
  1029. tally = _CategoryTally()
  1030. await _service()._restore_kprofiles(db_session, {}, tally)
  1031. assert any("No K-profile data" in note for note in tally.notes)
  1032. class TestSoftDeletedArchiveRoundTrip:
  1033. """The two halves of the soft-delete fix only work together.
  1034. The collector keeps soft-deleted rows on purpose (their stats still count),
  1035. so if it doesn't write ``deleted_at`` there is nothing for the restore to
  1036. carry across and a deleted archive comes back visible. Covered end to end
  1037. because each half looks harmless on its own.
  1038. """
  1039. @pytest.mark.asyncio
  1040. async def test_deleted_at_survives_collect_then_restore(self, db_session):
  1041. from backend.app.services.github_backup import github_backup_service
  1042. deleted_at = datetime(2026, 3, 5, 9, 0, 0)
  1043. db_session.add(
  1044. PrintArchive(
  1045. filename="trashed.3mf",
  1046. file_path="",
  1047. file_size=1024,
  1048. content_hash="hash-trashed",
  1049. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1050. deleted_at=deleted_at,
  1051. )
  1052. )
  1053. await db_session.commit()
  1054. files: dict = {}
  1055. await github_backup_service._collect_archives(db_session, files)
  1056. payload = files[ARCHIVES_PATH]
  1057. assert payload["archives"][0]["deleted_at"] == str(deleted_at)
  1058. # Restore that payload into an instance where the row is gone entirely.
  1059. await db_session.execute(PrintArchive.__table__.delete())
  1060. await db_session.commit()
  1061. tally = _CategoryTally()
  1062. await _service()._restore_archives(db_session, payload, False, tally, {})
  1063. await db_session.commit()
  1064. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1065. assert row.deleted_at == deleted_at, "a deleted archive must not come back visible"
  1066. class TestCategoryPathMapping:
  1067. def setup_method(self):
  1068. self.service = _service()
  1069. self.available = [
  1070. "backup_metadata.json",
  1071. SETTINGS_PATH,
  1072. SPOOLS_PATH,
  1073. SPOOL_USAGE_PATH,
  1074. ARCHIVES_PATH,
  1075. "kprofiles/SERIAL1/0.4.json",
  1076. "kprofiles/SERIAL1/0.8.json",
  1077. "cloud_profiles/filament.json",
  1078. ]
  1079. def test_spools_includes_usage_history(self):
  1080. paths = self.service._category_paths(RestoreCategory.SPOOLS, self.available)
  1081. assert paths == [SPOOLS_PATH, SPOOL_USAGE_PATH]
  1082. def test_kprofiles_globs_all_serials_and_nozzles(self):
  1083. paths = self.service._category_paths(RestoreCategory.KPROFILES, self.available)
  1084. assert paths == ["kprofiles/SERIAL1/0.4.json", "kprofiles/SERIAL1/0.8.json"]
  1085. def test_absent_paths_are_omitted(self):
  1086. paths = self.service._category_paths(RestoreCategory.SETTINGS, ["backup_metadata.json"])
  1087. assert paths == []
  1088. def test_cloud_profiles_are_not_a_restore_category(self):
  1089. assert "cloud_profiles" not in {c.value for c in RestoreCategory}
  1090. class TestMutex:
  1091. @pytest.mark.asyncio
  1092. async def test_restore_refuses_while_a_backup_is_running(self):
  1093. service = _service()
  1094. with patch("backend.app.services.github_backup.github_backup_service") as backup:
  1095. backup.is_running = True
  1096. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  1097. assert result["success"] is False
  1098. assert "backup is currently running" in result["message"]
  1099. @pytest.mark.asyncio
  1100. async def test_restore_refuses_while_another_restore_is_running(self):
  1101. service = _service()
  1102. service._running_restore = True
  1103. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  1104. assert result["success"] is False
  1105. assert "restore is already running" in result["message"]
  1106. @pytest.mark.asyncio
  1107. async def test_backup_refuses_while_a_restore_is_running(self):
  1108. from backend.app.services.github_backup import GitHubBackupService
  1109. backup_service = GitHubBackupService()
  1110. with patch("backend.app.services.github_restore.github_restore_service") as restore:
  1111. restore.is_running = True
  1112. result = await backup_service.run_backup(1, trigger="manual")
  1113. assert result["success"] is False
  1114. assert "restore is currently running" in result["message"]
  1115. class TestMqttRelayReconfigure:
  1116. """Restoring mqtt_* rows has to reach the live relay, not just the table."""
  1117. @pytest.mark.asyncio
  1118. async def test_reconfigures_from_the_committed_rows(self, db_session):
  1119. db_session.add(Settings(key="mqtt_enabled", value="true"))
  1120. db_session.add(Settings(key="mqtt_broker", value="restored.local"))
  1121. db_session.add(Settings(key="mqtt_port", value="8883"))
  1122. db_session.add(Settings(key="mqtt_use_tls", value="true"))
  1123. # Never restorable (credential blocklist), so it comes from the row that
  1124. # was already there.
  1125. db_session.add(Settings(key="mqtt_password", value="kept"))
  1126. await db_session.commit()
  1127. tally = _CategoryTally()
  1128. relay = MagicMock()
  1129. relay.configure = AsyncMock(return_value=True)
  1130. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1131. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_broker"}, tally)
  1132. relay.configure.assert_awaited_once()
  1133. sent = relay.configure.await_args.args[0]
  1134. assert sent["mqtt_enabled"] is True
  1135. assert sent["mqtt_broker"] == "restored.local"
  1136. assert sent["mqtt_port"] == 8883
  1137. assert sent["mqtt_use_tls"] is True
  1138. assert sent["mqtt_password"] == "kept"
  1139. assert sent["mqtt_topic_prefix"] == "bambuddy"
  1140. assert tally.notes == []
  1141. @pytest.mark.asyncio
  1142. async def test_no_reconnect_when_no_mqtt_key_was_written(self, db_session):
  1143. """configure() tears the connection down, so don't call it for a theme change."""
  1144. tally = _CategoryTally()
  1145. relay = MagicMock()
  1146. relay.configure = AsyncMock()
  1147. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1148. await _service()._reconfigure_mqtt_relay(db_session, {"currency", "theme"}, tally)
  1149. relay.configure.assert_not_awaited()
  1150. @pytest.mark.asyncio
  1151. async def test_broker_failure_is_noted_not_fatal(self, db_session):
  1152. tally = _CategoryTally()
  1153. relay = MagicMock()
  1154. relay.configure = AsyncMock(side_effect=OSError("no route to broker"))
  1155. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1156. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_enabled"}, tally)
  1157. assert any("restart Bambuddy" in note for note in tally.notes)
  1158. @pytest.mark.asyncio
  1159. async def test_restore_settings_reports_the_keys_it_wrote(self, db_session):
  1160. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  1161. await db_session.commit()
  1162. written: set[str] = set()
  1163. payload = {
  1164. "settings": {
  1165. "mqtt_broker": "new.local",
  1166. "currency": "EUR",
  1167. "mqtt_password": "leaked",
  1168. "auth_enabled": "false",
  1169. }
  1170. }
  1171. await _service()._restore_settings(
  1172. db_session, payload, overwrite=True, tally=_CategoryTally(), keys_written=written
  1173. )
  1174. # Skipped keys are not "written", or a blocked mqtt_password would
  1175. # trigger a pointless reconnect.
  1176. assert written == {"mqtt_broker", "currency"}
  1177. @pytest.mark.asyncio
  1178. async def test_keys_skipped_for_overwrite_off_are_not_reported(self, db_session):
  1179. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  1180. await db_session.commit()
  1181. written: set[str] = set()
  1182. await _service()._restore_settings(
  1183. db_session,
  1184. {"settings": {"mqtt_broker": "new.local"}},
  1185. overwrite=False,
  1186. tally=_CategoryTally(),
  1187. keys_written=written,
  1188. )
  1189. assert written == set()
  1190. @pytest.mark.asyncio
  1191. async def test_a_refused_mqtt_enabled_is_not_reported_as_written(self, db_session):
  1192. """So the relay reconfigures from the *local* mqtt_enabled, not the backup's.
  1193. The companion rule refuses ``mqtt_enabled`` when the backup's password
  1194. cannot come across and there is none stored locally. It must not then
  1195. appear in ``keys_written``, or _reconfigure_mqtt_relay would be asked to
  1196. bring up a broker connection the restore deliberately declined to enable.
  1197. """
  1198. written: set[str] = set()
  1199. await _service()._restore_settings(
  1200. db_session,
  1201. {"settings": {"mqtt_enabled": "true", "mqtt_password": "refused", "mqtt_broker": "new.local"}},
  1202. overwrite=True,
  1203. tally=_CategoryTally(),
  1204. keys_written=written,
  1205. )
  1206. assert written == {"mqtt_broker"}
  1207. class TestApplyOrdering:
  1208. """_apply must not hold SQLite's write transaction across the MQTT phase."""
  1209. def _recording_service(self, calls: list[str]):
  1210. service = _service()
  1211. # Sync side effects on purpose: an AsyncMock returns a coroutine its
  1212. # side_effect hands back rather than awaiting it, so an async recorder
  1213. # would never run.
  1214. service._restore_archives = AsyncMock(side_effect=lambda *a, **k: calls.append("archives"))
  1215. service._restore_spools = AsyncMock(side_effect=lambda *a, **k: calls.append("spools"))
  1216. service._restore_settings = AsyncMock(side_effect=lambda *a, **k: calls.append("settings"))
  1217. service._restore_kprofiles = AsyncMock(side_effect=lambda *a, **k: calls.append("kprofiles"))
  1218. return service
  1219. @pytest.mark.asyncio
  1220. async def test_commits_database_categories_before_talking_to_printers(self):
  1221. """get_kprofiles is 3 x 5 s per printer/nozzle; busy_timeout is 15 s."""
  1222. calls: list[str] = []
  1223. service = self._recording_service(calls)
  1224. db = MagicMock()
  1225. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  1226. await service._apply(
  1227. db,
  1228. {},
  1229. [RestoreCategory.ARCHIVES, RestoreCategory.SPOOLS, RestoreCategory.KPROFILES],
  1230. False,
  1231. )
  1232. assert calls == ["archives", "spools", "commit", "kprofiles"]
  1233. @pytest.mark.asyncio
  1234. async def test_does_not_split_the_transaction_without_kprofiles(self):
  1235. """A database-only restore stays one transaction, committed by run_restore."""
  1236. calls: list[str] = []
  1237. service = self._recording_service(calls)
  1238. db = MagicMock()
  1239. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  1240. await service._apply(db, {}, [RestoreCategory.ARCHIVES, RestoreCategory.SETTINGS], False)
  1241. assert calls == ["archives", "settings"]
  1242. assert db.commit.await_count == 0
  1243. class TestResolveRef:
  1244. @pytest.mark.asyncio
  1245. async def test_concrete_sha_passes_through_without_an_api_call(self):
  1246. service = _service()
  1247. service.list_commits = AsyncMock()
  1248. config = MagicMock(branch="main")
  1249. resolved, error = await service._resolve_ref(config, "abc1234")
  1250. assert resolved == "abc1234"
  1251. assert error == ""
  1252. service.list_commits.assert_not_awaited()
  1253. @pytest.mark.asyncio
  1254. async def test_head_resolves_to_the_tip_sha(self):
  1255. service = _service()
  1256. service.list_commits = AsyncMock(
  1257. return_value={"success": True, "commits": [{"sha": "tipsha1"}, {"sha": "older"}]}
  1258. )
  1259. config = MagicMock(branch="main")
  1260. resolved, error = await service._resolve_ref(config, "HEAD")
  1261. assert resolved == "tipsha1"
  1262. assert error == ""
  1263. @pytest.mark.asyncio
  1264. async def test_empty_history_is_an_error(self):
  1265. service = _service()
  1266. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  1267. config = MagicMock(branch="main")
  1268. resolved, error = await service._resolve_ref(config, "HEAD")
  1269. assert resolved is None
  1270. assert "no commits" in error