test_github_restore.py 71 KB

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