test_github_restore.py 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784
  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, timedelta
  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.models.user import User
  17. from backend.app.schemas.github_backup import GitHubRestoreRequest, RestoreCategory
  18. from backend.app.services.github_restore import (
  19. _COMPANION_CREDENTIAL_ENV,
  20. _COMPANION_CREDENTIALS,
  21. _COMPANION_EXPOSURE_TOGGLES,
  22. ARCHIVES_PATH,
  23. SETTINGS_PATH,
  24. SPOOL_USAGE_PATH,
  25. SPOOLS_PATH,
  26. GitHubRestoreService,
  27. _CategoryTally,
  28. _is_blocked_setting_key,
  29. _is_protected_setting_key,
  30. _is_usable_credential,
  31. _parse_dt,
  32. _setting_value_is_true,
  33. _SettingsPlan,
  34. )
  35. def _service() -> GitHubRestoreService:
  36. return GitHubRestoreService()
  37. def _messages(tally: _CategoryTally) -> list[str]:
  38. """The English rendering of each note.
  39. Notes are ``{code, params, message}`` since they became translatable
  40. (#2656); asserting on the message keeps these tests readable while
  41. ``_codes`` covers the half a client actually keys on.
  42. """
  43. return [note["message"] for note in tally.notes]
  44. def _codes(tally: _CategoryTally) -> list[str]:
  45. return [note["code"] for note in tally.notes]
  46. class TestParseDt:
  47. def test_parses_str_datetime_the_backup_writes(self):
  48. assert _parse_dt("2026-07-27 06:02:05.123456") == datetime(2026, 7, 27, 6, 2, 5, 123456)
  49. def test_parses_iso_with_t_separator(self):
  50. assert _parse_dt("2026-07-27T06:02:05") == datetime(2026, 7, 27, 6, 2, 5)
  51. @pytest.mark.parametrize("value", ["", None, "not a date", 12345, {}])
  52. def test_returns_none_for_junk(self, value):
  53. assert _parse_dt(value) is None
  54. def test_an_offset_is_normalised_to_naive_utc(self):
  55. """Every DateTime column here is naive UTC; an aware value cannot be
  56. written to one without silently shifting the wall clock, nor compared
  57. against one without raising."""
  58. assert _parse_dt("2026-07-27T08:02:05+02:00") == datetime(2026, 7, 27, 6, 2, 5)
  59. assert _parse_dt("2026-07-27T06:02:05+00:00").tzinfo is None
  60. class TestSettingKeyBlocklist:
  61. @pytest.mark.parametrize(
  62. "key",
  63. [
  64. "bambu_cloud_token",
  65. "auth_secret_key",
  66. "ha_token",
  67. "prometheus_token",
  68. "printer_access_code",
  69. "smtp_password",
  70. "some_api_key",
  71. "ftp_passphrase",
  72. "MQTT_SECRET",
  73. ],
  74. )
  75. def test_credential_like_keys_are_blocked(self, key):
  76. assert _is_blocked_setting_key(key) is True
  77. @pytest.mark.parametrize(
  78. "key",
  79. ["low_stock_threshold", "currency", "theme", "local_backup_enabled", "timezone"],
  80. )
  81. def test_ordinary_keys_are_allowed(self, key):
  82. assert _is_blocked_setting_key(key) is False
  83. @pytest.mark.parametrize(
  84. "key",
  85. ["auth_enabled", "advanced_auth_enabled", "local_login_enabled", "setup_completed"],
  86. )
  87. def test_auth_policy_keys_are_protected(self, key):
  88. # Not credential-shaped, so the secret hints never catch them.
  89. assert _is_blocked_setting_key(key) is False
  90. assert _is_protected_setting_key(key) is True
  91. @pytest.mark.parametrize("key", ["currency", "ldap_enabled", "auth_secret_key"])
  92. def test_protected_set_is_only_the_auth_policy_keys(self, key):
  93. assert _is_protected_setting_key(key) is False
  94. def test_ha_token_from_env_is_deliberately_not_carved_out(self):
  95. """Recorded so the review's question about it is not re-litigated.
  96. ``ha_token_from_env`` looks like a false positive for the ``token`` hint,
  97. but it is only ever constructed in the settings GET response
  98. (``get_homeassistant_settings``). It is absent from ``AppSettingsUpdate``
  99. and so is never a ``Settings`` row — it cannot reach a backup, which
  100. makes an allowlist entry for it dead code.
  101. Carving it out would also be a live hole rather than a tidy-up: an
  102. attacker-authored ``settings/app_settings.json`` could then get a
  103. ``*token*``-named row written simply by choosing that name. This
  104. blocklist's whole job is belt-and-braces, so a name-shaped exception to
  105. it is exactly the wrong shape of fix.
  106. """
  107. assert _is_blocked_setting_key("ha_token_from_env") is True
  108. class TestCategoryTally:
  109. def test_a_note_carries_code_params_and_english(self):
  110. tally = _CategoryTally()
  111. tally.note("noData", "No data of this kind in this backup")
  112. tally.note("spoolUsageUnresolved", "2 usage record(s) skipped", count=2)
  113. assert tally.notes == [
  114. {"code": "noData", "params": {}, "message": "No data of this kind in this backup"},
  115. {"code": "spoolUsageUnresolved", "params": {"count": 2}, "message": "2 usage record(s) skipped"},
  116. ]
  117. def test_notes_are_deduplicated(self):
  118. tally = _CategoryTally()
  119. tally.note("noData", "same")
  120. tally.note("noData", "same")
  121. assert len(tally.notes) == 1
  122. def test_the_same_code_with_different_params_is_kept(self):
  123. """Two printers can both be offline, and the user needs both names."""
  124. tally = _CategoryTally()
  125. tally.note("kprofilesPrinterOffline", "A is not connected", printer="A")
  126. tally.note("kprofilesPrinterOffline", "B is not connected", printer="B")
  127. assert len(tally.notes) == 2
  128. def test_notes_are_bounded(self):
  129. tally = _CategoryTally()
  130. for i in range(50):
  131. tally.note("noData", f"note {i}", index=i)
  132. assert len(tally.notes) == 20
  133. class TestRestoreRequestSchema:
  134. def test_rejects_empty_category_list(self):
  135. with pytest.raises(ValueError):
  136. GitHubRestoreRequest(categories=[])
  137. def test_deduplicates_categories(self):
  138. request = GitHubRestoreRequest(
  139. categories=[RestoreCategory.SPOOLS, RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  140. )
  141. assert request.categories == [RestoreCategory.SPOOLS, RestoreCategory.SETTINGS]
  142. def test_defaults_to_head(self):
  143. assert GitHubRestoreRequest(categories=[RestoreCategory.SPOOLS]).ref == "HEAD"
  144. @pytest.mark.parametrize("ref", ["HEAD", "abc1234", "a" * 40])
  145. def test_accepts_valid_refs(self, ref):
  146. assert GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS]).ref == ref
  147. @pytest.mark.parametrize("ref", ["abc", "main", "../etc/passwd", "a" * 41, "zzzzzzz", "abc 123"])
  148. def test_rejects_refs_that_are_not_object_names(self, ref):
  149. with pytest.raises(ValueError):
  150. GitHubRestoreRequest(ref=ref, categories=[RestoreCategory.SPOOLS])
  151. class TestRestoreSettings:
  152. @pytest.mark.asyncio
  153. async def test_inserts_missing_keys(self, db_session):
  154. tally = _CategoryTally()
  155. payload = {"version": "1.0", "settings": {"currency": "EUR", "theme": "dark"}}
  156. await _service()._restore_settings(db_session, payload, overwrite=False, tally=tally)
  157. await db_session.commit()
  158. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  159. assert rows == {"currency": "EUR", "theme": "dark"}
  160. assert tally.restored == 2
  161. @pytest.mark.asyncio
  162. async def test_skips_existing_key_when_overwrite_off(self, db_session):
  163. db_session.add(Settings(key="currency", value="USD"))
  164. await db_session.commit()
  165. tally = _CategoryTally()
  166. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=False, tally=tally)
  167. await db_session.commit()
  168. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  169. assert row.value == "USD"
  170. assert tally.skipped == 1
  171. assert tally.restored == 0
  172. @pytest.mark.asyncio
  173. async def test_overwrites_existing_key_when_enabled(self, db_session):
  174. db_session.add(Settings(key="currency", value="USD"))
  175. await db_session.commit()
  176. tally = _CategoryTally()
  177. await _service()._restore_settings(db_session, {"settings": {"currency": "EUR"}}, overwrite=True, tally=tally)
  178. await db_session.commit()
  179. row = (await db_session.execute(select(Settings).where(Settings.key == "currency"))).scalar_one()
  180. assert row.value == "EUR"
  181. assert tally.restored == 1
  182. @pytest.mark.asyncio
  183. async def test_credential_keys_are_never_restored(self, db_session):
  184. """A backup predating the collector's denylist can still contain secrets."""
  185. tally = _CategoryTally()
  186. payload = {"settings": {"currency": "EUR", "bambu_cloud_token": "leaked", "ha_token": "leaked"}}
  187. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  188. await db_session.commit()
  189. keys = {s.key for s in (await db_session.execute(select(Settings))).scalars().all()}
  190. assert keys == {"currency"}
  191. # Refusals are notes, not tally rows: the preview never counted these
  192. # keys, so counting them here would put the total above what the user
  193. # was shown before they pressed Restore.
  194. assert tally.skipped == 0
  195. assert any("credential-like" in note for note in _messages(tally))
  196. @pytest.mark.asyncio
  197. async def test_auth_settings_are_never_restored(self, db_session):
  198. """Restoring auth_enabled=false would disable auth behind the cache's back."""
  199. db_session.add(Settings(key="auth_enabled", value="true"))
  200. db_session.add(Settings(key="local_login_enabled", value="true"))
  201. await db_session.commit()
  202. tally = _CategoryTally()
  203. payload = {
  204. "settings": {
  205. "currency": "EUR",
  206. "auth_enabled": "false",
  207. "advanced_auth_enabled": "false",
  208. "local_login_enabled": "false",
  209. "setup_completed": "false",
  210. }
  211. }
  212. await _service()._restore_settings(db_session, payload, overwrite=True, tally=tally)
  213. await db_session.commit()
  214. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  215. assert rows["auth_enabled"] == "true"
  216. assert rows["local_login_enabled"] == "true"
  217. assert "advanced_auth_enabled" not in rows
  218. assert "setup_completed" not in rows
  219. assert rows["currency"] == "EUR"
  220. assert tally.restored == 1
  221. # As above: refused keys are outside the preview's count, so outside the
  222. # tally too.
  223. assert tally.skipped == 0
  224. assert any("authentication setting" in note for note in _messages(tally))
  225. @pytest.mark.asyncio
  226. async def test_missing_payload_is_noted_not_fatal(self, db_session):
  227. tally = _CategoryTally()
  228. await _service()._restore_settings(db_session, None, overwrite=True, tally=tally)
  229. assert tally.restored == 0
  230. assert _codes(tally) == ["noData"]
  231. class TestSettingValueIsTrue:
  232. """Only the spellings a reader actually treats as "on" count as on."""
  233. @pytest.mark.parametrize("value", ["true", "TRUE", " True ", True])
  234. def test_on(self, value):
  235. assert _setting_value_is_true(value) is True
  236. @pytest.mark.parametrize("value", ["false", "1", "on", "yes", "", None, False, 0])
  237. def test_off(self, value):
  238. # "1"/"on"/"yes" are deliberately off: no reader in the codebase treats
  239. # them as on, so restoring one cannot switch anything on either.
  240. assert _setting_value_is_true(value) is False
  241. class TestUsableCredential:
  242. @pytest.mark.parametrize("value", ["s3cret", " x "])
  243. def test_present_values_are_usable(self, value):
  244. assert _is_usable_credential(value) is True
  245. @pytest.mark.parametrize("value", [None, "", " "])
  246. def test_absent_or_blank_is_not(self, value):
  247. # A present-but-blank prometheus_token row is exactly the `if token:`
  248. # hole in the metrics route, so it must not count as protection.
  249. assert _is_usable_credential(value) is False
  250. class TestCompanionCredentials:
  251. """Toggles whose safety depends on a credential the restore refuses to write.
  252. ``prometheus_enabled`` is the sharp one. ``/api/v1/metrics`` is a public
  253. route whose only gate is a non-empty ``prometheus_token``, so restoring the
  254. toggle onto an instance that has no token row publishes the entire metrics
  255. body to anyone who can reach the port — and with overwrite *off*, since the
  256. row is missing rather than present. The other four break an integration
  257. rather than open one, but they are the same shape.
  258. """
  259. async def _restore(self, db, tally=None, overwrite=False, **settings) -> _CategoryTally:
  260. tally = tally or _CategoryTally()
  261. await _service()._restore_settings(db, {"settings": settings}, overwrite=overwrite, tally=tally)
  262. await db.commit()
  263. return tally
  264. async def _rows(self, db) -> dict:
  265. return {s.key: s.value for s in (await db.execute(select(Settings))).scalars().all()}
  266. # --- The refusal itself ------------------------------------------------
  267. @pytest.mark.asyncio
  268. async def test_prometheus_toggle_is_refused_when_its_token_was_skipped(self, db_session):
  269. """The headline case: overwrite off, empty database, endpoint stays shut."""
  270. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  271. rows = await self._rows(db_session)
  272. assert rows == {"currency": "EUR"}
  273. assert any("prometheus_enabled" in note and "switched off" in note for note in _messages(tally))
  274. @pytest.mark.asyncio
  275. @pytest.mark.parametrize("toggle,credential", sorted(_COMPANION_CREDENTIALS.items()))
  276. async def test_every_pair_refuses_its_toggle(self, db_session, toggle, credential, monkeypatch):
  277. monkeypatch.delenv("HA_TOKEN", raising=False)
  278. await self._restore(db_session, **{toggle: "true", credential: "s3cret"})
  279. assert toggle not in await self._rows(db_session)
  280. @pytest.mark.asyncio
  281. async def test_ha_toggle_is_refused_when_the_environment_has_no_token(self, db_session, monkeypatch):
  282. monkeypatch.delenv("HA_TOKEN", raising=False)
  283. await self._restore(db_session, ha_enabled="true", ha_token="s3cret", ha_url="http://ha.local")
  284. rows = await self._rows(db_session)
  285. assert "ha_enabled" not in rows
  286. assert rows["ha_url"] == "http://ha.local"
  287. @pytest.mark.asyncio
  288. async def test_a_blank_local_credential_row_is_not_usable(self, db_session):
  289. db_session.add(Settings(key="prometheus_token", value=""))
  290. await db_session.commit()
  291. await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  292. assert "prometheus_enabled" not in await self._rows(db_session)
  293. @pytest.mark.asyncio
  294. @pytest.mark.parametrize("value", ["TRUE", " True ", True])
  295. async def test_true_is_refused_however_it_is_spelled(self, db_session, value):
  296. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  297. assert "prometheus_enabled" not in await self._rows(db_session)
  298. # --- Ruling 3: the tally counts what the preview counted ---------------
  299. @pytest.mark.asyncio
  300. async def test_refusals_are_not_counted_in_the_tally(self, db_session):
  301. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true", prometheus_token="s3cret")
  302. assert (tally.restored, tally.skipped, tally.failed) == (1, 0, 0)
  303. @pytest.mark.asyncio
  304. async def test_tally_total_equals_the_preview_item_count(self, db_session):
  305. """The ruling, encoded: the user is shown a number, and it has to hold.
  306. Off by three before this change — the two name-based refusals and the
  307. companion one were all counted as ``skipped`` despite never being in the
  308. preview's count.
  309. """
  310. db_session.add(Settings(key="theme", value="light"))
  311. await db_session.commit()
  312. values = {
  313. "currency": "EUR", # inserted -> restored
  314. "theme": "dark", # exists, overwrite off -> skipped
  315. "low_stock_threshold": None, # no value -> skipped
  316. "": "junk", # unusable key -> failed
  317. "bambu_cloud_token": "x", # blocked -> refused
  318. "auth_enabled": "false", # protected -> refused
  319. "prometheus_enabled": "true", # companion -> refused
  320. "prometheus_token": "s3cret", # blocked -> refused
  321. }
  322. item_count, _ = await _service()._count_items(
  323. db_session, RestoreCategory.SETTINGS, {SETTINGS_PATH: {"settings": values}}
  324. )
  325. tally = _CategoryTally()
  326. await _service()._restore_settings(db_session, {"settings": values}, overwrite=False, tally=tally)
  327. await db_session.commit()
  328. assert tally.restored + tally.skipped + tally.failed == item_count
  329. assert (tally.restored, tally.skipped, tally.failed) == (1, 2, 1)
  330. @pytest.mark.asyncio
  331. async def test_preview_count_drops_by_one_when_the_local_credential_is_missing(self, db_session):
  332. parsed = {
  333. SETTINGS_PATH: {"settings": {"currency": "EUR", "prometheus_enabled": "true", "prometheus_token": "s3cret"}}
  334. }
  335. refused_count, refused_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  336. db_session.add(Settings(key="prometheus_token", value="already-set"))
  337. await db_session.commit()
  338. allowed_count, allowed_detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  339. assert refused_count == allowed_count - 1
  340. assert refused_detail.code == "settingsCompanionWillSkip"
  341. assert refused_detail.params == {"count": 1, "companion": 1}
  342. # Nothing is being left off now, so the wording drops back to the plain
  343. # credential caveat.
  344. assert allowed_detail.code == "settingsCredentialsWillSkip"
  345. # --- The exposure class: a blank backup credential is the hole ----------
  346. #
  347. # The rule's second condition — "the backup carried a usable credential" —
  348. # is what stops it refusing an anonymous MQTT broker. It does not transfer to
  349. # Prometheus: a backup taken on an instance that enabled Prometheus without a
  350. # token (the field is optional and defaults to "") carries the toggle and no
  351. # usable token, and writing it opens /api/v1/metrics just as wide. That is
  352. # the *more* likely source of the exposure, not the less.
  353. @pytest.mark.asyncio
  354. async def test_prometheus_is_refused_when_the_backup_has_no_token_key_at_all(self, db_session):
  355. tally = await self._restore(db_session, currency="EUR", prometheus_enabled="true")
  356. rows = await self._rows(db_session)
  357. assert rows == {"currency": "EUR"}
  358. assert any("prometheus_enabled" in note and "switched off" in note for note in _messages(tally))
  359. @pytest.mark.asyncio
  360. @pytest.mark.parametrize("token", ["", " "])
  361. async def test_prometheus_is_refused_when_the_backup_token_is_blank(self, db_session, token):
  362. tally = await self._restore(db_session, prometheus_enabled="true", prometheus_token=token)
  363. assert "prometheus_enabled" not in await self._rows(db_session)
  364. assert "settingsCompanionSkipped" in _codes(tally)
  365. @pytest.mark.asyncio
  366. async def test_the_preview_says_so_with_no_credential_key_to_skip(self, db_session):
  367. """The wording has to survive ``blocked`` being empty.
  368. The shared caveat counts credential-like keys *and* switches; on this
  369. payload there are no credential-like keys, so "0 credential-like key(s)
  370. will be skipped" would be noise.
  371. """
  372. parsed = {SETTINGS_PATH: {"settings": {"currency": "EUR", "prometheus_enabled": "true"}}}
  373. count, detail = await _service()._count_items(db_session, RestoreCategory.SETTINGS, parsed)
  374. assert count == 1
  375. assert detail.code == "settingsCompanionOnlyWillSkip"
  376. assert detail.params == {"companion": 1}
  377. @pytest.mark.asyncio
  378. async def test_the_availability_class_keeps_the_backup_credential_condition(self, db_session):
  379. """The other half of the same change: only Prometheus loses condition 2.
  380. Absent is treated like blank here — an anonymous broker or bind is a
  381. working config, so refusing it would be a false positive.
  382. """
  383. await self._restore(db_session, mqtt_enabled="true", ldap_enabled="true", virtual_printer_enabled="true")
  384. rows = await self._rows(db_session)
  385. assert rows["mqtt_enabled"] == "true"
  386. assert rows["ldap_enabled"] == "true"
  387. assert rows["virtual_printer_enabled"] == "true"
  388. def test_every_exposure_toggle_is_a_companion_toggle(self):
  389. assert _COMPANION_EXPOSURE_TOGGLES.issubset(_COMPANION_CREDENTIALS)
  390. # --- Controls: over-refusal is the real risk here ----------------------
  391. @pytest.mark.asyncio
  392. async def test_a_usable_local_credential_lets_the_toggle_through(self, db_session):
  393. db_session.add(Settings(key="prometheus_token", value="already-set"))
  394. await db_session.commit()
  395. tally = await self._restore(db_session, prometheus_enabled="true", prometheus_token="s3cret")
  396. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  397. assert not any("switched off" in note for note in _messages(tally))
  398. @pytest.mark.asyncio
  399. async def test_the_exposure_route_still_stands_down_for_a_local_token(self, db_session):
  400. """Skipping condition 2 must not skip the local-state pass with it."""
  401. db_session.add(Settings(key="prometheus_token", value="already-set"))
  402. await db_session.commit()
  403. tally = await self._restore(db_session, prometheus_enabled="true")
  404. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  405. assert not any("switched off" in note for note in _messages(tally))
  406. @pytest.mark.asyncio
  407. async def test_the_exposure_route_still_stands_down_when_already_on(self, db_session):
  408. """The exposure pre-dates this restore either way — see ruling 3."""
  409. db_session.add(Settings(key="prometheus_enabled", value="true"))
  410. await db_session.commit()
  411. tally = await self._restore(db_session, overwrite=True, prometheus_enabled="true")
  412. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  413. assert not any("switched off" in note for note in _messages(tally))
  414. @pytest.mark.asyncio
  415. async def test_an_anonymous_broker_is_not_a_false_positive(self, db_session):
  416. """mqtt_relay passes an empty password straight through — a real config."""
  417. tally = await self._restore(db_session, mqtt_enabled="true", mqtt_broker="10.0.0.5")
  418. assert (await self._rows(db_session))["mqtt_enabled"] == "true"
  419. assert not any("switched off" in note for note in _messages(tally))
  420. @pytest.mark.asyncio
  421. async def test_an_anonymous_ldap_bind_is_not_a_false_positive(self, db_session):
  422. """Same for a backup that carries the key with a blank value."""
  423. tally = await self._restore(db_session, ldap_enabled="true", ldap_bind_password=" ")
  424. assert (await self._rows(db_session))["ldap_enabled"] == "true"
  425. assert not any("switched off" in note for note in _messages(tally))
  426. @pytest.mark.asyncio
  427. async def test_turning_a_toggle_off_is_always_written(self, db_session):
  428. await self._restore(db_session, prometheus_enabled="false", prometheus_token="s3cret")
  429. assert (await self._rows(db_session))["prometheus_enabled"] == "false"
  430. @pytest.mark.asyncio
  431. @pytest.mark.parametrize("value", ["1", "on", "yes"])
  432. async def test_spellings_no_reader_treats_as_on_are_written(self, db_session, value):
  433. await self._restore(db_session, prometheus_enabled=value, prometheus_token="s3cret")
  434. assert (await self._rows(db_session))["prometheus_enabled"] == value
  435. @pytest.mark.asyncio
  436. async def test_ha_token_in_the_environment_counts_as_usable(self, db_session, monkeypatch):
  437. monkeypatch.setenv("HA_TOKEN", "from-env")
  438. await self._restore(db_session, ha_enabled="true", ha_token="s3cret")
  439. assert (await self._rows(db_session))["ha_enabled"] == "true"
  440. @pytest.mark.asyncio
  441. async def test_a_toggle_already_on_locally_is_written(self, db_session):
  442. """The exposure pre-dates the restore, so "left switched off" would be a lie."""
  443. db_session.add(Settings(key="prometheus_enabled", value="true"))
  444. await db_session.commit()
  445. tally = await self._restore(db_session, overwrite=True, prometheus_enabled="true", prometheus_token="s3cret")
  446. assert (await self._rows(db_session))["prometheus_enabled"] == "true"
  447. assert not any("switched off" in note for note in _messages(tally))
  448. # --- The map itself ----------------------------------------------------
  449. def test_every_companion_credential_is_blocked_and_no_toggle_is(self):
  450. """Guards the rule against a future edit to _SECRET_KEY_HINTS.
  451. If a credential stopped being blocked, its toggle would travel with it
  452. and the refusal would be pointless; if a toggle started being blocked,
  453. the pair would never be reached at all.
  454. """
  455. for toggle, credential in _COMPANION_CREDENTIALS.items():
  456. assert _is_blocked_setting_key(credential) is True, credential
  457. assert _is_blocked_setting_key(toggle) is False, toggle
  458. assert _is_protected_setting_key(toggle) is False, toggle
  459. def test_every_environment_override_names_a_companion_credential(self):
  460. assert set(_COMPANION_CREDENTIAL_ENV) <= set(_COMPANION_CREDENTIALS.values())
  461. @pytest.mark.asyncio
  462. async def test_plan_leaves_unusable_key_names_in_no_bucket(self, db_session):
  463. """They are the restore's ``failed``, not a refusal."""
  464. plan = await _service()._plan_settings(db_session, {"": "x", 7: "y", "currency": "EUR"})
  465. assert plan == _SettingsPlan()
  466. class TestSpoolTagOverwrite:
  467. """Overwrite must not write the backup's *other* tag key onto a matched spool.
  468. ``tag_uid`` and ``tray_uuid`` are both in the overwrite ``setattr`` loop, and
  469. neither column has a unique constraint, so writing one onto a spool matched
  470. by the other silently creates a duplicate tag rather than erroring. After
  471. that ``_find_spool``'s ``.first()`` is non-deterministic and an AMS tag
  472. lookup resolves to an arbitrary one of the two. The same loop can also clear
  473. a tag the user has scanned since the backup was taken.
  474. """
  475. def _entry(self, **overrides):
  476. entry = {
  477. "id": 41,
  478. "material": "PLA",
  479. "brand": "Bambu Lab",
  480. "created_at": "2026-01-05 12:00:00",
  481. "tag_uid": "TAG-A",
  482. "tray_uuid": None,
  483. }
  484. entry.update(overrides)
  485. return entry
  486. async def _restore(self, db, entry, tally=None):
  487. tally = tally or _CategoryTally()
  488. await _service()._restore_spools(db, {"spools": [entry]}, None, True, tally, {})
  489. await db.commit()
  490. return tally
  491. @pytest.mark.asyncio
  492. async def test_an_empty_incoming_tag_does_not_clear_a_scanned_one(self, db_session):
  493. """The backup predates the scan, so the local tag is the newer fact."""
  494. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-LIVE"))
  495. await db_session.commit()
  496. tally = await self._restore(db_session, self._entry(tray_uuid=None))
  497. row = (await db_session.execute(select(Spool))).scalar_one()
  498. assert row.tray_uuid == "TRAY-LIVE"
  499. assert any(note["code"] == "spoolTagKept" for note in tally.notes)
  500. @pytest.mark.asyncio
  501. async def test_a_tag_another_spool_already_holds_is_not_written(self, db_session):
  502. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A"))
  503. db_session.add(Spool(material="PETG", brand="Other", tray_uuid="TRAY-B"))
  504. await db_session.commit()
  505. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-B"))
  506. holders = (await db_session.execute(select(Spool).where(Spool.tray_uuid == "TRAY-B"))).scalars().all()
  507. assert len(holders) == 1, "a duplicate tray_uuid makes AMS lookups non-deterministic"
  508. assert holders[0].material == "PETG"
  509. assert any(note["code"] == "spoolTagKept" for note in tally.notes)
  510. @pytest.mark.asyncio
  511. async def test_the_note_counts_every_column_it_kept(self, db_session):
  512. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-LIVE"))
  513. db_session.add(Spool(material="PETG", brand="Other", tag_uid="TAG-CLASH"))
  514. await db_session.commit()
  515. # Matched on tray_uuid, so the guard judges tag_uid: it clashes.
  516. tally = await self._restore(db_session, self._entry(tag_uid="TAG-CLASH", tray_uuid="TRAY-LIVE"))
  517. row = (await db_session.execute(select(Spool).where(Spool.tray_uuid == "TRAY-LIVE"))).scalar_one()
  518. assert row.tag_uid == "TAG-A"
  519. note = next(n for n in tally.notes if n["code"] == "spoolTagKept")
  520. assert note["params"] == {"count": 1}
  521. # --- Controls ----------------------------------------------------------
  522. @pytest.mark.asyncio
  523. async def test_a_free_tag_is_still_written(self, db_session):
  524. """The point of overwrite: a spool that gained a tray_uuid gets it."""
  525. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A"))
  526. await db_session.commit()
  527. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-NEW"))
  528. row = (await db_session.execute(select(Spool))).scalar_one()
  529. assert row.tray_uuid == "TRAY-NEW"
  530. assert not any(note["code"] == "spoolTagKept" for note in tally.notes)
  531. @pytest.mark.asyncio
  532. async def test_an_unchanged_tag_is_not_reported_as_kept(self, db_session):
  533. db_session.add(Spool(material="PLA", brand="Bambu Lab", tag_uid="TAG-A", tray_uuid="TRAY-A"))
  534. await db_session.commit()
  535. tally = await self._restore(db_session, self._entry(tray_uuid="TRAY-A"))
  536. assert not any(note["code"] == "spoolTagKept" for note in tally.notes)
  537. @pytest.mark.asyncio
  538. async def test_a_new_spool_keeps_both_tags_from_the_backup(self, db_session):
  539. """The guard is an overwrite-only concern; an insert is unaffected."""
  540. await self._restore(db_session, self._entry(tag_uid="TAG-NEW", tray_uuid="TRAY-NEW"))
  541. row = (await db_session.execute(select(Spool))).scalar_one()
  542. assert (row.tag_uid, row.tray_uuid) == ("TAG-NEW", "TRAY-NEW")
  543. @pytest.mark.asyncio
  544. async def test_find_spool_reports_which_key_matched(self, db_session):
  545. db_session.add(Spool(material="PLA", tag_uid="TAG-A"))
  546. db_session.add(Spool(material="PETG", tray_uuid="TRAY-B"))
  547. await db_session.commit()
  548. service = _service()
  549. assert (await service._find_spool(db_session, {"tag_uid": "TAG-A"}))[1] == "tag_uid"
  550. assert (await service._find_spool(db_session, {"tray_uuid": "TRAY-B"}))[1] == "tray_uuid"
  551. assert await service._find_spool(db_session, {"tag_uid": "NOPE"}) == (None, None)
  552. class TestRestoreSpools:
  553. def _spool_entry(self, **overrides):
  554. entry = {
  555. "id": 41,
  556. "material": "PLA",
  557. "subtype": "Basic",
  558. "color_name": "Jade White",
  559. "brand": "Bambu Lab",
  560. "tag_uid": "AABBCCDD",
  561. "created_at": "2026-01-05 12:00:00",
  562. "weight_used": 120.5,
  563. }
  564. entry.update(overrides)
  565. return entry
  566. @pytest.mark.asyncio
  567. async def test_inserts_without_reusing_backup_id(self, db_session):
  568. """The backup's spool.id belongs to an unrelated row today."""
  569. db_session.add(Spool(material="PETG")) # occupies id 1
  570. await db_session.commit()
  571. tally = _CategoryTally()
  572. payload = {"spools": [self._spool_entry(id=1)]}
  573. await _service()._restore_spools(db_session, payload, None, False, tally, {})
  574. await db_session.commit()
  575. spools = (await db_session.execute(select(Spool))).scalars().all()
  576. assert len(spools) == 2
  577. restored = next(s for s in spools if s.tag_uid == "AABBCCDD")
  578. assert restored.id != 1
  579. assert restored.material == "PLA"
  580. @pytest.mark.asyncio
  581. async def test_matches_existing_spool_by_tag_uid(self, db_session):
  582. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  583. await db_session.commit()
  584. tally = _CategoryTally()
  585. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, False, tally, {})
  586. await db_session.commit()
  587. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  588. assert tally.skipped == 1
  589. @pytest.mark.asyncio
  590. async def test_matches_existing_spool_by_tray_uuid(self, db_session):
  591. db_session.add(Spool(material="PLA", tray_uuid="1234" * 8))
  592. await db_session.commit()
  593. tally = _CategoryTally()
  594. entry = self._spool_entry(tag_uid=None, tray_uuid="1234" * 8)
  595. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  596. await db_session.commit()
  597. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  598. assert tally.skipped == 1
  599. @pytest.mark.asyncio
  600. async def test_matches_tagless_spool_by_descriptive_composite(self, db_session):
  601. """Manually added spools have no tag, so fall back to created_at + description."""
  602. db_session.add(
  603. Spool(
  604. material="PLA",
  605. subtype="Basic",
  606. color_name="Jade White",
  607. brand="Bambu Lab",
  608. created_at=datetime(2026, 1, 5, 12, 0, 0),
  609. )
  610. )
  611. await db_session.commit()
  612. tally = _CategoryTally()
  613. entry = self._spool_entry(tag_uid=None)
  614. await _service()._restore_spools(db_session, {"spools": [entry]}, None, False, tally, {})
  615. await db_session.commit()
  616. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  617. assert tally.skipped == 1
  618. @pytest.mark.asyncio
  619. async def test_overwrite_updates_matched_spool(self, db_session):
  620. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old", weight_used=0))
  621. await db_session.commit()
  622. tally = _CategoryTally()
  623. await _service()._restore_spools(db_session, {"spools": [self._spool_entry()]}, None, True, tally, {})
  624. await db_session.commit()
  625. row = (await db_session.execute(select(Spool))).scalar_one()
  626. assert row.color_name == "Jade White"
  627. assert row.weight_used == 120.5
  628. assert tally.restored == 1
  629. @pytest.mark.asyncio
  630. async def test_insert_preserves_created_at_so_repeat_restore_is_idempotent(self, db_session):
  631. """Second restore of the same backup must match, not duplicate."""
  632. service = _service()
  633. payload = {"spools": [self._spool_entry(tag_uid=None)]}
  634. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  635. await db_session.commit()
  636. await service._restore_spools(db_session, payload, None, False, _CategoryTally(), {})
  637. await db_session.commit()
  638. spools = (await db_session.execute(select(Spool))).scalars().all()
  639. assert len(spools) == 1
  640. assert spools[0].created_at == datetime(2026, 1, 5, 12, 0, 0)
  641. @pytest.mark.asyncio
  642. async def test_usage_history_spool_id_is_remapped(self, db_session):
  643. """Usage rows must point at the new local spool id, not the backup's."""
  644. tally = _CategoryTally()
  645. inventory = {"spools": [self._spool_entry(id=41)]}
  646. usage = {
  647. "usage_history": [
  648. {
  649. "id": 900,
  650. "spool_id": 41,
  651. "printer_id": None,
  652. "print_name": "benchy.3mf",
  653. "archive_id": None,
  654. "weight_used": 12.0,
  655. "percent_used": 5,
  656. "status": "completed",
  657. "created_at": "2026-02-01 09:00:00",
  658. }
  659. ]
  660. }
  661. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  662. await db_session.commit()
  663. spool = (await db_session.execute(select(Spool))).scalar_one()
  664. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  665. assert row.spool_id == spool.id
  666. assert row.print_name == "benchy.3mf"
  667. @pytest.mark.asyncio
  668. async def test_usage_history_archive_id_is_remapped(self, db_session):
  669. tally = _CategoryTally()
  670. inventory = {"spools": [self._spool_entry(id=41)]}
  671. usage = {
  672. "usage_history": [
  673. {
  674. "spool_id": 41,
  675. "archive_id": 77,
  676. "weight_used": 1.0,
  677. "created_at": "2026-02-01 09:00:00",
  678. }
  679. ]
  680. }
  681. archive = PrintArchive(filename="a.3mf", file_path="", file_size=1)
  682. db_session.add(archive)
  683. await db_session.flush()
  684. await _service()._restore_spools(db_session, inventory, usage, False, tally, {77: archive.id})
  685. await db_session.commit()
  686. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  687. assert row.archive_id == archive.id
  688. @pytest.mark.asyncio
  689. async def test_usage_row_with_unresolvable_spool_is_skipped_and_explained(self, db_session):
  690. tally = _CategoryTally()
  691. usage = {"usage_history": [{"spool_id": 999, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}]}
  692. await _service()._restore_spools(db_session, {"spools": []}, usage, False, tally, {})
  693. await db_session.commit()
  694. assert (await db_session.execute(select(SpoolUsageHistory))).scalars().first() is None
  695. assert tally.skipped == 1
  696. assert any("their spool is not in this backup's spool list" in note for note in _messages(tally))
  697. # No remedy is offered, because none exists: overwrite does not change
  698. # which spools land in the map (a skipped spool is mapped anyway), and
  699. # usage history is always restored alongside the spools category.
  700. assert not any("overwrite" in note.lower() for note in _messages(tally))
  701. @pytest.mark.asyncio
  702. async def test_usage_resolves_against_a_spool_skipped_because_overwrite_is_off(self, db_session):
  703. """A skipped spool is still mapped, so its usage rows are not "unresolved".
  704. This is why the note above offers no remedy: turning overwrite on would
  705. not rescue anything, and saying so misdescribed which records are lost.
  706. """
  707. db_session.add(Spool(material="PLA", tag_uid="AABBCCDD", color_name="Old"))
  708. await db_session.commit()
  709. tally = _CategoryTally()
  710. inventory = {"spools": [self._spool_entry(id=41)]}
  711. usage = {
  712. "usage_history": [
  713. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  714. ]
  715. }
  716. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  717. await db_session.commit()
  718. spool = (await db_session.execute(select(Spool))).scalar_one()
  719. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  720. assert row.spool_id == spool.id
  721. assert not any("spool list" in note for note in _messages(tally))
  722. @pytest.mark.asyncio
  723. async def test_usage_history_is_not_duplicated_on_repeat_restore(self, db_session):
  724. service = _service()
  725. inventory = {"spools": [self._spool_entry(id=41)]}
  726. usage = {
  727. "usage_history": [
  728. {"spool_id": 41, "print_name": "b.3mf", "weight_used": 5.0, "created_at": "2026-02-01 09:00:00"}
  729. ]
  730. }
  731. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  732. await db_session.commit()
  733. await service._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  734. await db_session.commit()
  735. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  736. assert len(rows) == 1
  737. @pytest.mark.asyncio
  738. async def test_dropped_archive_link_is_explained(self, db_session):
  739. """Spools without archives nulls every usage -> archive link, silently."""
  740. tally = _CategoryTally()
  741. inventory = {"spools": [self._spool_entry(id=41)]}
  742. usage = {
  743. "usage_history": [
  744. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"},
  745. {"spool_id": 41, "archive_id": 8, "weight_used": 2.0, "created_at": "2026-02-01 10:00:00"},
  746. {"spool_id": 41, "weight_used": 3.0, "created_at": "2026-02-01 11:00:00"},
  747. ]
  748. }
  749. # Empty archive_id_map: the archives category wasn't selected, so its
  750. # payload was never fetched and there is nothing to match against.
  751. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  752. await db_session.commit()
  753. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  754. assert len(rows) == 3
  755. assert all(row.archive_id is None for row in rows)
  756. # Only the two that had a link to lose are counted.
  757. assert any("2 usage record(s) restored without their print-history link" in n for n in _messages(tally))
  758. assert any("select Print archives alongside" in n for n in _messages(tally))
  759. @pytest.mark.asyncio
  760. async def test_no_note_when_every_archive_link_resolves(self, db_session):
  761. tally = _CategoryTally()
  762. inventory = {"spools": [self._spool_entry(id=41)]}
  763. usage = {
  764. "usage_history": [
  765. {"spool_id": 41, "archive_id": 7, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  766. ]
  767. }
  768. archive = PrintArchive(filename="linked.3mf", file_path="", file_size=1)
  769. db_session.add(archive)
  770. await db_session.flush()
  771. await _service()._restore_spools(db_session, inventory, usage, False, tally, {7: archive.id})
  772. await db_session.commit()
  773. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  774. assert row.archive_id == archive.id
  775. assert not any("print-history link" in note for note in _messages(tally))
  776. @pytest.mark.asyncio
  777. async def test_dangling_printer_id_is_cleared(self, db_session):
  778. tally = _CategoryTally()
  779. inventory = {"spools": [self._spool_entry(id=41)]}
  780. usage = {
  781. "usage_history": [
  782. {"spool_id": 41, "printer_id": 4242, "weight_used": 1.0, "created_at": "2026-02-01 09:00:00"}
  783. ]
  784. }
  785. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  786. await db_session.commit()
  787. row = (await db_session.execute(select(SpoolUsageHistory))).scalar_one()
  788. assert row.printer_id is None
  789. class TestServerDefaultCreatedAtDedupe:
  790. """Dedupe against rows whose ``created_at`` came from the server default.
  791. Every test above seeds its "existing" row through the restore itself, which
  792. binds ``created_at`` explicitly — so both sides end up in SQLAlchemy's
  793. microsecond format and a SQL ``==`` matches. Rows the *application* created
  794. do not: SQLite fills ``server_default=func.now()`` from
  795. ``CURRENT_TIMESTAMP``, which has second precision, and the two strings
  796. never compare equal. That is the ordinary case — a user's own spools and
  797. their print history — and it duplicated the lot on every restore.
  798. """
  799. @staticmethod
  800. async def _native_spool(db_session, **kwargs):
  801. """A spool created the way the app creates one: no explicit created_at."""
  802. spool = Spool(material="PLA", brand="Bambu Lab", subtype="Basic", color_name="Jade White", **kwargs)
  803. db_session.add(spool)
  804. await db_session.commit()
  805. await db_session.refresh(spool)
  806. return spool
  807. def _entry_for(self, spool, **overrides):
  808. """The backup entry the collector writes for ``spool``."""
  809. entry = {
  810. "id": 41,
  811. "material": spool.material,
  812. "brand": spool.brand,
  813. "subtype": spool.subtype,
  814. "color_name": spool.color_name,
  815. "created_at": str(spool.created_at),
  816. }
  817. entry.update(overrides)
  818. return entry
  819. @pytest.mark.asyncio
  820. async def test_find_spool_matches_on_the_composite_fallback(self, db_session):
  821. spool = await self._native_spool(db_session)
  822. found, matched_on = await _service()._find_spool(db_session, self._entry_for(spool))
  823. assert found is not None and found.id == spool.id
  824. assert matched_on is None # the composite, not a tag column
  825. @pytest.mark.asyncio
  826. async def test_a_tagless_spool_is_not_duplicated(self, db_session):
  827. spool = await self._native_spool(db_session)
  828. payload = {"spools": [self._entry_for(spool)]}
  829. tally = _CategoryTally()
  830. await _service()._restore_spools(db_session, payload, None, False, tally, {})
  831. await db_session.commit()
  832. assert len((await db_session.execute(select(Spool))).scalars().all()) == 1
  833. assert tally.skipped == 1
  834. @pytest.mark.asyncio
  835. async def test_overwrite_updates_the_original_instead_of_inserting(self, db_session):
  836. spool = await self._native_spool(db_session)
  837. payload = {"spools": [self._entry_for(spool, weight_used=250.0)]}
  838. await _service()._restore_spools(db_session, payload, None, True, _CategoryTally(), {})
  839. await db_session.commit()
  840. row = (await db_session.execute(select(Spool))).scalar_one()
  841. assert row.id == spool.id
  842. assert row.weight_used == 250.0
  843. @pytest.mark.asyncio
  844. async def test_a_second_spool_added_later_stays_distinct(self, db_session):
  845. """The composite is only unique because of created_at, so the Python
  846. comparison has to stay exact — not a same-day tolerance."""
  847. spool = await self._native_spool(db_session)
  848. twin = Spool(material=spool.material, brand=spool.brand, subtype=spool.subtype, color_name=spool.color_name)
  849. twin.created_at = spool.created_at + timedelta(hours=1)
  850. db_session.add(twin)
  851. await db_session.commit()
  852. found, _ = await _service()._find_spool(db_session, self._entry_for(spool))
  853. assert found.id == spool.id
  854. @pytest.mark.asyncio
  855. async def test_existing_usage_history_is_not_re_inserted(self, db_session):
  856. spool = await self._native_spool(db_session, tag_uid="AABBCCDD")
  857. usage_row = SpoolUsageHistory(spool_id=spool.id, print_name="b.3mf", weight_used=5.0)
  858. db_session.add(usage_row)
  859. await db_session.commit()
  860. await db_session.refresh(usage_row)
  861. tally = _CategoryTally()
  862. inventory = {"spools": [self._entry_for(spool, tag_uid="AABBCCDD")]}
  863. usage = {
  864. "usage_history": [
  865. {
  866. "spool_id": 41,
  867. "print_name": "b.3mf",
  868. "weight_used": 5.0,
  869. "created_at": str(usage_row.created_at),
  870. }
  871. ]
  872. }
  873. await _service()._restore_spools(db_session, inventory, usage, False, tally, {})
  874. await db_session.commit()
  875. rows = (await db_session.execute(select(SpoolUsageHistory))).scalars().all()
  876. assert len(rows) == 1
  877. assert tally.skipped == 2 # the spool and its one usage row
  878. @pytest.mark.asyncio
  879. async def test_a_genuinely_new_usage_row_still_lands(self, db_session):
  880. """Dedupe by timestamp must not swallow a repeat of the same print."""
  881. spool = await self._native_spool(db_session, tag_uid="AABBCCDD")
  882. usage_row = SpoolUsageHistory(spool_id=spool.id, print_name="b.3mf", weight_used=5.0)
  883. db_session.add(usage_row)
  884. await db_session.commit()
  885. await db_session.refresh(usage_row)
  886. inventory = {"spools": [self._entry_for(spool, tag_uid="AABBCCDD")]}
  887. usage = {
  888. "usage_history": [
  889. {
  890. "spool_id": 41,
  891. "print_name": "b.3mf",
  892. "weight_used": 5.0,
  893. "created_at": str(usage_row.created_at + timedelta(days=1)),
  894. }
  895. ]
  896. }
  897. await _service()._restore_spools(db_session, inventory, usage, False, _CategoryTally(), {})
  898. await db_session.commit()
  899. assert len((await db_session.execute(select(SpoolUsageHistory))).scalars().all()) == 2
  900. class TestRestoreArchives:
  901. def _archive_entry(self, **overrides):
  902. entry = {
  903. "id": 77,
  904. "filename": "benchy.3mf",
  905. "file_size": 2048,
  906. "content_hash": "abc123",
  907. "print_name": "Benchy",
  908. "status": "completed",
  909. "started_at": "2026-03-01 10:00:00",
  910. "completed_at": "2026-03-01 11:00:00",
  911. "created_at": "2026-03-01 10:00:00",
  912. "quantity": 1,
  913. "is_favorite": False,
  914. }
  915. entry.update(overrides)
  916. return entry
  917. @pytest.mark.asyncio
  918. async def test_inserts_metadata_only_row_with_empty_file_path(self, db_session):
  919. """print_archives.file_path is NOT NULL but is not in the backup."""
  920. tally = _CategoryTally()
  921. id_map: dict[int, int] = {}
  922. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, id_map)
  923. await db_session.commit()
  924. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  925. assert row.file_path == ""
  926. assert row.filename == "benchy.3mf"
  927. assert row.id != 77
  928. assert id_map == {77: row.id}
  929. assert any("metadata only" in note for note in _messages(tally))
  930. @pytest.mark.asyncio
  931. async def test_matches_existing_archive_by_hash_and_start(self, db_session):
  932. db_session.add(
  933. PrintArchive(
  934. filename="benchy.3mf",
  935. file_path="/data/benchy.3mf",
  936. file_size=2048,
  937. content_hash="abc123",
  938. started_at=datetime(2026, 3, 1, 10, 0, 0),
  939. )
  940. )
  941. await db_session.commit()
  942. tally = _CategoryTally()
  943. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  944. await db_session.commit()
  945. rows = (await db_session.execute(select(PrintArchive))).scalars().all()
  946. assert len(rows) == 1
  947. assert rows[0].file_path == "/data/benchy.3mf"
  948. assert tally.skipped == 1
  949. @pytest.mark.asyncio
  950. async def test_falls_back_to_filename_and_start_without_hash(self, db_session):
  951. db_session.add(
  952. PrintArchive(
  953. filename="benchy.3mf",
  954. file_path="/data/benchy.3mf",
  955. file_size=2048,
  956. started_at=datetime(2026, 3, 1, 10, 0, 0),
  957. )
  958. )
  959. await db_session.commit()
  960. tally = _CategoryTally()
  961. entry = self._archive_entry(content_hash=None)
  962. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  963. await db_session.commit()
  964. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  965. assert tally.skipped == 1
  966. @pytest.mark.asyncio
  967. async def test_matches_archive_with_no_started_at_by_hash(self, db_session):
  968. """started_at is NULL for re-sliced archives, so it cannot be required.
  969. Gating both match branches on it meant these rows never matched: every
  970. restore re-inserted them and overwrite mode could never update them.
  971. """
  972. db_session.add(
  973. PrintArchive(
  974. filename="benchy.3mf",
  975. file_path="/data/benchy.3mf",
  976. file_size=2048,
  977. content_hash="abc123",
  978. started_at=None,
  979. )
  980. )
  981. await db_session.commit()
  982. tally = _CategoryTally()
  983. entry = self._archive_entry(started_at=None)
  984. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  985. await db_session.commit()
  986. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 1
  987. assert tally.skipped == 1
  988. @pytest.mark.asyncio
  989. async def test_started_at_still_discriminates_when_present(self, db_session):
  990. """A NULL-tolerant match must not collapse rows that do differ."""
  991. db_session.add(
  992. PrintArchive(
  993. filename="benchy.3mf",
  994. file_path="/data/benchy.3mf",
  995. file_size=2048,
  996. content_hash="abc123",
  997. started_at=datetime(2026, 3, 1, 10, 0, 0),
  998. )
  999. )
  1000. await db_session.commit()
  1001. tally = _CategoryTally()
  1002. # Same file, no start time recorded — a different row, not that one.
  1003. entry = self._archive_entry(started_at=None)
  1004. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1005. await db_session.commit()
  1006. assert len((await db_session.execute(select(PrintArchive))).scalars().all()) == 2
  1007. assert tally.restored == 1
  1008. @pytest.mark.asyncio
  1009. async def test_soft_deleted_archive_is_not_restored_as_visible(self, db_session):
  1010. """A backup keeps soft-deleted rows, so the flag has to survive.
  1011. Their row is retained on purpose (stats keep counting the filament and
  1012. energy), so without carrying deleted_at a restore turns an archive the
  1013. user deleted back into a visible one.
  1014. """
  1015. tally = _CategoryTally()
  1016. entry = self._archive_entry(deleted_at="2026-03-02 08:00:00")
  1017. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1018. await db_session.commit()
  1019. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1020. assert row.deleted_at == datetime(2026, 3, 2, 8, 0, 0)
  1021. assert tally.restored == 1
  1022. @pytest.mark.asyncio
  1023. async def test_locally_deleted_archive_stays_deleted_without_overwrite(self, db_session):
  1024. db_session.add(
  1025. PrintArchive(
  1026. filename="benchy.3mf",
  1027. file_path="",
  1028. file_size=2048,
  1029. content_hash="abc123",
  1030. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1031. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  1032. )
  1033. )
  1034. await db_session.commit()
  1035. tally = _CategoryTally()
  1036. # The backup predates the deletion, so its copy is live.
  1037. await _service()._restore_archives(db_session, {"archives": [self._archive_entry()]}, False, tally, {})
  1038. await db_session.commit()
  1039. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1040. assert row.deleted_at == datetime(2026, 3, 5, 9, 0, 0)
  1041. assert tally.skipped == 1
  1042. @pytest.mark.asyncio
  1043. async def test_overwrite_undeletes_a_locally_deleted_archive_and_says_so(self, db_session):
  1044. """The entry has to *say* the archive was live — absent no longer means null.
  1045. A commit taken before the collector wrote ``deleted_at`` carries no
  1046. opinion about it, and overwrite now leaves the column alone in that
  1047. case; see ``TestRestoredArchiveOwnership``.
  1048. """
  1049. db_session.add(
  1050. PrintArchive(
  1051. filename="benchy.3mf",
  1052. file_path="",
  1053. file_size=2048,
  1054. content_hash="abc123",
  1055. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1056. deleted_at=datetime(2026, 3, 5, 9, 0, 0),
  1057. )
  1058. )
  1059. await db_session.commit()
  1060. tally = _CategoryTally()
  1061. await _service()._restore_archives(
  1062. db_session, {"archives": [self._archive_entry(deleted_at=None)]}, True, tally, {}
  1063. )
  1064. await db_session.commit()
  1065. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1066. assert row.deleted_at is None
  1067. assert tally.restored == 1
  1068. assert any("visible again" in note for note in _messages(tally))
  1069. @pytest.mark.asyncio
  1070. async def test_overwrite_updates_metadata_but_keeps_local_file_path(self, db_session):
  1071. db_session.add(
  1072. PrintArchive(
  1073. filename="benchy.3mf",
  1074. file_path="/data/benchy.3mf",
  1075. file_size=2048,
  1076. content_hash="abc123",
  1077. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1078. notes="old",
  1079. )
  1080. )
  1081. await db_session.commit()
  1082. tally = _CategoryTally()
  1083. entry = self._archive_entry(notes="restored note")
  1084. await _service()._restore_archives(db_session, {"archives": [entry]}, True, tally, {})
  1085. await db_session.commit()
  1086. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1087. assert row.notes == "restored note"
  1088. # The 3MF on disk must not be orphaned by a metadata restore.
  1089. assert row.file_path == "/data/benchy.3mf"
  1090. assert tally.restored == 1
  1091. @pytest.mark.asyncio
  1092. async def test_dangling_printer_and_project_links_are_cleared(self, db_session):
  1093. tally = _CategoryTally()
  1094. entry = self._archive_entry(printer_id=4242, project_id=4343)
  1095. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1096. await db_session.commit()
  1097. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1098. assert row.printer_id is None
  1099. assert row.project_id is None
  1100. assert any("no longer exist" in note for note in _messages(tally))
  1101. @pytest.mark.asyncio
  1102. async def test_valid_printer_link_is_preserved(self, db_session, printer_factory):
  1103. printer = await printer_factory()
  1104. tally = _CategoryTally()
  1105. entry = self._archive_entry(printer_id=printer.id)
  1106. await _service()._restore_archives(db_session, {"archives": [entry]}, False, tally, {})
  1107. await db_session.commit()
  1108. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1109. assert row.printer_id == printer.id
  1110. @pytest.mark.asyncio
  1111. async def test_non_dict_entry_counts_as_failed(self, db_session):
  1112. tally = _CategoryTally()
  1113. await _service()._restore_archives(db_session, {"archives": ["nonsense"]}, False, tally, {})
  1114. assert tally.failed == 1
  1115. class TestRestoreKprofiles:
  1116. @staticmethod
  1117. def _live(slot_id, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123", extruder_id=0):
  1118. """One profile as the printer currently reports it.
  1119. ``extruder_id`` mirrors ``KProfile`` (bambu_mqtt.py), which has carried
  1120. it all along; single-nozzle printers report 0.
  1121. """
  1122. return SimpleNamespace(
  1123. slot_id=slot_id,
  1124. filament_id=filament_id,
  1125. name=name,
  1126. setting_id=setting_id,
  1127. extruder_id=extruder_id,
  1128. )
  1129. def _client(self, live=None, sent="7", ack=(True, "")):
  1130. """A connected printer client.
  1131. ``set_kprofiles_batch`` returns the sequence_id it published under, not
  1132. a success flag (#2718), and the verdict arrives separately from
  1133. ``await_cali_ack`` as ``(ok, detail)``.
  1134. """
  1135. client = MagicMock()
  1136. client.state.connected = True
  1137. client.set_kprofiles_batch = MagicMock(return_value=sent)
  1138. client.await_cali_ack = AsyncMock(return_value=ack)
  1139. client.get_kprofiles = AsyncMock(return_value=list(live or []))
  1140. return client
  1141. def _payload(self, serial="00M09A123456789", nozzle="0.4"):
  1142. return {
  1143. f"kprofiles/{serial}/{nozzle}.json": {
  1144. "version": "1.0",
  1145. "printer_serial": serial,
  1146. "nozzle_diameter": nozzle,
  1147. "profiles": [
  1148. {
  1149. "slot_id": 0,
  1150. "name": "Bambu PLA",
  1151. "k_value": "0.020000",
  1152. "filament_id": "GFA00",
  1153. "nozzle_id": "HS00-0.4",
  1154. "extruder_id": 0,
  1155. "setting_id": "PFUS123",
  1156. }
  1157. ],
  1158. }
  1159. }
  1160. @pytest.mark.asyncio
  1161. async def test_sends_batch_to_connected_printer(self, db_session, printer_factory):
  1162. printer = await printer_factory(serial_number="00M09A123456789")
  1163. client = self._client()
  1164. tally = _CategoryTally()
  1165. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1166. manager.get_client = MagicMock(return_value=client)
  1167. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1168. client.set_kprofiles_batch.assert_called_once()
  1169. profiles, nozzle = client.set_kprofiles_batch.call_args.args
  1170. assert nozzle == "0.4"
  1171. assert profiles[0]["name"] == "Bambu PLA"
  1172. assert profiles[0]["filament_id"] == "GFA00"
  1173. assert tally.restored == 1
  1174. assert manager.get_client.call_args.args == (printer.id,)
  1175. @pytest.mark.asyncio
  1176. async def test_always_warns_to_verify_on_the_printer(self, db_session, printer_factory):
  1177. await printer_factory(serial_number="00M09A123456789")
  1178. client = self._client()
  1179. tally = _CategoryTally()
  1180. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1181. manager.get_client = MagicMock(return_value=client)
  1182. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1183. # A refusal is now read and counted failed, so the caveat is narrowed to
  1184. # what is genuinely left uncertain: a printer that never answers.
  1185. assert any("verify the profiles on the printer" in note for note in _messages(tally))
  1186. assert any("does not answer still counts as restored" in note for note in _messages(tally))
  1187. assert not any("without acknowledgement" in note for note in _messages(tally))
  1188. assert any("always overwrite" in note for note in _messages(tally))
  1189. # --- cali_idx is resolved live, never taken from the backup -------------
  1190. #
  1191. # Regression cover for the silent no-op found testing on an X1E: the backup
  1192. # stored cali_idx 8151, a Bambuddy edit re-keyed the profile to 4606, and
  1193. # the restore aimed extrusion_cali_set at 8151. The printer dropped it and
  1194. # the tally still said "1 restored".
  1195. @pytest.mark.asyncio
  1196. async def test_uses_the_live_cali_idx_not_the_backed_up_slot(self, db_session, printer_factory):
  1197. await printer_factory(serial_number="00M09A123456789")
  1198. payload = self._payload()
  1199. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]["slot_id"] = 8151
  1200. client = self._client(live=[self._live(slot_id=4606)])
  1201. tally = _CategoryTally()
  1202. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1203. manager.get_client = MagicMock(return_value=client)
  1204. await _service()._restore_kprofiles(db_session, payload, tally)
  1205. client.get_kprofiles.assert_awaited_once_with(nozzle_diameter="0.4")
  1206. profiles, _ = client.set_kprofiles_batch.call_args.args
  1207. assert profiles[0]["cali_idx"] == 4606, "must address the slot that exists now"
  1208. assert profiles[0]["cali_idx"] != 8151, "must not reuse the backup's cali_idx"
  1209. assert tally.restored == 1
  1210. @pytest.mark.asyncio
  1211. async def test_matches_on_name_when_setting_id_was_regenerated(self, db_session, printer_factory):
  1212. # A delete-then-add edit mints a fresh setting_id, so the name carries
  1213. # the match instead.
  1214. await printer_factory(serial_number="00M09A123456789")
  1215. client = self._client(live=[self._live(slot_id=4606, setting_id="PF9999999999")])
  1216. tally = _CategoryTally()
  1217. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1218. manager.get_client = MagicMock(return_value=client)
  1219. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1220. profiles, _ = client.set_kprofiles_batch.call_args.args
  1221. assert profiles[0]["cali_idx"] == 4606
  1222. # The live setting_id wins: it is what the printer associates with the slot.
  1223. assert profiles[0]["setting_id"] == "PF9999999999"
  1224. @pytest.mark.asyncio
  1225. async def test_unmatched_profile_is_added_rather_than_aimed_at_a_dead_slot(self, db_session, printer_factory):
  1226. await printer_factory(serial_number="00M09A123456789")
  1227. client = self._client(live=[]) # printer has nothing for this nozzle
  1228. tally = _CategoryTally()
  1229. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1230. manager.get_client = MagicMock(return_value=client)
  1231. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1232. profiles, _ = client.set_kprofiles_batch.call_args.args
  1233. assert profiles[0]["cali_idx"] == -1, "-1 tells the printer to add a new profile"
  1234. assert profiles[0]["setting_id"] == "PFUS123", "falls back to the backed-up preset"
  1235. assert any("added as new profiles" in note for note in _messages(tally))
  1236. @pytest.mark.asyncio
  1237. async def test_different_filament_is_not_treated_as_a_match(self, db_session, printer_factory):
  1238. # Same slot, different filament — matching on slot alone would clobber
  1239. # an unrelated profile.
  1240. await printer_factory(serial_number="00M09A123456789")
  1241. client = self._client(live=[self._live(slot_id=4606, filament_id="GFB99", name="Bambu PLA")])
  1242. tally = _CategoryTally()
  1243. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1244. manager.get_client = MagicMock(return_value=client)
  1245. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1246. profiles, _ = client.set_kprofiles_batch.call_args.args
  1247. assert profiles[0]["cali_idx"] == -1
  1248. @pytest.mark.asyncio
  1249. async def test_unreadable_live_index_degrades_to_adding(self, db_session, printer_factory):
  1250. # A failed read must not abort the restore.
  1251. await printer_factory(serial_number="00M09A123456789")
  1252. client = self._client()
  1253. client.get_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt timeout"))
  1254. tally = _CategoryTally()
  1255. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1256. manager.get_client = MagicMock(return_value=client)
  1257. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1258. profiles, _ = client.set_kprofiles_batch.call_args.args
  1259. assert profiles[0]["cali_idx"] == -1
  1260. assert tally.restored == 1
  1261. @pytest.mark.asyncio
  1262. async def test_sole_profile_for_a_filament_matches_without_setting_id_or_name(self, db_session, printer_factory):
  1263. await printer_factory(serial_number="00M09A123456789")
  1264. payload = self._payload()
  1265. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  1266. entry["setting_id"] = None
  1267. entry["name"] = ""
  1268. client = self._client(live=[self._live(slot_id=4606, setting_id="PFOTHER", name="Renamed")])
  1269. tally = _CategoryTally()
  1270. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1271. manager.get_client = MagicMock(return_value=client)
  1272. await _service()._restore_kprofiles(db_session, payload, tally)
  1273. profiles, _ = client.set_kprofiles_batch.call_args.args
  1274. assert profiles[0]["cali_idx"] == 4606
  1275. @pytest.mark.asyncio
  1276. async def test_ambiguous_filament_without_discriminator_is_added_not_guessed(self, db_session, printer_factory):
  1277. await printer_factory(serial_number="00M09A123456789")
  1278. payload = self._payload()
  1279. entry = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0]
  1280. entry["setting_id"] = None
  1281. entry["name"] = ""
  1282. client = self._client(live=[self._live(slot_id=1, setting_id="A"), self._live(slot_id=2, setting_id="B")])
  1283. tally = _CategoryTally()
  1284. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1285. manager.get_client = MagicMock(return_value=client)
  1286. await _service()._restore_kprofiles(db_session, payload, tally)
  1287. profiles, _ = client.set_kprofiles_batch.call_args.args
  1288. assert profiles[0]["cali_idx"] == -1, "two candidates and nothing to tell them apart"
  1289. @pytest.mark.asyncio
  1290. async def test_two_entries_cannot_claim_the_same_live_slot(self, db_session, printer_factory):
  1291. """One live profile cannot stand in for two backed-up ones (#2656).
  1292. Both entries fell through to the single-candidate arm, both took
  1293. cali_idx 4606, both went into the batch — so the second overwrote the
  1294. first on the printer while the tally counted two restored. Reachable
  1295. whenever the user has deleted one of a pair since the backup, because
  1296. the delete-then-add re-key is what strips the setting_id match.
  1297. """
  1298. await printer_factory(serial_number="00M09A123456789")
  1299. payload = self._payload()
  1300. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1301. entries[0].update(setting_id="PFGONE1", name="PLA Basic")
  1302. entries.append({**entries[0], "setting_id": "PFGONE2", "name": "PLA Matte"})
  1303. client = self._client(live=[self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA")])
  1304. tally = _CategoryTally()
  1305. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1306. manager.get_client = MagicMock(return_value=client)
  1307. await _service()._restore_kprofiles(db_session, payload, tally)
  1308. profiles, _ = client.set_kprofiles_batch.call_args.args
  1309. assert [p["cali_idx"] for p in profiles] == [4606, -1], "the displaced entry has to be added, not aliased"
  1310. assert sum(1 for p in profiles if p["cali_idx"] == 4606) == 1
  1311. assert any("added as new profiles" in note for note in _messages(tally))
  1312. @pytest.mark.asyncio
  1313. async def test_the_displaced_entry_does_not_inherit_the_claimed_setting_id(self, db_session, printer_factory):
  1314. """An add-as-new keeps its own preset, or it lands on top of the match anyway.
  1315. cali_idx -1 is only safe if the rest of the payload doesn't point at the
  1316. profile the first entry just claimed — the generated-setting_id fallback
  1317. reads setting_id when cali_idx is -1.
  1318. """
  1319. await printer_factory(serial_number="00M09A123456789")
  1320. payload = self._payload()
  1321. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1322. entries[0].update(setting_id="PFGONE1", name="PLA Basic")
  1323. entries.append({**entries[0], "setting_id": "PFGONE2", "name": "PLA Matte"})
  1324. client = self._client(live=[self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA")])
  1325. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1326. manager.get_client = MagicMock(return_value=client)
  1327. await _service()._restore_kprofiles(db_session, payload, _CategoryTally())
  1328. profiles, _ = client.set_kprofiles_batch.call_args.args
  1329. assert profiles[0]["setting_id"] == "PFUS123", "the match prefers the live preset"
  1330. assert profiles[1]["setting_id"] == "PFGONE2", "the displaced entry keeps its own"
  1331. @pytest.mark.asyncio
  1332. async def test_two_entries_matching_two_live_profiles_keep_their_own_slots(self, db_session, printer_factory):
  1333. """Control: the guard must not displace a legitimate second match."""
  1334. await printer_factory(serial_number="00M09A123456789")
  1335. payload = self._payload()
  1336. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1337. entries.append({**entries[0], "setting_id": "PFUS456", "name": "Bambu PETG"})
  1338. client = self._client(
  1339. live=[
  1340. self._live(slot_id=4606, setting_id="PFUS123", name="Bambu PLA"),
  1341. self._live(slot_id=4607, setting_id="PFUS456", name="Bambu PETG"),
  1342. ]
  1343. )
  1344. tally = _CategoryTally()
  1345. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1346. manager.get_client = MagicMock(return_value=client)
  1347. await _service()._restore_kprofiles(db_session, payload, tally)
  1348. profiles, _ = client.set_kprofiles_batch.call_args.args
  1349. assert [p["cali_idx"] for p in profiles] == [4606, 4607]
  1350. assert not any("added as new profiles" in note for note in _messages(tally))
  1351. @pytest.mark.asyncio
  1352. async def test_a_claimed_slot_does_not_make_an_ambiguous_pair_matchable(self, db_session, printer_factory):
  1353. """Two live profiles for one filament stay ambiguous after one is taken.
  1354. The single-candidate fallback is judged against every candidate, not the
  1355. unclaimed ones — otherwise claiming the first would leave exactly one
  1356. "available" and turn a guess the code deliberately refuses into a match.
  1357. """
  1358. await printer_factory(serial_number="00M09A123456789")
  1359. payload = self._payload()
  1360. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1361. entries[0].update(setting_id="PFUS123", name="Bambu PLA")
  1362. entries.append({**entries[0], "setting_id": None, "name": ""})
  1363. client = self._client(
  1364. live=[
  1365. self._live(slot_id=1, setting_id="PFUS123", name="Bambu PLA"),
  1366. self._live(slot_id=2, setting_id="PFOTHER", name="Renamed"),
  1367. ]
  1368. )
  1369. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1370. manager.get_client = MagicMock(return_value=client)
  1371. await _service()._restore_kprofiles(db_session, payload, _CategoryTally())
  1372. profiles, _ = client.set_kprofiles_batch.call_args.args
  1373. assert [p["cali_idx"] for p in profiles] == [1, -1]
  1374. # --- the match is scoped to the extruder it was calibrated on -----------
  1375. #
  1376. # get_kprofiles reads per nozzle *diameter*, so on a dual-nozzle printer
  1377. # both extruders come back in one list. Scoping candidates on filament_id
  1378. # alone let one extruder's calibration be written over the other's.
  1379. @pytest.mark.asyncio
  1380. async def test_each_extruders_profile_lands_on_its_own_extruder(self, db_session, printer_factory):
  1381. """The same preset calibrated on both extruders of an H2D.
  1382. Both live profiles share a filament_id *and* a setting_id, so the
  1383. setting_id arm matched whichever the printer happened to list first —
  1384. and with an entry per extruder the two swapped slots, each overwriting
  1385. the other's calibration while the tally counted both restored.
  1386. """
  1387. await printer_factory(serial_number="00M09A123456789")
  1388. payload = self._payload()
  1389. entries = payload["kprofiles/00M09A123456789/0.4.json"]["profiles"]
  1390. entries.append({**entries[0], "extruder_id": 1, "nozzle_id": "HS00-0.4-R"})
  1391. client = self._client(
  1392. live=[
  1393. # Right extruder first, which is what made the bug bite.
  1394. self._live(slot_id=1001, extruder_id=1),
  1395. self._live(slot_id=1000, extruder_id=0),
  1396. ]
  1397. )
  1398. tally = _CategoryTally()
  1399. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1400. manager.get_client = MagicMock(return_value=client)
  1401. await _service()._restore_kprofiles(db_session, payload, tally)
  1402. profiles, _ = client.set_kprofiles_batch.call_args.args
  1403. assert [(p["extruder_id"], p["cali_idx"]) for p in profiles] == [(0, 1000), (1, 1001)]
  1404. assert tally.restored == 2
  1405. assert not any("added as new profiles" in note for note in _messages(tally))
  1406. @pytest.mark.asyncio
  1407. async def test_the_other_extruders_profile_is_not_a_candidate(self, db_session, printer_factory):
  1408. """One backed-up entry, and the only live profile is the other extruder's.
  1409. Adding as new is the right answer: extruder 0's calibration is not a
  1410. stand-in for extruder 1's, however well the filament and preset line up.
  1411. """
  1412. await printer_factory(serial_number="00M09A123456789")
  1413. client = self._client(live=[self._live(slot_id=1001, extruder_id=1)])
  1414. tally = _CategoryTally()
  1415. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1416. manager.get_client = MagicMock(return_value=client)
  1417. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1418. profiles, _ = client.set_kprofiles_batch.call_args.args
  1419. assert profiles[0]["cali_idx"] == -1
  1420. assert any("added as new profiles" in note for note in _messages(tally))
  1421. @pytest.mark.asyncio
  1422. async def test_an_entry_without_an_extruder_id_still_matches(self, db_session, printer_factory):
  1423. """Control: a pre-#2656 backup carries no extruder_id.
  1424. A missing key must leave the match exactly as it was, not turn every
  1425. entry into an add.
  1426. """
  1427. await printer_factory(serial_number="00M09A123456789")
  1428. payload = self._payload()
  1429. payload["kprofiles/00M09A123456789/0.4.json"]["profiles"][0].pop("extruder_id")
  1430. client = self._client(live=[self._live(slot_id=4606)])
  1431. tally = _CategoryTally()
  1432. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1433. manager.get_client = MagicMock(return_value=client)
  1434. await _service()._restore_kprofiles(db_session, payload, tally)
  1435. profiles, _ = client.set_kprofiles_batch.call_args.args
  1436. assert profiles[0]["cali_idx"] == 4606
  1437. assert tally.restored == 1
  1438. @pytest.mark.asyncio
  1439. async def test_a_live_index_that_reports_no_extruder_still_matches(self, db_session, printer_factory):
  1440. """Control: the same, for a printer whose profiles carry no extruder_id."""
  1441. await printer_factory(serial_number="00M09A123456789")
  1442. live = SimpleNamespace(slot_id=4606, filament_id="GFA00", name="Bambu PLA", setting_id="PFUS123")
  1443. client = self._client(live=[live])
  1444. tally = _CategoryTally()
  1445. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1446. manager.get_client = MagicMock(return_value=client)
  1447. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1448. profiles, _ = client.set_kprofiles_batch.call_args.args
  1449. assert profiles[0]["cali_idx"] == 4606
  1450. assert tally.restored == 1
  1451. @pytest.mark.asyncio
  1452. async def test_unknown_serial_is_skipped_with_reason(self, db_session):
  1453. tally = _CategoryTally()
  1454. with patch("backend.app.services.github_restore.printer_manager"):
  1455. await _service()._restore_kprofiles(db_session, self._payload(serial="NOSUCH"), tally)
  1456. assert tally.restored == 0
  1457. assert tally.skipped == 1
  1458. assert any("No printer with serial NOSUCH" in note for note in _messages(tally))
  1459. @pytest.mark.asyncio
  1460. async def test_offline_printer_is_skipped_not_failed(self, db_session, printer_factory):
  1461. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  1462. client = MagicMock()
  1463. client.state.connected = False
  1464. tally = _CategoryTally()
  1465. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1466. manager.get_client = MagicMock(return_value=client)
  1467. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1468. assert tally.skipped == 1
  1469. assert tally.failed == 0
  1470. assert any("not connected" in note for note in _messages(tally))
  1471. @pytest.mark.asyncio
  1472. async def test_no_client_at_all_is_skipped(self, db_session, printer_factory):
  1473. await printer_factory(serial_number="00M09A123456789")
  1474. tally = _CategoryTally()
  1475. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1476. manager.get_client = MagicMock(return_value=None)
  1477. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1478. assert tally.skipped == 1
  1479. @pytest.mark.asyncio
  1480. async def test_publish_failure_counts_as_failed(self, db_session, printer_factory):
  1481. # None is what set_kprofiles_batch returns when it could not publish —
  1482. # a disconnected client. There is no ack to wait for in that case.
  1483. await printer_factory(serial_number="00M09A123456789")
  1484. client = self._client(sent=None)
  1485. tally = _CategoryTally()
  1486. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1487. manager.get_client = MagicMock(return_value=client)
  1488. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1489. assert tally.failed == 1
  1490. assert tally.restored == 0
  1491. assert "kprofilesSendFailed" in _codes(tally)
  1492. assert "kprofilesRefused" not in _codes(tally), "nothing was sent, so the printer refused nothing"
  1493. client.await_cali_ack.assert_not_awaited()
  1494. @pytest.mark.asyncio
  1495. async def test_publish_exception_is_contained(self, db_session, printer_factory):
  1496. await printer_factory(serial_number="00M09A123456789")
  1497. client = MagicMock()
  1498. client.state.connected = True
  1499. client.set_kprofiles_batch = MagicMock(side_effect=RuntimeError("mqtt down"))
  1500. tally = _CategoryTally()
  1501. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1502. manager.get_client = MagicMock(return_value=client)
  1503. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1504. assert tally.failed == 1
  1505. # --- the printer's verdict decides the tally, not the publish ------------
  1506. #
  1507. # #2718 changed set_kprofiles_batch from returning a bool to returning the
  1508. # sequence_id it published under. A sequence_id string is truthy, so a
  1509. # restore that branches on the return value alone reports every refused
  1510. # write as saved — the defect that fix closed in every other caller.
  1511. @pytest.mark.asyncio
  1512. async def test_awaits_the_ack_for_the_sequence_id_it_was_given(self, db_session, printer_factory):
  1513. await printer_factory(serial_number="00M09A123456789")
  1514. client = self._client(sent="4211")
  1515. tally = _CategoryTally()
  1516. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1517. manager.get_client = MagicMock(return_value=client)
  1518. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1519. client.await_cali_ack.assert_awaited_once_with("4211")
  1520. assert tally.restored == 1
  1521. @pytest.mark.asyncio
  1522. async def test_a_refused_batch_counts_failed_not_restored(self, db_session, printer_factory):
  1523. await printer_factory(serial_number="00M09A123456789", name="Shelf Printer")
  1524. client = self._client(ack=(False, "invalid tray_id"))
  1525. tally = _CategoryTally()
  1526. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1527. manager.get_client = MagicMock(return_value=client)
  1528. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1529. assert tally.restored == 0
  1530. assert tally.failed == 1
  1531. assert "kprofilesRefused" in _codes(tally)
  1532. assert "kprofilesSendFailed" not in _codes(tally), "it was sent — the printer answered no"
  1533. note = next(n for n in tally.notes if n["code"] == "kprofilesRefused")
  1534. assert note["params"]["reason"] == "invalid tray_id", "the printer's own reason has to survive"
  1535. assert "Shelf Printer" in note["message"] and "invalid tray_id" in note["message"]
  1536. @pytest.mark.asyncio
  1537. async def test_a_silent_printer_still_counts_restored(self, db_session, printer_factory):
  1538. # maziggy's rule, and await_cali_ack's own contract: no answer is not
  1539. # evidence of refusal. Firmware that predates the ack never answers.
  1540. await printer_factory(serial_number="00M09A123456789")
  1541. client = self._client(ack=(True, "no acknowledgement from printer"))
  1542. tally = _CategoryTally()
  1543. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1544. manager.get_client = MagicMock(return_value=client)
  1545. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1546. assert tally.restored == 1
  1547. assert tally.failed == 0
  1548. assert "kprofilesRefused" not in _codes(tally)
  1549. @pytest.mark.asyncio
  1550. async def test_an_unreadable_ack_does_not_fail_the_batch(self, db_session, printer_factory):
  1551. # Same situation one layer up: the write most likely landed, so this
  1552. # degrades the way a timeout does rather than inventing a failure.
  1553. await printer_factory(serial_number="00M09A123456789")
  1554. client = self._client()
  1555. client.await_cali_ack = AsyncMock(side_effect=RuntimeError("mqtt down"))
  1556. tally = _CategoryTally()
  1557. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1558. manager.get_client = MagicMock(return_value=client)
  1559. await _service()._restore_kprofiles(db_session, self._payload(), tally)
  1560. assert tally.restored == 1
  1561. assert tally.failed == 0
  1562. @pytest.mark.asyncio
  1563. async def test_one_refused_nozzle_does_not_condemn_the_other(self, db_session, printer_factory):
  1564. await printer_factory(serial_number="00M09A123456789")
  1565. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  1566. client = self._client()
  1567. client.await_cali_ack = AsyncMock(side_effect=[(False, "busy"), (True, "")])
  1568. tally = _CategoryTally()
  1569. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1570. manager.get_client = MagicMock(return_value=client)
  1571. await _service()._restore_kprofiles(db_session, payload, tally)
  1572. assert tally.restored == 1
  1573. assert tally.failed == 1
  1574. @pytest.mark.asyncio
  1575. async def test_each_nozzle_is_sent_separately(self, db_session, printer_factory):
  1576. await printer_factory(serial_number="00M09A123456789")
  1577. payload = {**self._payload(nozzle="0.4"), **self._payload(nozzle="0.8")}
  1578. client = self._client()
  1579. tally = _CategoryTally()
  1580. with patch("backend.app.services.github_restore.printer_manager") as manager:
  1581. manager.get_client = MagicMock(return_value=client)
  1582. await _service()._restore_kprofiles(db_session, payload, tally)
  1583. assert client.set_kprofiles_batch.call_count == 2
  1584. assert {c.args[1] for c in client.set_kprofiles_batch.call_args_list} == {"0.4", "0.8"}
  1585. assert tally.restored == 2
  1586. @pytest.mark.asyncio
  1587. async def test_empty_payload_is_noted(self, db_session):
  1588. tally = _CategoryTally()
  1589. await _service()._restore_kprofiles(db_session, {}, tally)
  1590. assert _codes(tally) == ["noData"]
  1591. class TestSoftDeletedArchiveRoundTrip:
  1592. """The two halves of the soft-delete fix only work together.
  1593. The collector keeps soft-deleted rows on purpose (their stats still count),
  1594. so if it doesn't write ``deleted_at`` there is nothing for the restore to
  1595. carry across and a deleted archive comes back visible. Covered end to end
  1596. because each half looks harmless on its own.
  1597. """
  1598. @pytest.mark.asyncio
  1599. async def test_deleted_at_survives_collect_then_restore(self, db_session):
  1600. from backend.app.services.github_backup import github_backup_service
  1601. deleted_at = datetime(2026, 3, 5, 9, 0, 0)
  1602. db_session.add(
  1603. PrintArchive(
  1604. filename="trashed.3mf",
  1605. file_path="",
  1606. file_size=1024,
  1607. content_hash="hash-trashed",
  1608. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1609. deleted_at=deleted_at,
  1610. )
  1611. )
  1612. await db_session.commit()
  1613. files: dict = {}
  1614. await github_backup_service._collect_archives(db_session, files)
  1615. payload = files[ARCHIVES_PATH]
  1616. assert payload["archives"][0]["deleted_at"] == str(deleted_at)
  1617. # Restore that payload into an instance where the row is gone entirely.
  1618. await db_session.execute(PrintArchive.__table__.delete())
  1619. await db_session.commit()
  1620. tally = _CategoryTally()
  1621. await _service()._restore_archives(db_session, payload, False, tally, {})
  1622. await db_session.commit()
  1623. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1624. assert row.deleted_at == deleted_at, "a deleted archive must not come back visible"
  1625. class TestRestoredArchiveOwnership:
  1626. """A restored archive without an owner is invisible to the person who owns it.
  1627. ``created_by_id`` is not attribution, it is the column the access check runs
  1628. on: ``_ensure_archive_visible`` fails closed on NULL (404 for any caller
  1629. without ``archives:read_all``) and the list paths filter
  1630. ``created_by_id == user.id``. So on a multi-user instance the tally reported
  1631. archives restored while their owner could neither list nor open them.
  1632. """
  1633. def _entry(self, **overrides):
  1634. entry = {
  1635. "id": 77,
  1636. "filename": "benchy.3mf",
  1637. "file_size": 2048,
  1638. "content_hash": "abc123",
  1639. "started_at": "2026-03-01 10:00:00",
  1640. "created_at": "2026-03-01 10:00:00",
  1641. }
  1642. entry.update(overrides)
  1643. return entry
  1644. async def _user(self, db, username="alice"):
  1645. user = User(username=username, role="operator")
  1646. db.add(user)
  1647. await db.flush()
  1648. return user
  1649. @pytest.mark.asyncio
  1650. async def test_owner_is_carried_across(self, db_session):
  1651. user = await self._user(db_session)
  1652. tally = _CategoryTally()
  1653. await _service()._restore_archives(
  1654. db_session, {"archives": [self._entry(created_by_id=user.id)]}, False, tally, {}
  1655. )
  1656. await db_session.commit()
  1657. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1658. assert row.created_by_id == user.id
  1659. assert not any("owner cleared" in note for note in _messages(tally))
  1660. @pytest.mark.asyncio
  1661. async def test_an_unknown_owner_is_cleared_with_a_note_not_failed(self, db_session):
  1662. """The archive is still worth having; an admin can reassign it."""
  1663. tally = _CategoryTally()
  1664. await _service()._restore_archives(
  1665. db_session, {"archives": [self._entry(created_by_id=4242)]}, False, tally, {}
  1666. )
  1667. await db_session.commit()
  1668. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1669. assert row.created_by_id is None
  1670. assert tally.restored == 1 and tally.failed == 0
  1671. assert any("owner cleared" in note and "archives:read_all" in note for note in _messages(tally))
  1672. @pytest.mark.asyncio
  1673. async def test_the_owner_note_is_emitted_once_for_many_rows(self, db_session):
  1674. tally = _CategoryTally()
  1675. archives = [
  1676. self._entry(id=1, content_hash="h1", filename="a.3mf", created_by_id=4242),
  1677. self._entry(id=2, content_hash="h2", filename="b.3mf", created_by_id=4243),
  1678. ]
  1679. await _service()._restore_archives(db_session, {"archives": archives}, False, tally, {})
  1680. await db_session.commit()
  1681. assert sum(1 for note in _messages(tally) if "owner cleared" in note) == 1
  1682. @pytest.mark.asyncio
  1683. async def test_a_backup_without_the_key_still_restores_and_says_so(self, db_session):
  1684. """Backups taken before the collector recorded it just can't know the owner.
  1685. The archive is worth restoring anyway, but it lands ownerless — which is
  1686. a 404 for everyone without ``archives:read_all``. Reporting N restored
  1687. while the user who asked for them sees none is the failure mode the note
  1688. exists to prevent.
  1689. """
  1690. tally = _CategoryTally()
  1691. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, False, tally, {})
  1692. await db_session.commit()
  1693. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1694. assert row.created_by_id is None
  1695. assert tally.restored == 1
  1696. assert not any("owner cleared" in note for note in _messages(tally))
  1697. assert any("without an owner" in note and "archives:read_all" in note for note in _messages(tally))
  1698. @pytest.mark.asyncio
  1699. async def test_an_explicitly_ownerless_archive_is_reported_too(self, db_session):
  1700. """Same consequence, so the same note: the source row had no owner either."""
  1701. tally = _CategoryTally()
  1702. await _service()._restore_archives(
  1703. db_session, {"archives": [self._entry(created_by_id=None)]}, False, tally, {}
  1704. )
  1705. await db_session.commit()
  1706. assert any("without an owner" in note for note in _messages(tally))
  1707. @pytest.mark.asyncio
  1708. async def test_a_stale_owner_is_not_reported_twice(self, db_session):
  1709. """One row, one cause, one note — the cleared-owner branch already spoke."""
  1710. tally = _CategoryTally()
  1711. await _service()._restore_archives(
  1712. db_session, {"archives": [self._entry(created_by_id=4242)]}, False, tally, {}
  1713. )
  1714. await db_session.commit()
  1715. assert any("owner cleared" in note for note in _messages(tally))
  1716. assert not any("without an owner" in note for note in _messages(tally))
  1717. @pytest.mark.asyncio
  1718. async def test_a_known_owner_is_not_reported(self, db_session):
  1719. user = await self._user(db_session)
  1720. tally = _CategoryTally()
  1721. await _service()._restore_archives(
  1722. db_session, {"archives": [self._entry(created_by_id=user.id)]}, False, tally, {}
  1723. )
  1724. await db_session.commit()
  1725. assert not any("without an owner" in note for note in _messages(tally))
  1726. @pytest.mark.asyncio
  1727. async def test_the_unknown_owner_note_is_not_emitted_on_overwrite(self, db_session):
  1728. """Overwrite keeps the local owner, so there is nothing to warn about."""
  1729. bob = await self._user(db_session, "bob")
  1730. db_session.add(
  1731. PrintArchive(
  1732. filename="benchy.3mf",
  1733. file_path="/data/benchy.3mf",
  1734. file_size=2048,
  1735. content_hash="abc123",
  1736. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1737. created_by_id=bob.id,
  1738. )
  1739. )
  1740. await db_session.commit()
  1741. tally = _CategoryTally()
  1742. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1743. await db_session.commit()
  1744. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1745. assert row.created_by_id == bob.id
  1746. assert not any("without an owner" in note for note in _messages(tally))
  1747. @pytest.mark.asyncio
  1748. async def test_overwrite_makes_the_local_owner_match_the_backup(self, db_session):
  1749. alice = await self._user(db_session, "alice")
  1750. bob = await self._user(db_session, "bob")
  1751. db_session.add(
  1752. PrintArchive(
  1753. filename="benchy.3mf",
  1754. file_path="/data/benchy.3mf",
  1755. file_size=2048,
  1756. content_hash="abc123",
  1757. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1758. created_by_id=bob.id,
  1759. )
  1760. )
  1761. await db_session.commit()
  1762. await _service()._restore_archives(
  1763. db_session, {"archives": [self._entry(created_by_id=alice.id)]}, True, _CategoryTally(), {}
  1764. )
  1765. await db_session.commit()
  1766. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1767. assert row.created_by_id == alice.id
  1768. @pytest.mark.asyncio
  1769. async def test_overwrite_leaves_the_owner_alone_when_the_backup_predates_the_key(self, db_session):
  1770. """A pre-#2656 commit must not blank the owner of a row that was fine.
  1771. The entry carries no ``created_by_id`` at all, so there is nothing to
  1772. write. Treating that as an explicit null inflicted the exact bug the
  1773. column was added to fix — a 404 for the owner — on rows the restore had
  1774. no business touching, silently, while still counting them restored.
  1775. """
  1776. bob = await self._user(db_session, "bob")
  1777. db_session.add(
  1778. PrintArchive(
  1779. filename="benchy.3mf",
  1780. file_path="/data/benchy.3mf",
  1781. file_size=2048,
  1782. content_hash="abc123",
  1783. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1784. created_by_id=bob.id,
  1785. )
  1786. )
  1787. await db_session.commit()
  1788. tally = _CategoryTally()
  1789. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1790. await db_session.commit()
  1791. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1792. assert row.created_by_id == bob.id, "an old backup does not know the owner, so it must not clear one"
  1793. assert tally.restored == 1
  1794. @pytest.mark.asyncio
  1795. async def test_overwrite_leaves_deleted_at_alone_when_the_backup_predates_the_key(self, db_session):
  1796. """The mirror case: an old commit must not un-delete, and must not claim to.
  1797. ``archivesUndeleted`` reads the same absent value, so the un-delete was
  1798. not merely wrong but unannounced.
  1799. """
  1800. db_session.add(
  1801. PrintArchive(
  1802. filename="benchy.3mf",
  1803. file_path="/data/benchy.3mf",
  1804. file_size=2048,
  1805. content_hash="abc123",
  1806. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1807. deleted_at=datetime(2026, 3, 4, 8, 0, 0),
  1808. )
  1809. )
  1810. await db_session.commit()
  1811. tally = _CategoryTally()
  1812. await _service()._restore_archives(db_session, {"archives": [self._entry()]}, True, tally, {})
  1813. await db_session.commit()
  1814. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1815. assert row.deleted_at == datetime(2026, 3, 4, 8, 0, 0), "an old backup must not resurrect a deleted archive"
  1816. assert not any("visible again" in note for note in _messages(tally))
  1817. @pytest.mark.asyncio
  1818. async def test_overwrite_still_clears_an_owner_the_backup_explicitly_nulls(self, db_session):
  1819. """Control: absent is ignored, but an explicit null is still honoured.
  1820. A current-format backup of an unowned archive has to be able to say so,
  1821. or overwrite stops meaning "make the local row match the backup".
  1822. """
  1823. bob = await self._user(db_session, "bob")
  1824. db_session.add(
  1825. PrintArchive(
  1826. filename="benchy.3mf",
  1827. file_path="/data/benchy.3mf",
  1828. file_size=2048,
  1829. content_hash="abc123",
  1830. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1831. created_by_id=bob.id,
  1832. )
  1833. )
  1834. await db_session.commit()
  1835. await _service()._restore_archives(
  1836. db_session, {"archives": [self._entry(created_by_id=None)]}, True, _CategoryTally(), {}
  1837. )
  1838. await db_session.commit()
  1839. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1840. assert row.created_by_id is None
  1841. @pytest.mark.asyncio
  1842. async def test_overwrite_still_undeletes_when_the_backup_explicitly_nulls(self, db_session):
  1843. """Control for the deleted_at half, with the note that goes with it."""
  1844. db_session.add(
  1845. PrintArchive(
  1846. filename="benchy.3mf",
  1847. file_path="/data/benchy.3mf",
  1848. file_size=2048,
  1849. content_hash="abc123",
  1850. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1851. deleted_at=datetime(2026, 3, 4, 8, 0, 0),
  1852. )
  1853. )
  1854. await db_session.commit()
  1855. tally = _CategoryTally()
  1856. await _service()._restore_archives(db_session, {"archives": [self._entry(deleted_at=None)]}, True, tally, {})
  1857. await db_session.commit()
  1858. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1859. assert row.deleted_at is None
  1860. assert any("visible again" in note for note in _messages(tally))
  1861. @pytest.mark.asyncio
  1862. async def test_owner_survives_collect_then_restore(self, db_session):
  1863. """Both halves, because each looks harmless alone.
  1864. The collector never wrote the key, so there was nothing for the restore
  1865. to carry across even once it wanted to.
  1866. """
  1867. from backend.app.services.github_backup import github_backup_service
  1868. user = await self._user(db_session)
  1869. db_session.add(
  1870. PrintArchive(
  1871. filename="owned.3mf",
  1872. file_path="",
  1873. file_size=1024,
  1874. content_hash="hash-owned",
  1875. started_at=datetime(2026, 3, 1, 10, 0, 0),
  1876. created_by_id=user.id,
  1877. )
  1878. )
  1879. await db_session.commit()
  1880. files: dict = {}
  1881. await github_backup_service._collect_archives(db_session, files)
  1882. payload = files[ARCHIVES_PATH]
  1883. assert payload["archives"][0]["created_by_id"] == user.id
  1884. await db_session.execute(PrintArchive.__table__.delete())
  1885. await db_session.commit()
  1886. await _service()._restore_archives(db_session, payload, False, _CategoryTally(), {})
  1887. await db_session.commit()
  1888. row = (await db_session.execute(select(PrintArchive))).scalar_one()
  1889. assert row.created_by_id == user.id, "a restored archive its owner cannot see is not restored"
  1890. class TestCategoryPathMapping:
  1891. def setup_method(self):
  1892. self.service = _service()
  1893. self.available = [
  1894. "backup_metadata.json",
  1895. SETTINGS_PATH,
  1896. SPOOLS_PATH,
  1897. SPOOL_USAGE_PATH,
  1898. ARCHIVES_PATH,
  1899. "kprofiles/SERIAL1/0.4.json",
  1900. "kprofiles/SERIAL1/0.8.json",
  1901. "cloud_profiles/filament.json",
  1902. ]
  1903. def test_spools_includes_usage_history(self):
  1904. paths = self.service._category_paths(RestoreCategory.SPOOLS, self.available)
  1905. assert paths == [SPOOLS_PATH, SPOOL_USAGE_PATH]
  1906. def test_kprofiles_globs_all_serials_and_nozzles(self):
  1907. paths = self.service._category_paths(RestoreCategory.KPROFILES, self.available)
  1908. assert paths == ["kprofiles/SERIAL1/0.4.json", "kprofiles/SERIAL1/0.8.json"]
  1909. def test_absent_paths_are_omitted(self):
  1910. paths = self.service._category_paths(RestoreCategory.SETTINGS, ["backup_metadata.json"])
  1911. assert paths == []
  1912. def test_cloud_profiles_are_not_a_restore_category(self):
  1913. assert "cloud_profiles" not in {c.value for c in RestoreCategory}
  1914. class TestMutex:
  1915. @pytest.mark.asyncio
  1916. async def test_restore_refuses_while_a_backup_is_running(self):
  1917. service = _service()
  1918. with patch("backend.app.services.github_backup.github_backup_service") as backup:
  1919. backup.is_running = True
  1920. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  1921. assert result["success"] is False
  1922. assert "backup is currently running" in result["message"]
  1923. @pytest.mark.asyncio
  1924. async def test_restore_refuses_while_another_restore_is_running(self):
  1925. service = _service()
  1926. service._running_restore = True
  1927. result = await service.run_restore(1, "HEAD", [RestoreCategory.SPOOLS])
  1928. assert result["success"] is False
  1929. assert "restore is already running" in result["message"]
  1930. @pytest.mark.asyncio
  1931. async def test_backup_refuses_while_a_restore_is_running(self):
  1932. from backend.app.services.github_backup import GitHubBackupService
  1933. backup_service = GitHubBackupService()
  1934. with patch("backend.app.services.github_restore.github_restore_service") as restore:
  1935. restore.is_running = True
  1936. result = await backup_service.run_backup(1, trigger="manual")
  1937. assert result["success"] is False
  1938. assert "restore is currently running" in result["message"]
  1939. class TestMqttRelayReconfigure:
  1940. """Restoring mqtt_* rows has to reach the live relay, not just the table."""
  1941. @pytest.mark.asyncio
  1942. async def test_reconfigures_from_the_committed_rows(self, db_session):
  1943. db_session.add(Settings(key="mqtt_enabled", value="true"))
  1944. db_session.add(Settings(key="mqtt_broker", value="restored.local"))
  1945. db_session.add(Settings(key="mqtt_port", value="8883"))
  1946. db_session.add(Settings(key="mqtt_use_tls", value="true"))
  1947. # Never restorable (credential blocklist), so it comes from the row that
  1948. # was already there.
  1949. db_session.add(Settings(key="mqtt_password", value="kept"))
  1950. await db_session.commit()
  1951. tally = _CategoryTally()
  1952. relay = MagicMock()
  1953. relay.configure = AsyncMock(return_value=True)
  1954. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1955. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_broker"}, tally)
  1956. relay.configure.assert_awaited_once()
  1957. sent = relay.configure.await_args.args[0]
  1958. assert sent["mqtt_enabled"] is True
  1959. assert sent["mqtt_broker"] == "restored.local"
  1960. assert sent["mqtt_port"] == 8883
  1961. assert sent["mqtt_use_tls"] is True
  1962. assert sent["mqtt_password"] == "kept"
  1963. assert sent["mqtt_topic_prefix"] == "bambuddy"
  1964. assert tally.notes == []
  1965. @pytest.mark.asyncio
  1966. async def test_no_reconnect_when_no_mqtt_key_was_written(self, db_session):
  1967. """configure() tears the connection down, so don't call it for a theme change."""
  1968. tally = _CategoryTally()
  1969. relay = MagicMock()
  1970. relay.configure = AsyncMock()
  1971. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1972. await _service()._reconfigure_mqtt_relay(db_session, {"currency", "theme"}, tally)
  1973. relay.configure.assert_not_awaited()
  1974. @pytest.mark.asyncio
  1975. async def test_broker_failure_is_noted_not_fatal(self, db_session):
  1976. tally = _CategoryTally()
  1977. relay = MagicMock()
  1978. relay.configure = AsyncMock(side_effect=OSError("no route to broker"))
  1979. with patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  1980. await _service()._reconfigure_mqtt_relay(db_session, {"mqtt_enabled"}, tally)
  1981. assert any("restart Bambuddy" in note for note in _messages(tally))
  1982. @pytest.mark.asyncio
  1983. async def test_restore_settings_reports_the_keys_it_wrote(self, db_session):
  1984. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  1985. await db_session.commit()
  1986. written: set[str] = set()
  1987. payload = {
  1988. "settings": {
  1989. "mqtt_broker": "new.local",
  1990. "currency": "EUR",
  1991. "mqtt_password": "leaked",
  1992. "auth_enabled": "false",
  1993. }
  1994. }
  1995. await _service()._restore_settings(
  1996. db_session, payload, overwrite=True, tally=_CategoryTally(), keys_written=written
  1997. )
  1998. # Skipped keys are not "written", or a blocked mqtt_password would
  1999. # trigger a pointless reconnect.
  2000. assert written == {"mqtt_broker", "currency"}
  2001. @pytest.mark.asyncio
  2002. async def test_keys_skipped_for_overwrite_off_are_not_reported(self, db_session):
  2003. db_session.add(Settings(key="mqtt_broker", value="old.local"))
  2004. await db_session.commit()
  2005. written: set[str] = set()
  2006. await _service()._restore_settings(
  2007. db_session,
  2008. {"settings": {"mqtt_broker": "new.local"}},
  2009. overwrite=False,
  2010. tally=_CategoryTally(),
  2011. keys_written=written,
  2012. )
  2013. assert written == set()
  2014. @pytest.mark.asyncio
  2015. async def test_a_refused_mqtt_enabled_is_not_reported_as_written(self, db_session):
  2016. """So the relay reconfigures from the *local* mqtt_enabled, not the backup's.
  2017. The companion rule refuses ``mqtt_enabled`` when the backup's password
  2018. cannot come across and there is none stored locally. It must not then
  2019. appear in ``keys_written``, or _reconfigure_mqtt_relay would be asked to
  2020. bring up a broker connection the restore deliberately declined to enable.
  2021. """
  2022. written: set[str] = set()
  2023. await _service()._restore_settings(
  2024. db_session,
  2025. {"settings": {"mqtt_enabled": "true", "mqtt_password": "refused", "mqtt_broker": "new.local"}},
  2026. overwrite=True,
  2027. tally=_CategoryTally(),
  2028. keys_written=written,
  2029. )
  2030. assert written == {"mqtt_broker"}
  2031. class TestApplyOrdering:
  2032. """_apply must not hold SQLite's write transaction across the MQTT phase."""
  2033. def _recording_service(self, calls: list[str]):
  2034. service = _service()
  2035. # Sync side effects on purpose: an AsyncMock returns a coroutine its
  2036. # side_effect hands back rather than awaiting it, so an async recorder
  2037. # would never run.
  2038. service._restore_archives = AsyncMock(side_effect=lambda *a, **k: calls.append("archives"))
  2039. service._restore_spools = AsyncMock(side_effect=lambda *a, **k: calls.append("spools"))
  2040. service._restore_settings = AsyncMock(side_effect=lambda *a, **k: calls.append("settings"))
  2041. service._restore_kprofiles = AsyncMock(side_effect=lambda *a, **k: calls.append("kprofiles"))
  2042. return service
  2043. @pytest.mark.asyncio
  2044. async def test_commits_database_categories_before_talking_to_printers(self):
  2045. """get_kprofiles is 3 x 5 s per printer/nozzle; busy_timeout is 15 s."""
  2046. calls: list[str] = []
  2047. service = self._recording_service(calls)
  2048. db = MagicMock()
  2049. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  2050. await service._apply(
  2051. db,
  2052. {},
  2053. [RestoreCategory.ARCHIVES, RestoreCategory.SPOOLS, RestoreCategory.KPROFILES],
  2054. False,
  2055. )
  2056. assert calls == ["archives", "spools", "commit", "kprofiles"]
  2057. @pytest.mark.asyncio
  2058. async def test_does_not_split_the_transaction_without_kprofiles(self):
  2059. """A database-only restore stays one transaction, committed by run_restore."""
  2060. calls: list[str] = []
  2061. service = self._recording_service(calls)
  2062. db = MagicMock()
  2063. db.commit = AsyncMock(side_effect=lambda: calls.append("commit"))
  2064. await service._apply(db, {}, [RestoreCategory.ARCHIVES, RestoreCategory.SETTINGS], False)
  2065. assert calls == ["archives", "settings"]
  2066. assert db.commit.await_count == 0
  2067. class TestKprofilePhaseFailure:
  2068. """The K-profile phase runs after _apply has committed everything else.
  2069. So an exception there used to reach run_restore's handler, which reports
  2070. ``success: False`` with an empty ``results`` — over archive, spool and
  2071. settings rows that are durable on disk. The honest-reporting theme of this
  2072. feature inverted on exactly the path where it matters, and the post-commit
  2073. MQTT reconfigure (downstream of the raise, inside the same try) was skipped,
  2074. leaving the relay pointed at the pre-restore broker.
  2075. """
  2076. _SETTINGS = {"version": "1.0", "settings": {"mqtt_broker": "restored.local", "currency": "EUR"}}
  2077. def _payload(self, profiles=None):
  2078. return {
  2079. SETTINGS_PATH: dict(self._SETTINGS),
  2080. "kprofiles/00M09A123456789/0.4.json": {
  2081. "profiles": [{"filament_id": "GFA00", "name": "Bambu PLA"}] if profiles is None else profiles
  2082. },
  2083. }
  2084. def _session_patch(self, db_session):
  2085. cm = AsyncMock()
  2086. cm.__aenter__ = AsyncMock(return_value=db_session)
  2087. cm.__aexit__ = AsyncMock(return_value=None)
  2088. return patch("backend.app.services.github_restore.async_session", return_value=cm)
  2089. async def _configured_service(self, db_session, payload):
  2090. from backend.app.models.github_backup import GitHubBackupConfig
  2091. config = GitHubBackupConfig(repository_url="https://github.com/o/r", access_token="tok", provider="github")
  2092. db_session.add(config)
  2093. await db_session.commit()
  2094. service = _service()
  2095. service._resolve_ref = AsyncMock(return_value=("a" * 40, "", None))
  2096. service._read_categories = AsyncMock(return_value=(payload, ""))
  2097. return service, config.id
  2098. @pytest.mark.asyncio
  2099. async def test_the_committed_categories_are_still_reported(self, db_session):
  2100. service = _service()
  2101. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  2102. results = await service._apply(
  2103. db_session,
  2104. self._payload(),
  2105. [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES],
  2106. False,
  2107. )
  2108. assert results[RestoreCategory.SETTINGS.value].restored == 2
  2109. rows = {s.key: s.value for s in (await db_session.execute(select(Settings))).scalars().all()}
  2110. assert rows == {"mqtt_broker": "restored.local", "currency": "EUR"}, "committed before the phase that failed"
  2111. @pytest.mark.asyncio
  2112. async def test_the_failure_is_counted_and_explained(self, db_session):
  2113. service = _service()
  2114. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  2115. results = await service._apply(
  2116. db_session,
  2117. self._payload(profiles=[{"filament_id": "GFA00"}, {"filament_id": "GFB99"}]),
  2118. [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES],
  2119. False,
  2120. )
  2121. tally = results[RestoreCategory.KPROFILES.value]
  2122. assert tally.failed == 2, "every profile the payload carried is unaccounted for"
  2123. assert tally.restored == 0
  2124. assert _codes(tally) == ["kprofilesStepFailed"]
  2125. assert tally.notes[0]["params"]["reason"] == "mqtt exploded"
  2126. @pytest.mark.asyncio
  2127. async def test_the_relay_is_reconfigured_even_though_the_phase_failed(self, db_session):
  2128. """The reconfigure sits downstream of the raise in run_restore's try."""
  2129. service, config_id = await self._configured_service(db_session, self._payload())
  2130. service._restore_kprofiles = AsyncMock(side_effect=RuntimeError("mqtt exploded"))
  2131. relay = MagicMock()
  2132. relay.configure = AsyncMock(return_value=True)
  2133. with self._session_patch(db_session), patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  2134. result = await service.run_restore(
  2135. config_id, "a" * 40, [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES]
  2136. )
  2137. assert result["success"] is True
  2138. assert result["results"][RestoreCategory.SETTINGS.value]["restored"] == 2
  2139. assert result["results"][RestoreCategory.KPROFILES.value]["failed"] == 1
  2140. relay.configure.assert_awaited_once()
  2141. assert relay.configure.await_args.args[0]["mqtt_broker"] == "restored.local"
  2142. @pytest.mark.asyncio
  2143. async def test_a_failure_before_the_commit_still_reports_nothing_restored(self, db_session):
  2144. """Control: rolling back and saying so is right when nothing landed."""
  2145. service, config_id = await self._configured_service(db_session, self._payload())
  2146. service._restore_settings = AsyncMock(side_effect=RuntimeError("read failed"))
  2147. relay = MagicMock()
  2148. relay.configure = AsyncMock(return_value=True)
  2149. with self._session_patch(db_session), patch("backend.app.services.mqtt_relay.mqtt_relay", relay):
  2150. result = await service.run_restore(
  2151. config_id, "a" * 40, [RestoreCategory.SETTINGS, RestoreCategory.KPROFILES]
  2152. )
  2153. assert result["success"] is False
  2154. assert result["results"] == {}
  2155. assert (await db_session.execute(select(Settings))).scalars().first() is None
  2156. relay.configure.assert_not_awaited()
  2157. @pytest.mark.asyncio
  2158. async def test_a_malformed_profiles_value_is_a_skipped_category_not_a_raise(self, db_session, printer_factory):
  2159. """Belt-and-braces: the pre-loop count ran ahead of the per-call guards.
  2160. ``sum(len(c.get("profiles") or []) ...)`` raises TypeError on a
  2161. hand-edited or truncated backup whose ``profiles`` is not a list — and it
  2162. raises after the database categories are already on disk.
  2163. """
  2164. await printer_factory(serial_number="00M09A123456789")
  2165. client = MagicMock()
  2166. client.state.connected = True
  2167. client.set_kprofiles_batch = MagicMock(return_value="7")
  2168. client.get_kprofiles = AsyncMock(return_value=[])
  2169. tally = _CategoryTally()
  2170. with patch("backend.app.services.github_restore.printer_manager") as manager:
  2171. manager.get_client = MagicMock(return_value=client)
  2172. await _service()._restore_kprofiles(db_session, self._payload(profiles=5), tally)
  2173. client.set_kprofiles_batch.assert_not_called()
  2174. assert (tally.restored, tally.failed) == (0, 0)
  2175. assert "kprofilesStepFailed" not in _codes(tally)
  2176. class TestResolveRef:
  2177. @pytest.mark.asyncio
  2178. async def test_concrete_sha_passes_through_without_an_api_call(self):
  2179. service = _service()
  2180. service.list_commits = AsyncMock()
  2181. config = MagicMock(branch="main")
  2182. resolved, error, commit = await service._resolve_ref(config, "abc1234")
  2183. assert resolved == "abc1234"
  2184. assert error == ""
  2185. # Nothing was fetched, so there is no entry to describe it with.
  2186. assert commit is None
  2187. service.list_commits.assert_not_awaited()
  2188. @pytest.mark.asyncio
  2189. async def test_head_resolves_to_the_tip_sha(self):
  2190. service = _service()
  2191. service.list_commits = AsyncMock(
  2192. return_value={"success": True, "commits": [{"sha": "tipsha1"}, {"sha": "older"}]}
  2193. )
  2194. config = MagicMock(branch="main")
  2195. resolved, error, commit = await service._resolve_ref(config, "HEAD")
  2196. assert resolved == "tipsha1"
  2197. assert error == ""
  2198. # Handed back so preview does not list commits a second time just to
  2199. # describe the one it already fetched.
  2200. assert commit == {"sha": "tipsha1"}
  2201. @pytest.mark.asyncio
  2202. async def test_empty_history_is_an_error(self):
  2203. service = _service()
  2204. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  2205. config = MagicMock(branch="main")
  2206. resolved, error, commit = await service._resolve_ref(config, "HEAD")
  2207. assert resolved is None
  2208. assert "no commits" in error
  2209. assert commit is None
  2210. class TestDescribeCommit:
  2211. """A preview that says `commit: null` gives the user no idea what they picked."""
  2212. def _config(self):
  2213. return MagicMock(branch="main", provider="github", repository_url="https://github.com/o/r", access_token="t")
  2214. def _entry(self, sha: str):
  2215. return {"sha": sha, "message": "Bambuddy backup", "author": "Bambuddy", "date": "2026-07-01T10:00:00Z"}
  2216. @pytest.mark.asyncio
  2217. async def test_an_abbreviated_ref_matches_a_full_sha_in_the_window(self):
  2218. """REF_PATTERN accepts 7 characters; providers return 40.
  2219. The old exact `==` therefore never matched an abbreviated ref, even when
  2220. the commit was right there in the top 20.
  2221. """
  2222. service = _service()
  2223. full = "abc1234" + "0" * 33
  2224. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry(full)]})
  2225. found = await service._describe_commit(self._config(), "abc1234")
  2226. assert found is not None
  2227. assert found["sha"] == full
  2228. @pytest.mark.asyncio
  2229. async def test_a_full_sha_matches_an_abbreviated_entry(self):
  2230. service = _service()
  2231. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry("abc1234")]})
  2232. found = await service._describe_commit(self._config(), "abc1234" + "0" * 33)
  2233. assert found is not None
  2234. @pytest.mark.asyncio
  2235. async def test_a_commit_outside_the_window_is_fetched_directly(self):
  2236. service = _service()
  2237. service.list_commits = AsyncMock(return_value={"success": True, "commits": [self._entry("f" * 40)]})
  2238. backend = MagicMock()
  2239. backend.get_commit = AsyncMock(return_value={"success": True, "commit": self._entry("old" + "0" * 37)})
  2240. with patch("backend.app.services.github_restore.get_provider_backend", return_value=backend):
  2241. found = await service._describe_commit(self._config(), "old" + "0" * 37)
  2242. assert found["sha"] == "old" + "0" * 37
  2243. backend.get_commit.assert_awaited_once()
  2244. @pytest.mark.asyncio
  2245. async def test_a_direct_lookup_failure_is_not_fatal(self):
  2246. """It is a subject line: render the preview without it."""
  2247. service = _service()
  2248. service.list_commits = AsyncMock(return_value={"success": True, "commits": []})
  2249. backend = MagicMock()
  2250. backend.get_commit = AsyncMock(return_value={"success": False, "message": "boom", "commit": None})
  2251. with patch("backend.app.services.github_restore.get_provider_backend", return_value=backend):
  2252. assert await service._describe_commit(self._config(), "a" * 40) is None
  2253. @pytest.mark.asyncio
  2254. async def test_the_window_scan_is_not_run_twice(self):
  2255. """_resolve_ref already listed commits for HEAD; preview reuses that."""
  2256. service = _service()
  2257. tip = self._entry("t" * 40)
  2258. service.list_commits = AsyncMock(return_value={"success": True, "commits": [tip]})
  2259. resolved, _, commit = await service._resolve_ref(self._config(), "HEAD")
  2260. assert resolved == "t" * 40
  2261. assert commit == tip
  2262. assert service.list_commits.await_count == 1