test_github_restore.py 73 KB

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