test_slicer_presets.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. """Tests for the unified slicer-presets endpoint helpers.
  2. The endpoint stitches together four preset sources (local / orca_cloud /
  3. cloud / standard). It does NOT dedup across tiers — every tier surfaces
  4. its full list so the user can pick any source. Bambu Cloud filament
  5. metadata is enriched from same-named entries in the other tiers so it
  6. can still score in the SliceModal's auto-pick. These tests pin the
  7. enrich behaviour, the cloud-status mapping, and the per-user / sidecar
  8. caches at the helper level — full HTTP integration is covered by the
  9. routes test.
  10. """
  11. from __future__ import annotations
  12. import time
  13. from unittest.mock import AsyncMock, MagicMock, patch
  14. import pytest
  15. from backend.app.api.routes import slicer_presets as sp
  16. from backend.app.schemas.slicer_presets import UnifiedPreset
  17. def _slot(items: list[tuple[str, str, str]]) -> dict[str, list[UnifiedPreset]]:
  18. """Helper: build a single-slot dict from (id, name, source) tuples placed
  19. on the printer slot. Process / filament default to empty so each test
  20. only exercises the slot it cares about."""
  21. return {
  22. "printer": [UnifiedPreset(id=i, name=n, source=s) for i, n, s in items],
  23. "process": [],
  24. "filament": [],
  25. }
  26. class TestEnrichCloudMetadata:
  27. """No cross-tier dedup — every tier's full list comes back; Bambu Cloud
  28. filament metadata is enriched from same-named entries in other tiers."""
  29. def test_same_name_in_all_tiers_appears_in_every_tier(self):
  30. """Critical regression guard for #1712: a user who has imported a
  31. local profile AND signed in to Orca AND has Bambu Cloud with the
  32. same name should see it under EACH source, not just the highest-
  33. priority tier. The order is used for auto-pick + group rendering;
  34. it is NOT used to hide profiles."""
  35. orca = _slot([("oid1", "Bambu PLA Basic", "orca_cloud")])
  36. cloud = _slot([("cid1", "Bambu PLA Basic", "cloud")])
  37. local = _slot([("lid1", "Bambu PLA Basic", "local")])
  38. standard = _slot([("Bambu PLA Basic", "Bambu PLA Basic", "standard")])
  39. oc, c, l_, s = sp._enrich_cloud_metadata(orca, cloud, local, standard)
  40. assert [p.source for p in l_["printer"]] == ["local"]
  41. assert [p.source for p in oc["printer"]] == ["orca_cloud"]
  42. assert [p.source for p in c["printer"]] == ["cloud"]
  43. assert [p.source for p in s["printer"]] == ["standard"]
  44. def test_preserves_order_within_tier(self):
  45. """A tier's input order must be preserved — nothing in the enrich
  46. pass should sort, reverse, or otherwise reorder entries."""
  47. cloud = _slot(
  48. [
  49. ("c1", "Z-First", "cloud"),
  50. ("c2", "A-Second", "cloud"),
  51. ("c3", "M-Third", "cloud"),
  52. ]
  53. )
  54. _oc, c, _l, _s = sp._enrich_cloud_metadata(_slot([]), cloud, _slot([]), _slot([]))
  55. assert [p.name for p in c["printer"]] == ["Z-First", "A-Second", "M-Third"]
  56. def test_bambu_cloud_filament_metadata_backfilled_from_local(self):
  57. """Bambu Cloud's list response omits filament_type/colour for
  58. rate-limit reasons. A same-named local entry's metadata fills in
  59. so the cloud entry can still score in pickFilamentForSlot."""
  60. local = {
  61. "printer": [],
  62. "process": [],
  63. "filament": [
  64. UnifiedPreset(
  65. id="lp1",
  66. name="Bambu PLA Basic",
  67. source="local",
  68. filament_type="PLA",
  69. filament_colour="#FF0000",
  70. )
  71. ],
  72. }
  73. cloud = {
  74. "printer": [],
  75. "process": [],
  76. "filament": [UnifiedPreset(id="cp1", name="Bambu PLA Basic", source="cloud")],
  77. }
  78. _oc, c, _l, _s = sp._enrich_cloud_metadata(_slot([]), cloud, local, _slot([]))
  79. # Cloud entry now carries the local entry's metadata.
  80. assert c["filament"][0].filament_type == "PLA"
  81. assert c["filament"][0].filament_colour == "#FF0000"
  82. # Local entry is untouched.
  83. assert local["filament"][0].filament_type == "PLA"
  84. def test_bambu_cloud_metadata_falls_back_through_orca_and_standard(self):
  85. """When local doesn't carry the name, orca_cloud / standard fill in."""
  86. orca = {
  87. "printer": [],
  88. "process": [],
  89. "filament": [
  90. UnifiedPreset(
  91. id="o1",
  92. name="Bambu PLA Basic",
  93. source="orca_cloud",
  94. filament_type="PLA",
  95. filament_colour="#00FF00",
  96. )
  97. ],
  98. }
  99. cloud = {
  100. "printer": [],
  101. "process": [],
  102. "filament": [UnifiedPreset(id="cp1", name="Bambu PLA Basic", source="cloud")],
  103. }
  104. _oc, c, _l, _s = sp._enrich_cloud_metadata(orca, cloud, _slot([]), _slot([]))
  105. assert c["filament"][0].filament_type == "PLA"
  106. assert c["filament"][0].filament_colour == "#00FF00"
  107. def test_bambu_cloud_keeps_its_own_metadata_when_present(self):
  108. """If Bambu Cloud already has filament_type / filament_colour the
  109. enrich pass must not overwrite them with a different same-named
  110. entry's values."""
  111. local = {
  112. "printer": [],
  113. "process": [],
  114. "filament": [
  115. UnifiedPreset(
  116. id="lp1",
  117. name="Bambu PLA Basic",
  118. source="local",
  119. filament_type="PETG",
  120. filament_colour="#000000",
  121. )
  122. ],
  123. }
  124. cloud = {
  125. "printer": [],
  126. "process": [],
  127. "filament": [
  128. UnifiedPreset(
  129. id="cp1",
  130. name="Bambu PLA Basic",
  131. source="cloud",
  132. filament_type="PLA",
  133. filament_colour="#FFFFFF",
  134. )
  135. ],
  136. }
  137. _oc, c, _l, _s = sp._enrich_cloud_metadata(_slot([]), cloud, local, _slot([]))
  138. assert c["filament"][0].filament_type == "PLA"
  139. assert c["filament"][0].filament_colour == "#FFFFFF"
  140. def _filaments(source: str, *items: tuple[str, str | None]) -> dict[str, list[UnifiedPreset]]:
  141. """A tier with only filament presets, from (name, filament_type) pairs."""
  142. return {
  143. "printer": [],
  144. "process": [],
  145. "filament": [UnifiedPreset(id=n, name=n, source=source, filament_type=t) for n, t in items],
  146. }
  147. class TestEnrichMaterialWithoutTwin:
  148. """#3403: with OrcaSlicer preferred, the bundle has no H2C profiles, so a
  149. Bambu Cloud "@BBL H2C" filament has no same-named twin and used to stay
  150. untyped -- a PETG-CF slot then auto-picked Generic PETG."""
  151. def _bundled(self) -> dict[str, list[UnifiedPreset]]:
  152. # The OrcaSlicer 2.4.2 bundle as it lists these: every printer's
  153. # profile but the H2C, and Orca's own "@System" generics.
  154. return _filaments(
  155. "standard",
  156. ("Generic PETG-CF @BBL X1C", "PETG-CF"),
  157. ("Generic PETG-CF @BBL H2D", "PETG-CF"),
  158. ("Generic PETG-CF @System", "PETG"),
  159. ("Generic PETG @BBL X1C", "PETG"),
  160. ("Generic PE-CF @BBL X1C", "PE-CF"),
  161. ("Generic PE-CF @System", "PE"),
  162. )
  163. def test_bambu_cloud_stock_profile_takes_the_material_of_its_other_printers(self):
  164. cloud = _filaments(
  165. "cloud",
  166. ("Generic PETG @BBL H2C", None),
  167. ("Generic PETG-CF @BBL H2C", None),
  168. ("Generic PETG-CF @BBL H2C 0.4 nozzle", None),
  169. ("Generic PE-CF @BBL H2C", None),
  170. )
  171. _oc, c, _l, _s = sp._enrich_cloud_metadata(
  172. _filaments("orca_cloud"), cloud, _filaments("local"), self._bundled()
  173. )
  174. assert [p.filament_type for p in c["filament"]] == ["PETG", "PETG-CF", "PETG-CF", "PE-CF"]
  175. # Material only: the colour of another printer's profile isn't this one's.
  176. assert all(p.filament_colour is None for p in c["filament"])
  177. def test_disagreeing_bundled_materials_leave_it_unknown(self):
  178. bundled = _filaments("standard", ("Odd PLA @BBL X1C", "PLA"), ("Odd PLA @BBL A1", "PLA-CF"))
  179. cloud = _filaments("cloud", ("Odd PLA @BBL H2C", None))
  180. _oc, c, _l, _s = sp._enrich_cloud_metadata(_filaments("orca_cloud"), cloud, _filaments("local"), bundled)
  181. assert c["filament"][0].filament_type is None
  182. def test_only_bundled_bbl_names_count(self):
  183. """A name without "@BBL", or a user's own "@BBL"-named profile, is no
  184. source of another profile's material."""
  185. local = _filaments("local", ("Generic PLA @BBL X1C", "PETG"))
  186. cloud = _filaments("cloud", ("Generic PETG-CF", None), ("Generic PLA @BBL H2C", None))
  187. _oc, c, _l, _s = sp._enrich_cloud_metadata(_filaments("orca_cloud"), cloud, local, self._bundled())
  188. assert [p.filament_type for p in c["filament"]] == [None, None]
  189. def test_a_users_copy_of_a_stock_profile_is_left_unknown(self):
  190. """Its material may be the one the user changed it to."""
  191. cloud = _filaments("cloud", ("Generic PETG @BBL H2C - Copy", None), ("Generic PETG @BBL H2C 0.4 nozzle", None))
  192. _oc, c, _l, _s = sp._enrich_cloud_metadata(
  193. _filaments("orca_cloud"), cloud, _filaments("local"), self._bundled()
  194. )
  195. assert [p.filament_type for p in c["filament"]] == [None, "PETG"]
  196. def test_a_stated_material_is_kept(self):
  197. cloud = _filaments("cloud", ("Generic PETG-CF @BBL H2C", "PETG"))
  198. _oc, c, _l, _s = sp._enrich_cloud_metadata(
  199. _filaments("orca_cloud"), cloud, _filaments("local"), self._bundled()
  200. )
  201. assert c["filament"][0].filament_type == "PETG"
  202. def test_orca_cloud_profile_takes_the_material_of_its_parent(self):
  203. orca = _filaments(
  204. "orca_cloud",
  205. ("My PETG-CF", None),
  206. ("My PETG-CF fast", None),
  207. ("My H2C PETG-CF", None),
  208. ("Loop A", None),
  209. ("Loop B", None),
  210. ("Typed", "PLA"),
  211. ("From System", None),
  212. )
  213. parents = {
  214. "My PETG-CF": "Generic PETG-CF @BBL X1C", # bundled, same name
  215. "My PETG-CF fast": "My PETG-CF", # through another user profile
  216. "My H2C PETG-CF": "Generic PETG-CF @BBL H2C", # not bundled: by filament
  217. "Loop A": "Loop B",
  218. "Loop B": "Loop A",
  219. "Typed": "Generic PETG @BBL X1C",
  220. # Orca's own generic states the coarser PETG: no source.
  221. "From System": "Generic PETG-CF @System",
  222. }
  223. for p in orca["filament"]:
  224. p.inherits = parents[p.name]
  225. oc, _c, _l, _s = sp._enrich_cloud_metadata(orca, _filaments("cloud"), _filaments("local"), self._bundled())
  226. assert [p.filament_type for p in oc["filament"]] == ["PETG-CF", "PETG-CF", "PETG-CF", None, None, "PLA", None]
  227. class TestEnrichCompatiblePrinters:
  228. """#2628: the same name bridge carries ``compatible_printers`` onto the
  229. tiers that don't ship one. Bambu Cloud never does — so a profile whose
  230. name carries no printer model reads as "compatibility unknown", which the
  231. SliceModal treats as usable and auto-picks for the wrong printer."""
  232. COMPAT = ["Bambu Lab X1 Carbon 0.2 nozzle", "Bambu Lab P1S 0.2 nozzle"]
  233. def _tier(self, source: str, slot: str, compat: list[str] | None) -> dict[str, list[UnifiedPreset]]:
  234. empty: dict[str, list[UnifiedPreset]] = {"printer": [], "process": [], "filament": []}
  235. empty[slot] = [
  236. UnifiedPreset(id=f"{source}1", name="Overture PLA Matte @0.2", source=source, compatible_printers=compat)
  237. ]
  238. return empty
  239. def test_bambu_cloud_borrows_the_list_from_a_same_named_local_import(self):
  240. local = self._tier("local", "filament", self.COMPAT)
  241. cloud = self._tier("cloud", "filament", None)
  242. _oc, c, _l, _s = sp._enrich_cloud_metadata(_slot([]), cloud, local, _slot([]))
  243. assert c["filament"][0].compatible_printers == self.COMPAT
  244. def test_bambu_cloud_borrows_from_orca_cloud_too(self):
  245. orca = self._tier("orca_cloud", "filament", self.COMPAT)
  246. cloud = self._tier("cloud", "filament", None)
  247. _oc, c, _l, _s = sp._enrich_cloud_metadata(orca, cloud, _slot([]), _slot([]))
  248. assert c["filament"][0].compatible_printers == self.COMPAT
  249. def test_orca_cloud_borrows_when_its_own_content_had_no_list(self):
  250. orca = self._tier("orca_cloud", "filament", None)
  251. local = self._tier("local", "filament", self.COMPAT)
  252. oc, _c, _l, _s = sp._enrich_cloud_metadata(orca, _slot([]), local, _slot([]))
  253. assert oc["filament"][0].compatible_printers == self.COMPAT
  254. def test_process_slot_is_bridged_as_well(self):
  255. local = self._tier("local", "process", self.COMPAT)
  256. cloud = self._tier("cloud", "process", None)
  257. _oc, c, _l, _s = sp._enrich_cloud_metadata(_slot([]), cloud, local, _slot([]))
  258. assert c["process"][0].compatible_printers == self.COMPAT
  259. def test_never_overwrites_a_list_the_entry_already_has(self):
  260. own = ["Bambu Lab P2S 0.4 nozzle"]
  261. local = self._tier("local", "filament", self.COMPAT)
  262. cloud = self._tier("cloud", "filament", own)
  263. _oc, c, _l, _s = sp._enrich_cloud_metadata(_slot([]), cloud, local, _slot([]))
  264. assert c["filament"][0].compatible_printers == own
  265. def test_no_donor_leaves_the_entry_unclassified(self):
  266. """Absent evidence the entry must stay None — the SliceModal then
  267. falls back to the name matcher instead of hiding the profile."""
  268. cloud = self._tier("cloud", "filament", None)
  269. _oc, c, _l, _s = sp._enrich_cloud_metadata(_slot([]), cloud, _slot([]), _slot([]))
  270. assert c["filament"][0].compatible_printers is None
  271. def test_borrowed_list_is_copied_not_shared(self):
  272. """A later mutation of one tier's list must not reach through to the
  273. other — these objects are cached per user between requests."""
  274. local = self._tier("local", "filament", list(self.COMPAT))
  275. cloud = self._tier("cloud", "filament", None)
  276. _oc, c, l_, _s = sp._enrich_cloud_metadata(_slot([]), cloud, local, _slot([]))
  277. l_["filament"][0].compatible_printers.append("Bambu Lab H2D 0.4 nozzle")
  278. assert c["filament"][0].compatible_printers == self.COMPAT
  279. def _user_with_cloud_auth(user_id: int = 1) -> MagicMock:
  280. """Construct a mock User that passes the CLOUD_AUTH permission check.
  281. `MagicMock` defaults `.has_permission(...)` to a truthy MagicMock object,
  282. which would coincidentally pass the gate — but explicit is better than
  283. accidental. Setting `.return_value = True` documents the intent."""
  284. user = MagicMock(id=user_id)
  285. user.has_permission = MagicMock(return_value=True)
  286. return user
  287. class TestFetchOrcaCloudPresets:
  288. """``_fetch_orca_cloud_presets`` mirrors the Bambu Cloud fetcher's status
  289. vocabulary (``ok`` / ``not_authenticated`` / ``expired`` / ``unreachable``)
  290. and the same permission-shortcut + caching behaviour. Tests pin the
  291. contract so a future bug in either fetcher doesn't silently desync them."""
  292. def _orca_creds(self, token: str | None = "tok") -> MagicMock:
  293. creds = MagicMock()
  294. creds.token = token
  295. return creds
  296. @pytest.mark.asyncio
  297. async def test_no_token_returns_not_authenticated(self):
  298. sp._orca_cloud_cache.clear()
  299. with patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds(None))):
  300. user = MagicMock(id=1)
  301. user.has_permission = MagicMock(return_value=True)
  302. slots, status = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  303. assert status == "not_authenticated"
  304. assert slots == {"printer": [], "process": [], "filament": []}
  305. @pytest.mark.asyncio
  306. async def test_user_without_orca_cloud_auth_returns_not_authenticated(self):
  307. """Defence-in-depth — a user lacking ORCA_CLOUD_AUTH must not see Orca
  308. presets even if their User row carries a stale token. Credentials
  309. lookup must short-circuit ahead of the token read."""
  310. sp._orca_cloud_cache.clear()
  311. user = MagicMock(id=1)
  312. user.has_permission = MagicMock(return_value=False)
  313. with patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))) as load:
  314. slots, status = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  315. assert status == "not_authenticated"
  316. assert slots["printer"] == []
  317. load.assert_not_called()
  318. @pytest.mark.asyncio
  319. async def test_auth_error_returns_expired(self):
  320. sp._orca_cloud_cache.clear()
  321. svc_mock = MagicMock()
  322. svc_mock.list_profiles = AsyncMock(side_effect=sp.OrcaCloudAuthError("expired"))
  323. svc_mock.close = AsyncMock()
  324. user = MagicMock(id=1)
  325. user.has_permission = MagicMock(return_value=True)
  326. with (
  327. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  328. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)),
  329. ):
  330. _slots, status = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  331. assert status == "expired"
  332. svc_mock.close.assert_awaited_once()
  333. @pytest.mark.asyncio
  334. async def test_orca_error_returns_unreachable(self):
  335. sp._orca_cloud_cache.clear()
  336. svc_mock = MagicMock()
  337. svc_mock.list_profiles = AsyncMock(side_effect=sp.OrcaCloudError("net down"))
  338. svc_mock.close = AsyncMock()
  339. user = MagicMock(id=1)
  340. user.has_permission = MagicMock(return_value=True)
  341. with (
  342. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  343. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)),
  344. ):
  345. _slots, status = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  346. assert status == "unreachable"
  347. @pytest.mark.asyncio
  348. async def test_happy_path_shapes_grouped_by_type(self):
  349. """Orca content.type values map onto Bambu Cloud's preset type vocab
  350. (``printer`` / ``print`` → ``process`` / ``filament``). Verify the
  351. full mapping by feeding one of each shape."""
  352. sp._orca_cloud_cache.clear()
  353. svc_mock = MagicMock()
  354. svc_mock.list_profiles = AsyncMock(
  355. return_value=[
  356. {"id": "m1", "name": "Orca X1C", "content": {"type": "printer"}},
  357. {"id": "p1", "name": "Orca 0.20mm", "content": {"type": "print"}},
  358. {
  359. "id": "f1",
  360. "name": "Orca PLA",
  361. "content": {
  362. "type": "filament",
  363. "filament_type": ["PLA"],
  364. "default_filament_colour": ["#000000"],
  365. },
  366. },
  367. ]
  368. )
  369. svc_mock.close = AsyncMock()
  370. user = MagicMock(id=1)
  371. user.has_permission = MagicMock(return_value=True)
  372. with (
  373. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  374. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)),
  375. ):
  376. slots, status = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  377. assert status == "ok"
  378. assert [p.name for p in slots["printer"]] == ["Orca X1C"]
  379. assert [p.name for p in slots["process"]] == ["Orca 0.20mm"]
  380. filament = slots["filament"]
  381. assert [p.name for p in filament] == ["Orca PLA"]
  382. # Inline metadata extracted from the content blob (Orca's sync_pull
  383. # returns full content, so unlike Bambu Cloud we don't need a second
  384. # per-preset fetch to enrich filament_type / filament_colour).
  385. assert filament[0].filament_type == "PLA"
  386. assert filament[0].filament_colour == "#000000"
  387. @pytest.mark.asyncio
  388. async def test_extracts_compatible_printers_from_content(self):
  389. """#2628: Orca's sync_pull already carries the profile's own
  390. compatible-printer list. Surfacing it lets the SliceModal reject a
  391. profile built for another printer instead of falling back to reading
  392. the model out of the NAME — which fails outright for names that carry
  393. no model ("Overture PLA Matte @0.2")."""
  394. sp._orca_cloud_cache.clear()
  395. compat = ["Bambu Lab X1 Carbon 0.2 nozzle", "Bambu Lab P1S 0.2 nozzle"]
  396. svc_mock = MagicMock()
  397. svc_mock.list_profiles = AsyncMock(
  398. return_value=[
  399. {
  400. "id": "f1",
  401. "name": "Overture PLA Matte @0.2",
  402. "content": {
  403. "type": "filament",
  404. "filament_type": ["PLA"],
  405. "compatible_printers": compat,
  406. },
  407. },
  408. {
  409. "id": "p1",
  410. "name": "Orca 0.20mm",
  411. "content": {"type": "print", "compatible_printers": "Bambu Lab P2S 0.4 nozzle"},
  412. },
  413. {"id": "m1", "name": "Orca X1C", "content": {"type": "printer"}},
  414. ]
  415. )
  416. svc_mock.close = AsyncMock()
  417. user = MagicMock(id=1)
  418. user.has_permission = MagicMock(return_value=True)
  419. with (
  420. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  421. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)),
  422. ):
  423. slots, status = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  424. assert status == "ok"
  425. assert slots["filament"][0].compatible_printers == compat
  426. # A single-printer profile may store a bare string — normalised to a list.
  427. assert slots["process"][0].compatible_printers == ["Bambu Lab P2S 0.4 nozzle"]
  428. # Printer presets have nothing to be compatible with.
  429. assert slots["printer"][0].compatible_printers is None
  430. @pytest.mark.asyncio
  431. async def test_printer_preset_carries_the_preset_it_was_saved_from(self):
  432. """#3250: a printer preset saved under a name of its own is in no
  433. process's compatible_printers; the SliceModal needs its parent."""
  434. sp._orca_cloud_cache.clear()
  435. svc_mock = MagicMock()
  436. svc_mock.list_profiles = AsyncMock(
  437. return_value=[
  438. {
  439. "id": "m1",
  440. "name": "Bambu Lab H2D 0.4 nozzle - Skew",
  441. "content": {"type": "printer", "inherits": " Bambu Lab H2D 0.4 nozzle "},
  442. },
  443. {"id": "m2", "name": "Orca X1C", "content": {"type": "printer", "inherits": ""}},
  444. {"id": "m3", "name": "Odd", "content": {"type": "printer", "inherits": ["x"]}},
  445. ]
  446. )
  447. svc_mock.close = AsyncMock()
  448. user = MagicMock(id=1)
  449. user.has_permission = MagicMock(return_value=True)
  450. with (
  451. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  452. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)),
  453. ):
  454. slots, _ = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  455. assert [p.inherits for p in slots["printer"]] == ["Bambu Lab H2D 0.4 nozzle", None, None]
  456. @pytest.mark.asyncio
  457. async def test_filament_preset_carries_the_preset_it_was_saved_from(self):
  458. """#3403: a filament saved with only the keys the user changed states no
  459. material of its own; the enrich pass reads it off this parent."""
  460. sp._orca_cloud_cache.clear()
  461. svc_mock = MagicMock()
  462. svc_mock.list_profiles = AsyncMock(
  463. return_value=[
  464. {
  465. "id": "f1",
  466. "name": "My PETG-CF",
  467. "content": {"type": "filament", "inherits": "Generic PETG-CF @BBL X1C"},
  468. },
  469. {
  470. "id": "p1",
  471. "name": "Orca 0.20mm",
  472. "content": {"type": "print", "inherits": "0.20mm Standard @BBL X1C"},
  473. },
  474. ]
  475. )
  476. svc_mock.close = AsyncMock()
  477. user = MagicMock(id=1)
  478. user.has_permission = MagicMock(return_value=True)
  479. with (
  480. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  481. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)),
  482. ):
  483. slots, _ = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  484. assert slots["filament"][0].inherits == "Generic PETG-CF @BBL X1C"
  485. assert slots["filament"][0].filament_type is None
  486. assert slots["process"][0].inherits is None
  487. @pytest.mark.asyncio
  488. async def test_missing_or_malformed_compatible_printers_stays_none(self):
  489. """No data must read as "unknown", never as "compatible with nothing" —
  490. the SliceModal falls back to the name matcher for those."""
  491. sp._orca_cloud_cache.clear()
  492. svc_mock = MagicMock()
  493. svc_mock.list_profiles = AsyncMock(
  494. return_value=[
  495. {"id": "f1", "name": "No list", "content": {"type": "filament"}},
  496. {"id": "f2", "name": "Empty list", "content": {"type": "filament", "compatible_printers": []}},
  497. {"id": "f3", "name": "Blanks", "content": {"type": "filament", "compatible_printers": ["", " "]}},
  498. {"id": "f4", "name": "Wrong type", "content": {"type": "filament", "compatible_printers": {"a": 1}}},
  499. ]
  500. )
  501. svc_mock.close = AsyncMock()
  502. user = MagicMock(id=1)
  503. user.has_permission = MagicMock(return_value=True)
  504. with (
  505. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  506. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)),
  507. ):
  508. slots, _status = await sp._fetch_orca_cloud_presets(MagicMock(), user)
  509. assert [p.compatible_printers for p in slots["filament"]] == [None, None, None, None]
  510. @pytest.mark.asyncio
  511. async def test_cache_hit_skips_orca_call(self):
  512. """A second call within TTL must reuse the cached slots and NOT
  513. hit the Orca service again — same TTL as Bambu Cloud (5 min)."""
  514. sp._orca_cloud_cache.clear()
  515. svc_mock = MagicMock()
  516. svc_mock.list_profiles = AsyncMock(return_value=[])
  517. svc_mock.close = AsyncMock()
  518. user = MagicMock(id=1)
  519. user.has_permission = MagicMock(return_value=True)
  520. with (
  521. patch.object(sp, "_load_orca_credentials", AsyncMock(return_value=self._orca_creds("tok"))),
  522. patch.object(sp, "_build_orca_service", AsyncMock(return_value=svc_mock)) as build,
  523. ):
  524. await sp._fetch_orca_cloud_presets(MagicMock(), user)
  525. await sp._fetch_orca_cloud_presets(MagicMock(), user)
  526. # Build is the cache miss signal — second call reused the cache.
  527. build.assert_awaited_once()
  528. class TestFetchCloudPresets:
  529. """`_fetch_cloud_presets` translates token state and cloud errors into
  530. the four ``cloud_status`` values the SliceModal banner consumes."""
  531. @pytest.mark.asyncio
  532. async def test_no_token_returns_not_authenticated(self):
  533. sp._cloud_cache.clear()
  534. with patch.object(sp, "get_stored_token", AsyncMock(return_value=(None, None, None))):
  535. slots, status = await sp._fetch_cloud_presets(MagicMock(), _user_with_cloud_auth())
  536. assert status == "not_authenticated"
  537. assert slots == {"printer": [], "process": [], "filament": []}
  538. @pytest.mark.asyncio
  539. async def test_user_without_cloud_auth_returns_not_authenticated(self):
  540. """Defence-in-depth: a user lacking CLOUD_AUTH must NOT see cloud
  541. presets even if their User row carries a stale cloud_token from a
  542. previous permission state. Token lookup is skipped entirely."""
  543. sp._cloud_cache.clear()
  544. user = MagicMock(id=1)
  545. user.has_permission = MagicMock(return_value=False)
  546. with patch.object(sp, "get_stored_token", AsyncMock(return_value=("leftover-token", None, None))) as get_tok:
  547. slots, status = await sp._fetch_cloud_presets(MagicMock(), user)
  548. assert status == "not_authenticated"
  549. assert slots["printer"] == []
  550. # Token was never read — the perm check short-circuits ahead of it.
  551. get_tok.assert_not_called()
  552. @pytest.mark.asyncio
  553. async def test_auth_error_returns_expired(self):
  554. sp._cloud_cache.clear()
  555. cloud_mock = MagicMock()
  556. cloud_mock.set_token = MagicMock()
  557. cloud_mock.get_slicer_settings = AsyncMock(side_effect=sp.BambuCloudAuthError("expired"))
  558. cloud_mock.close = AsyncMock()
  559. with (
  560. patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", "e@x", None))),
  561. patch.object(sp, "BambuCloudService", return_value=cloud_mock),
  562. ):
  563. slots, status = await sp._fetch_cloud_presets(MagicMock(), _user_with_cloud_auth())
  564. assert status == "expired"
  565. assert slots["printer"] == []
  566. cloud_mock.close.assert_awaited_once()
  567. @pytest.mark.asyncio
  568. async def test_cloud_error_returns_unreachable(self):
  569. sp._cloud_cache.clear()
  570. cloud_mock = MagicMock()
  571. cloud_mock.set_token = MagicMock()
  572. cloud_mock.get_slicer_settings = AsyncMock(side_effect=sp.BambuCloudError("net down"))
  573. cloud_mock.close = AsyncMock()
  574. with (
  575. patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
  576. patch.object(sp, "BambuCloudService", return_value=cloud_mock),
  577. ):
  578. _slots, status = await sp._fetch_cloud_presets(MagicMock(), _user_with_cloud_auth())
  579. assert status == "unreachable"
  580. @pytest.mark.asyncio
  581. async def test_happy_path_shapes_private_then_public(self):
  582. """Cloud presets split into private (user-custom) + public (Bambu's
  583. stock cloud presets). Private should sort before public so a user's
  584. own customisations sit at the top of the dropdown."""
  585. sp._cloud_cache.clear()
  586. cloud_mock = MagicMock()
  587. cloud_mock.set_token = MagicMock()
  588. cloud_mock.get_slicer_settings = AsyncMock(
  589. return_value={
  590. "printer": {
  591. "private": [{"setting_id": "PFUprivate1", "name": "My X1C"}],
  592. "public": [{"setting_id": "PFUpublic1", "name": "Bambu X1C Stock"}],
  593. },
  594. "print": {"private": [], "public": []},
  595. "filament": {"private": [], "public": []},
  596. }
  597. )
  598. cloud_mock.close = AsyncMock()
  599. with (
  600. patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
  601. patch.object(sp, "BambuCloudService", return_value=cloud_mock),
  602. ):
  603. slots, status = await sp._fetch_cloud_presets(MagicMock(), _user_with_cloud_auth())
  604. assert status == "ok"
  605. names = [p.name for p in slots["printer"]]
  606. assert names == ["My X1C", "Bambu X1C Stock"]
  607. @pytest.mark.asyncio
  608. async def test_cache_hit_skips_cloud_call(self):
  609. """A second call within TTL must reuse the cached slots and NOT
  610. hit Bambu Cloud again."""
  611. sp._cloud_cache.clear()
  612. cloud_mock = MagicMock()
  613. cloud_mock.set_token = MagicMock()
  614. cloud_mock.get_slicer_settings = AsyncMock(
  615. return_value={
  616. "printer": {"private": [{"setting_id": "id1", "name": "X1C"}], "public": []},
  617. "print": {"private": [], "public": []},
  618. "filament": {"private": [], "public": []},
  619. }
  620. )
  621. cloud_mock.close = AsyncMock()
  622. user = _user_with_cloud_auth(user_id=42)
  623. with (
  624. patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
  625. patch.object(sp, "BambuCloudService", return_value=cloud_mock),
  626. ):
  627. await sp._fetch_cloud_presets(MagicMock(), user)
  628. await sp._fetch_cloud_presets(MagicMock(), user)
  629. cloud_mock.get_slicer_settings.assert_awaited_once()
  630. @pytest.mark.asyncio
  631. async def test_cache_is_per_user(self):
  632. """User A's cached cloud presets must not surface for user B."""
  633. sp._cloud_cache.clear()
  634. def make_mock(name: str):
  635. m = MagicMock()
  636. m.set_token = MagicMock()
  637. m.get_slicer_settings = AsyncMock(
  638. return_value={
  639. "printer": {"private": [{"setting_id": f"id-{name}", "name": name}], "public": []},
  640. "print": {"private": [], "public": []},
  641. "filament": {"private": [], "public": []},
  642. }
  643. )
  644. m.close = AsyncMock()
  645. return m
  646. sequence = [make_mock("AliceX1C"), make_mock("BobX1C")]
  647. with (
  648. patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
  649. patch.object(sp, "BambuCloudService", side_effect=sequence),
  650. ):
  651. alice_slots, _ = await sp._fetch_cloud_presets(MagicMock(), _user_with_cloud_auth(1))
  652. bob_slots, _ = await sp._fetch_cloud_presets(MagicMock(), _user_with_cloud_auth(2))
  653. assert alice_slots["printer"][0].name == "AliceX1C"
  654. assert bob_slots["printer"][0].name == "BobX1C"
  655. @pytest.mark.asyncio
  656. async def test_cache_invalidates_on_token_change(self):
  657. """A token change (logout + login, admin reset, region switch) must
  658. bypass the cache for that user — pinning a real-world auth bug
  659. where user re-login + cache-stuck-on-old-cloud-account would
  660. silently serve a different account's preset list for ~5 minutes."""
  661. sp._cloud_cache.clear()
  662. def make_mock(name: str):
  663. m = MagicMock()
  664. m.set_token = MagicMock()
  665. m.get_slicer_settings = AsyncMock(
  666. return_value={
  667. "printer": {"private": [{"setting_id": f"id-{name}", "name": name}], "public": []},
  668. "print": {"private": [], "public": []},
  669. "filament": {"private": [], "public": []},
  670. }
  671. )
  672. m.close = AsyncMock()
  673. return m
  674. # Same user_id, different token between calls — the second call must
  675. # NOT serve the first call's cached slots.
  676. services = [make_mock("OldAccountX1C"), make_mock("NewAccountX1C")]
  677. token_sequence = [("tok-old", None, None), ("tok-new", None, None)]
  678. user = _user_with_cloud_auth(user_id=7)
  679. with (
  680. patch.object(sp, "get_stored_token", AsyncMock(side_effect=token_sequence)),
  681. patch.object(sp, "BambuCloudService", side_effect=services),
  682. ):
  683. first, _ = await sp._fetch_cloud_presets(MagicMock(), user)
  684. second, _ = await sp._fetch_cloud_presets(MagicMock(), user)
  685. assert first["printer"][0].name == "OldAccountX1C"
  686. assert second["printer"][0].name == "NewAccountX1C"
  687. @pytest.mark.asyncio
  688. async def test_refresh_bypasses_cloud_cache(self):
  689. """``refresh=True`` must skip an otherwise-warm cache entry and hit
  690. Bambu Cloud again — wiring for the SliceModal's Refresh button so a
  691. user who deletes a cloud preset in Bambu Studio / Handy doesn't have
  692. to wait for the 5-minute TTL to expire (#1581)."""
  693. sp._cloud_cache.clear()
  694. cloud_mock = MagicMock()
  695. cloud_mock.set_token = MagicMock()
  696. cloud_mock.get_slicer_settings = AsyncMock(
  697. return_value={
  698. "printer": {"private": [{"setting_id": "id1", "name": "X1C"}], "public": []},
  699. "print": {"private": [], "public": []},
  700. "filament": {"private": [], "public": []},
  701. }
  702. )
  703. cloud_mock.close = AsyncMock()
  704. user = _user_with_cloud_auth(user_id=99)
  705. with (
  706. patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
  707. patch.object(sp, "BambuCloudService", return_value=cloud_mock),
  708. ):
  709. await sp._fetch_cloud_presets(MagicMock(), user)
  710. # Without refresh, the second call hits cache (covered by
  711. # test_cache_hit_skips_cloud_call). With refresh=True it MUST
  712. # re-fetch.
  713. await sp._fetch_cloud_presets(MagicMock(), user, refresh=True)
  714. assert cloud_mock.get_slicer_settings.await_count == 2
  715. @pytest.mark.asyncio
  716. async def test_refresh_writes_back_to_cache(self):
  717. """A refresh call must still update the cache so a subsequent normal
  718. call doesn't re-hit the cloud immediately afterwards."""
  719. sp._cloud_cache.clear()
  720. cloud_mock = MagicMock()
  721. cloud_mock.set_token = MagicMock()
  722. cloud_mock.get_slicer_settings = AsyncMock(
  723. return_value={
  724. "printer": {"private": [{"setting_id": "id1", "name": "X1C"}], "public": []},
  725. "print": {"private": [], "public": []},
  726. "filament": {"private": [], "public": []},
  727. }
  728. )
  729. cloud_mock.close = AsyncMock()
  730. user = _user_with_cloud_auth(user_id=101)
  731. with (
  732. patch.object(sp, "get_stored_token", AsyncMock(return_value=("tok", None, None))),
  733. patch.object(sp, "BambuCloudService", return_value=cloud_mock),
  734. ):
  735. await sp._fetch_cloud_presets(MagicMock(), user, refresh=True)
  736. await sp._fetch_cloud_presets(MagicMock(), user)
  737. # Two calls — first refresh, second a normal cache hit.
  738. assert cloud_mock.get_slicer_settings.await_count == 1
  739. class TestFetchBundledPresets:
  740. """Standard tier reaches out to the slicer-api sidecar; tolerate the
  741. sidecar being absent / unreachable so the modal still works."""
  742. @pytest.mark.asyncio
  743. async def test_no_sidecar_url_returns_empty(self):
  744. sp._bundled_cache = None
  745. with patch.object(sp, "_resolve_slicer_api_url", AsyncMock(return_value=None)):
  746. slots = await sp._fetch_bundled_presets(MagicMock())
  747. assert slots == {"printer": [], "process": [], "filament": []}
  748. # No URL means no useful cache result either — second call should
  749. # try again (so users who configure a URL mid-session see results).
  750. assert sp._bundled_cache is None
  751. @pytest.mark.asyncio
  752. async def test_sidecar_error_returns_empty(self):
  753. sp._bundled_cache = None
  754. svc_mock = MagicMock()
  755. svc_mock.list_bundled_profiles = AsyncMock(side_effect=sp.SlicerApiError("boom"))
  756. svc_mock.__aenter__ = AsyncMock(return_value=svc_mock)
  757. svc_mock.__aexit__ = AsyncMock(return_value=False)
  758. with (
  759. patch.object(sp, "_resolve_slicer_api_url", AsyncMock(return_value="http://nope")),
  760. patch.object(sp, "SlicerApiService", return_value=svc_mock),
  761. ):
  762. slots = await sp._fetch_bundled_presets(MagicMock())
  763. assert slots == {"printer": [], "process": [], "filament": []}
  764. @pytest.mark.asyncio
  765. async def test_happy_path_shapes_response(self):
  766. sp._bundled_cache = None
  767. svc_mock = MagicMock()
  768. svc_mock.list_bundled_profiles = AsyncMock(
  769. return_value={
  770. "printer": [{"name": "Bambu X1C 0.4", "base_id": None}],
  771. "process": [{"name": "0.20mm Standard", "base_id": "fdm_process_common"}],
  772. "filament": [{"name": "Bambu PLA Basic", "base_id": "fdm_filament_pla"}],
  773. }
  774. )
  775. svc_mock.__aenter__ = AsyncMock(return_value=svc_mock)
  776. svc_mock.__aexit__ = AsyncMock(return_value=False)
  777. with (
  778. patch.object(sp, "_resolve_slicer_api_url", AsyncMock(return_value="http://ok")),
  779. patch.object(sp, "SlicerApiService", return_value=svc_mock),
  780. ):
  781. slots = await sp._fetch_bundled_presets(MagicMock())
  782. assert slots["printer"][0].name == "Bambu X1C 0.4"
  783. assert slots["printer"][0].source == "standard"
  784. # Bundled presets are addressed by name (the slicer's inheritance
  785. # walker resolves them by name), so id == name.
  786. assert slots["printer"][0].id == "Bambu X1C 0.4"
  787. @pytest.mark.asyncio
  788. async def test_cache_hit_skips_sidecar(self):
  789. """A second call within TTL must serve from the cached entry and not
  790. re-hit the sidecar HTTP."""
  791. sp._bundled_cache = (
  792. time.monotonic(),
  793. {
  794. "printer": [UnifiedPreset(id="Cached", name="Cached", source="standard")],
  795. "process": [],
  796. "filament": [],
  797. },
  798. )
  799. # If `SlicerApiService` is constructed at all we've missed the cache.
  800. with patch.object(sp, "SlicerApiService", side_effect=AssertionError("cache miss!")):
  801. slots = await sp._fetch_bundled_presets(MagicMock())
  802. assert slots["printer"][0].name == "Cached"
  803. @pytest.mark.asyncio
  804. async def test_refresh_bypasses_bundled_cache(self):
  805. """``refresh=True`` must re-hit the sidecar even when the in-process
  806. cache is warm — paired with the cloud-cache refresh, this is what
  807. powers the SliceModal's Refresh button (#1581)."""
  808. sp._bundled_cache = (
  809. time.monotonic(),
  810. {
  811. "printer": [UnifiedPreset(id="Stale", name="Stale", source="standard")],
  812. "process": [],
  813. "filament": [],
  814. },
  815. )
  816. svc_mock = MagicMock()
  817. svc_mock.list_bundled_profiles = AsyncMock(
  818. return_value={
  819. "printer": [{"name": "Fresh", "base_id": None}],
  820. "process": [],
  821. "filament": [],
  822. }
  823. )
  824. svc_mock.__aenter__ = AsyncMock(return_value=svc_mock)
  825. svc_mock.__aexit__ = AsyncMock(return_value=False)
  826. with (
  827. patch.object(sp, "_resolve_slicer_api_url", AsyncMock(return_value="http://ok")),
  828. patch.object(sp, "SlicerApiService", return_value=svc_mock),
  829. ):
  830. slots = await sp._fetch_bundled_presets(MagicMock(), refresh=True)
  831. svc_mock.list_bundled_profiles.assert_awaited_once()
  832. assert [p.name for p in slots["printer"]] == ["Fresh"]
  833. # The fresh result must also be written back to the cache so a
  834. # subsequent normal (non-refresh) call doesn't re-hit the sidecar.
  835. assert sp._bundled_cache is not None
  836. assert [p.name for p in sp._bundled_cache[1]["printer"]] == ["Fresh"]
  837. class TestResolveSlicerApiUrl:
  838. """`_resolve_slicer_api_url` must respect the user's `preferred_slicer`
  839. setting just like the slice route does. The bundled-listing fetch
  840. used to be hardcoded to OrcaSlicer's URL, which left the Standard
  841. tier permanently empty for BambuStudio installs."""
  842. @pytest.mark.asyncio
  843. async def test_bambu_studio_preference_uses_bambu_url(self):
  844. """When the user prefers Bambu Studio, the listing fetch must hit
  845. the bambu-studio-api sidecar (port 3001 by default), not orca's
  846. port 3003."""
  847. async def fake_get_setting(_db, key):
  848. return {
  849. "preferred_slicer": "bambu_studio",
  850. "bambu_studio_api_url": "http://bambu-studio-api:3000",
  851. }.get(key)
  852. with patch(
  853. "backend.app.api.routes.settings.get_setting",
  854. new=fake_get_setting,
  855. ):
  856. url = await sp._resolve_slicer_api_url(MagicMock())
  857. assert url == "http://bambu-studio-api:3000"
  858. @pytest.mark.asyncio
  859. async def test_orcaslicer_preference_uses_orca_url(self):
  860. async def fake_get_setting(_db, key):
  861. return {
  862. "preferred_slicer": "orcaslicer",
  863. "orcaslicer_api_url": "http://orca-slicer-api:3000",
  864. }.get(key)
  865. with patch(
  866. "backend.app.api.routes.settings.get_setting",
  867. new=fake_get_setting,
  868. ):
  869. url = await sp._resolve_slicer_api_url(MagicMock())
  870. assert url == "http://orca-slicer-api:3000"
  871. @pytest.mark.asyncio
  872. async def test_default_preference_is_bambu_studio(self):
  873. """Empty preferred_slicer → bambu_studio (matches the slice route's
  874. default at library.py:_run_slicer_with_fallback)."""
  875. async def fake_get_setting(_db, key):
  876. return {
  877. # preferred_slicer not set
  878. "bambu_studio_api_url": "http://bambu-default:3000",
  879. }.get(key)
  880. with patch(
  881. "backend.app.api.routes.settings.get_setting",
  882. new=fake_get_setting,
  883. ):
  884. url = await sp._resolve_slicer_api_url(MagicMock())
  885. assert url == "http://bambu-default:3000"
  886. @pytest.mark.asyncio
  887. async def test_unknown_preference_returns_none(self):
  888. """An unrecognised preferred_slicer value (e.g. set out-of-band by
  889. a stale migration) returns None so the modal degrades to "no
  890. Standard tier" rather than crashing — the slice route raises 400
  891. in this case but the listing is informational, so be lenient."""
  892. async def fake_get_setting(_db, key):
  893. return {"preferred_slicer": "prusaslicer"}.get(key)
  894. with patch(
  895. "backend.app.api.routes.settings.get_setting",
  896. new=fake_get_setting,
  897. ):
  898. url = await sp._resolve_slicer_api_url(MagicMock())
  899. assert url is None
  900. class TestParseCompatiblePrinters:
  901. """``compatible_printers`` exposed for local process / filament presets so
  902. the SliceModal can filter the dropdowns by the selected printer (#1325)."""
  903. def test_parses_json_array(self):
  904. raw = '["Bambu Lab X1 Carbon 0.4 nozzle", "Bambu Lab X1 0.4 nozzle"]'
  905. assert sp._parse_compatible_printers(raw) == [
  906. "Bambu Lab X1 Carbon 0.4 nozzle",
  907. "Bambu Lab X1 0.4 nozzle",
  908. ]
  909. def test_none_and_empty_return_none(self):
  910. assert sp._parse_compatible_printers(None) is None
  911. assert sp._parse_compatible_printers("") is None
  912. assert sp._parse_compatible_printers("[]") is None
  913. def test_malformed_json_returns_none(self):
  914. assert sp._parse_compatible_printers("not json") is None
  915. # A JSON value that isn't an array is treated as absent, not an error.
  916. assert sp._parse_compatible_printers('"a string"') is None
  917. def test_drops_non_string_and_blank_entries(self):
  918. assert sp._parse_compatible_printers('["X1C", 5, "", " ", "A1"]') == [
  919. "X1C",
  920. "A1",
  921. ]
  922. class TestListPrinterModels:
  923. """``GET /slicer/printer-models`` exposes ``PRINTER_MODEL_MAP`` so the
  924. frontend doesn't duplicate the Bambu model registry (#1325 follow-up)."""
  925. def test_returns_canonical_printer_model_map(self):
  926. from backend.app.utils.printer_models import PRINTER_MODEL_MAP
  927. result = sp.list_printer_models()
  928. # Same shape - mapping from "Bambu Lab <model>" to short code.
  929. assert result == PRINTER_MODEL_MAP
  930. # Spot-check a few entries: the SliceModal name-fallback (#1325)
  931. # specifically depends on these resolving.
  932. assert result["Bambu Lab X1 Carbon"] == "X1C"
  933. assert result["Bambu Lab P2S"] == "P2S"
  934. assert result["Bambu Lab A1 mini"] == "A1 Mini"
  935. assert result["Bambu Lab H2D Pro"] == "H2D Pro"
  936. def test_returns_a_copy_not_the_module_dict(self):
  937. # A response handler must never hand out the live module-level dict —
  938. # accidental mutation by middleware / serialisers would silently
  939. # corrupt the registry for every subsequent request.
  940. from backend.app.utils.printer_models import PRINTER_MODEL_MAP
  941. result = sp.list_printer_models()
  942. assert result is not PRINTER_MODEL_MAP
  943. class TestNoUserWithAuthOn:
  944. """The sign-in stored without a user is the auth-off install's, and may be
  945. left over after auth was turned on. A caller with no user while auth is
  946. on (an API key without Allow Cloud Access) must not list its presets."""
  947. @pytest.mark.asyncio
  948. async def test_bambu_cloud(self):
  949. sp._cloud_cache.clear()
  950. with (
  951. patch.object(sp, "is_auth_enabled", AsyncMock(return_value=True)),
  952. patch.object(sp, "get_stored_token", AsyncMock(return_value=("global-tok", None, None))) as get_tok,
  953. ):
  954. slots, status = await sp._fetch_cloud_presets(MagicMock(), None)
  955. assert status == "not_authenticated"
  956. assert slots == {"printer": [], "process": [], "filament": []}
  957. get_tok.assert_not_called()
  958. @pytest.mark.asyncio
  959. async def test_orca_cloud(self):
  960. sp._orca_cloud_cache.clear()
  961. with (
  962. patch.object(sp, "is_auth_enabled", AsyncMock(return_value=True)),
  963. patch.object(sp, "_load_orca_credentials", AsyncMock()) as load,
  964. ):
  965. slots, status = await sp._fetch_orca_cloud_presets(MagicMock(), None)
  966. assert status == "not_authenticated"
  967. assert slots == {"printer": [], "process": [], "filament": []}
  968. load.assert_not_called()
  969. class TestLocalPrinterInherits:
  970. """#3250: local printer presets report the preset they were saved from."""
  971. @pytest.mark.asyncio
  972. async def test_local_printer_preset_carries_inherits(self, db_session):
  973. from backend.app.models.local_preset import LocalPreset
  974. db_session.add_all(
  975. [
  976. LocalPreset(
  977. name="Bambu Lab H2D 0.4 nozzle - Skew",
  978. preset_type="printer",
  979. source="orcaslicer",
  980. setting="{}",
  981. inherits="Bambu Lab H2D 0.4 nozzle",
  982. ),
  983. LocalPreset(name="Plain", preset_type="printer", source="orcaslicer", setting="{}", inherits=" "),
  984. LocalPreset(
  985. name="0.20mm Mine",
  986. preset_type="process",
  987. source="orcaslicer",
  988. setting="{}",
  989. inherits="0.20mm Standard @BBL H2D",
  990. ),
  991. ]
  992. )
  993. await db_session.commit()
  994. slots = await sp._fetch_local_presets(db_session)
  995. by_name = {p.name: p for p in slots["printer"]}
  996. assert by_name["Bambu Lab H2D 0.4 nozzle - Skew"].inherits == "Bambu Lab H2D 0.4 nozzle"
  997. assert by_name["Plain"].inherits is None
  998. # Only printer presets need it; a process is matched by its own list.
  999. assert slots["process"][0].inherits is None