test_spoolman_inventory_helpers.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. """Unit tests for _safe_int, _safe_float, and _map_spoolman_spool helpers."""
  2. import math
  3. import pytest
  4. from backend.app.api.routes._spoolman_helpers import (
  5. _map_spoolman_spool,
  6. _safe_float,
  7. _safe_int,
  8. )
  9. # ---------------------------------------------------------------------------
  10. # _safe_int
  11. # ---------------------------------------------------------------------------
  12. class TestSafeInt:
  13. def test_normal_int(self):
  14. assert _safe_int(1000, 0) == 1000
  15. def test_float_rounds_down(self):
  16. assert _safe_int(750.9, 0) == 750
  17. def test_none_returns_fallback(self):
  18. assert _safe_int(None, 999) == 999
  19. def test_nan_returns_fallback(self):
  20. assert _safe_int(math.nan, 999) == 999
  21. def test_inf_returns_fallback(self):
  22. assert _safe_int(math.inf, 999) == 999
  23. def test_neg_inf_returns_fallback(self):
  24. assert _safe_int(-math.inf, 999) == 999
  25. def test_string_numeric(self):
  26. assert _safe_int("500", 0) == 500
  27. def test_string_non_numeric_returns_fallback(self):
  28. assert _safe_int("abc", 42) == 42
  29. def test_zero(self):
  30. assert _safe_int(0, 999) == 0
  31. # ---------------------------------------------------------------------------
  32. # _safe_float
  33. # ---------------------------------------------------------------------------
  34. class TestSafeFloat:
  35. def test_normal_float(self):
  36. assert _safe_float(123.45, 0.0) == pytest.approx(123.45)
  37. def test_none_returns_fallback(self):
  38. assert _safe_float(None, -1.0) == -1.0
  39. def test_nan_returns_fallback(self):
  40. assert _safe_float(math.nan, -1.0) == -1.0
  41. def test_inf_returns_fallback(self):
  42. assert _safe_float(math.inf, -1.0) == -1.0
  43. def test_neg_inf_returns_fallback(self):
  44. assert _safe_float(-math.inf, -1.0) == -1.0
  45. def test_string_numeric(self):
  46. assert _safe_float("3.14", 0.0) == pytest.approx(3.14)
  47. def test_string_non_numeric_returns_fallback(self):
  48. assert _safe_float("bad", 0.0) == 0.0
  49. def test_zero(self):
  50. assert _safe_float(0.0, 99.0) == 0.0
  51. # ---------------------------------------------------------------------------
  52. # _map_spoolman_spool
  53. # ---------------------------------------------------------------------------
  54. MINIMAL_SPOOL = {
  55. "id": 1,
  56. "filament": {
  57. "material": "PLA",
  58. "name": "PLA Basic",
  59. "color_hex": "FF0000",
  60. "weight": 1000.0,
  61. "vendor": {"name": "Bambu Lab"},
  62. },
  63. "used_weight": 250.0,
  64. "archived": False,
  65. "registered": "2024-01-01T00:00:00Z",
  66. }
  67. class TestMapSpoolmanSpool:
  68. def test_basic_mapping(self):
  69. result = _map_spoolman_spool(MINIMAL_SPOOL)
  70. assert result["id"] == 1
  71. assert result["material"] == "PLA"
  72. assert result["rgba"] == "FF0000FF"
  73. assert result["label_weight"] == 1000
  74. # No remaining_weight set → fallback path: weight_used = used_weight, baseline = 0.
  75. assert result["weight_used"] == pytest.approx(250.0)
  76. assert result["weight_used_baseline"] == pytest.approx(0.0)
  77. assert result["data_origin"] == "spoolman"
  78. def test_remaining_weight_drives_synthetic_used_for_parity(self):
  79. """When remaining_weight is set, weight_used = label - remaining and
  80. the baseline absorbs the used_weight delta. This mirrors the internal
  81. Spool model's split between consumed counter and physical depletion
  82. so the frontend computes the same display in both modes (#1390).
  83. """
  84. spool = {**MINIMAL_SPOOL, "used_weight": 250.0, "remaining_weight": 544.0}
  85. result = _map_spoolman_spool(spool)
  86. # Remaining = label - weight_used must equal real remaining_weight.
  87. assert result["label_weight"] - result["weight_used"] == pytest.approx(544.0)
  88. # Consumed = weight_used - baseline must equal real used_weight.
  89. assert result["weight_used"] - result["weight_used_baseline"] == pytest.approx(250.0)
  90. def test_remaining_weight_after_reset(self):
  91. """Spoolman reset: used_weight=0, remaining_weight unchanged. The
  92. mapper produces baseline = weight_used so the displayed consumed
  93. counter reads 0 while remaining stays at the real value.
  94. """
  95. spool = {**MINIMAL_SPOOL, "used_weight": 0.0, "remaining_weight": 544.0}
  96. result = _map_spoolman_spool(spool)
  97. assert result["weight_used"] == pytest.approx(456.0)
  98. assert result["weight_used_baseline"] == pytest.approx(456.0)
  99. assert result["weight_used"] - result["weight_used_baseline"] == pytest.approx(0.0)
  100. assert result["label_weight"] - result["weight_used"] == pytest.approx(544.0)
  101. def test_missing_id_raises(self):
  102. spool = {k: v for k, v in MINIMAL_SPOOL.items() if k != "id"}
  103. with pytest.raises(ValueError, match="missing required 'id'"):
  104. _map_spoolman_spool(spool)
  105. def test_none_id_raises(self):
  106. with pytest.raises(ValueError):
  107. _map_spoolman_spool({**MINIMAL_SPOOL, "id": None})
  108. def test_string_id_raises(self):
  109. with pytest.raises(ValueError, match="not a valid integer"):
  110. _map_spoolman_spool({**MINIMAL_SPOOL, "id": "abc"})
  111. def test_zero_id_raises(self):
  112. with pytest.raises(ValueError, match="positive integer"):
  113. _map_spoolman_spool({**MINIMAL_SPOOL, "id": 0})
  114. def test_negative_id_raises(self):
  115. with pytest.raises(ValueError, match="positive integer"):
  116. _map_spoolman_spool({**MINIMAL_SPOOL, "id": -5})
  117. def test_numeric_string_id_accepted(self):
  118. result = _map_spoolman_spool({**MINIMAL_SPOOL, "id": "42"})
  119. assert result["id"] == 42
  120. def test_zero_price_not_converted_to_none(self):
  121. spool = {**MINIMAL_SPOOL, "price": 0.0}
  122. result = _map_spoolman_spool(spool)
  123. assert result["cost_per_kg"] == 0.0
  124. def test_nonzero_price_preserved(self):
  125. spool = {**MINIMAL_SPOOL, "price": 9.99}
  126. result = _map_spoolman_spool(spool)
  127. assert result["cost_per_kg"] == pytest.approx(9.99)
  128. def test_none_price_stays_none(self):
  129. spool = {**MINIMAL_SPOOL, "price": None}
  130. result = _map_spoolman_spool(spool)
  131. assert result["cost_per_kg"] is None
  132. def test_infinity_weight_falls_back(self):
  133. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "weight": math.inf}}
  134. result = _map_spoolman_spool(spool)
  135. assert result["label_weight"] == 1000
  136. def test_nan_used_weight_falls_back(self):
  137. spool = {**MINIMAL_SPOOL, "used_weight": math.nan}
  138. result = _map_spoolman_spool(spool)
  139. assert result["weight_used"] == 0.0
  140. def test_invalid_color_hex_falls_back_to_grey(self):
  141. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "ZZZZZZ"}}
  142. result = _map_spoolman_spool(spool)
  143. assert result["rgba"] == "808080FF"
  144. def test_short_color_hex_falls_back(self):
  145. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "FFF"}}
  146. result = _map_spoolman_spool(spool)
  147. assert result["rgba"] == "808080FF"
  148. def test_eight_char_color_hex_is_read_back_with_its_alpha(self):
  149. """#2912: 8-char color_hex is a value the write side stores on purpose for a
  150. translucent spool, so the read must return it rather than grey it out.
  151. This test previously asserted the opposite, on the premise that only 6-char
  152. hex was valid from Spoolman. Spoolman stores whatever it is given, and
  153. Bambuddy's own rgba fields advertise RRGGBBAA — the read was what turned a
  154. clear spool into neutral grey.
  155. """
  156. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "FF000080"}}
  157. result = _map_spoolman_spool(spool)
  158. assert result["rgba"] == "FF000080"
  159. def test_fully_transparent_color_hex_survives_the_read(self):
  160. """The reported case: a clear spool stored as 00000000 must not come back
  161. as opaque black."""
  162. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "00000000"}}
  163. result = _map_spoolman_spool(spool)
  164. assert result["rgba"] == "00000000"
  165. def test_six_char_color_hex_still_gains_the_opaque_alpha(self):
  166. """Existing data is 6-char and must keep round-tripping unchanged — the
  167. opaque byte is appended, not doubled onto an alpha that is already there."""
  168. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "FF0000"}}
  169. result = _map_spoolman_spool(spool)
  170. assert result["rgba"] == "FF0000FF"
  171. def test_seven_char_color_hex_falls_back(self):
  172. """Only 6 or 8 are valid lengths; a 7-char value is malformed and still
  173. greys out rather than being padded into something plausible."""
  174. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "FF0000F"}}
  175. result = _map_spoolman_spool(spool)
  176. assert result["rgba"] == "808080FF"
  177. def test_color_name_uses_explicit_field_when_present(self):
  178. """When Spoolman's filament has color_name set, that wins over the subtype fallback."""
  179. spool = {
  180. **MINIMAL_SPOOL,
  181. "filament": {**MINIMAL_SPOOL["filament"], "color_name": "Sunrise Orange"},
  182. }
  183. result = _map_spoolman_spool(spool)
  184. assert result["color_name"] == "Sunrise Orange"
  185. # Real stored value — not synthesised from subtype.
  186. assert result["color_name_is_synthesized"] is False
  187. def test_color_name_flags_synthesized_when_falling_back_to_subtype(self):
  188. """#1319: when the read falls back to subtype, the response must flag it
  189. so the edit form doesn't round-trip the synth value back to Spoolman."""
  190. spool = {
  191. **MINIMAL_SPOOL,
  192. "filament": {
  193. **MINIMAL_SPOOL["filament"],
  194. "name": "PLA Basic Red",
  195. # No color_name field.
  196. },
  197. }
  198. result = _map_spoolman_spool(spool)
  199. assert result["color_name"] == "Basic Red"
  200. assert result["color_name_is_synthesized"] is True
  201. def test_color_name_falls_back_to_subtype_when_field_missing(self):
  202. """Spoolman doesn't standardise color_name; the LinkSpoolModal would
  203. otherwise show 'Unknown color' for every Spoolman spool. The mapper
  204. falls back to the filament's name minus material prefix (which the
  205. subtype field already carries) so the user can tell spools apart at a
  206. glance even on installs that don't fill color_name.
  207. """
  208. spool = {
  209. **MINIMAL_SPOOL,
  210. "filament": {
  211. **MINIMAL_SPOOL["filament"],
  212. "name": "PLA Basic Red",
  213. # No color_name field — the common case for default Spoolman installs.
  214. },
  215. }
  216. result = _map_spoolman_spool(spool)
  217. # subtype is filament_name minus material prefix → "Basic Red"
  218. assert result["subtype"] == "Basic Red"
  219. # color_name falls back to subtype.
  220. assert result["color_name"] == "Basic Red"
  221. def test_color_name_read_from_spool_extra_first(self):
  222. """#1357: the canonical store for color_name is
  223. spool.extra.bambu_color_name (JSON-encoded). Read priority is
  224. extra > filament.color_name > subtype-synth. The user's
  225. Bambuddy-saved value MUST win even when Spoolman's own
  226. filament.color_name happens to be populated from some other source.
  227. """
  228. spool = {
  229. **MINIMAL_SPOOL,
  230. "extra": {"bambu_color_name": '"Galaxy Black"'},
  231. "filament": {
  232. **MINIMAL_SPOOL["filament"],
  233. "name": "PLA Glow",
  234. "color_name": "Glow", # would be picked up if extra weren't preferred
  235. },
  236. }
  237. result = _map_spoolman_spool(spool)
  238. assert result["color_name"] == "Galaxy Black"
  239. assert result["color_name_is_synthesized"] is False
  240. def test_color_name_empty_extra_falls_through_to_filament(self):
  241. """An explicit empty string in spool.extra.bambu_color_name (the
  242. "user cleared the field" shape) must NOT mask Spoolman's own
  243. filament.color_name if one exists — it falls through to the next
  244. layer instead of suppressing it."""
  245. spool = {
  246. **MINIMAL_SPOOL,
  247. "extra": {"bambu_color_name": '""'},
  248. "filament": {
  249. **MINIMAL_SPOOL["filament"],
  250. "color_name": "Sunset",
  251. },
  252. }
  253. result = _map_spoolman_spool(spool)
  254. assert result["color_name"] == "Sunset"
  255. assert result["color_name_is_synthesized"] is False
  256. def test_color_name_empty_extra_falls_through_to_synth(self):
  257. """When extra is cleared and filament has no color_name either,
  258. fall all the way through to the subtype synth — same UX as a fresh
  259. Spoolman install."""
  260. spool = {
  261. **MINIMAL_SPOOL,
  262. "extra": {"bambu_color_name": '""'},
  263. "filament": {
  264. **MINIMAL_SPOOL["filament"],
  265. "name": "PLA Basic Red",
  266. },
  267. }
  268. result = _map_spoolman_spool(spool)
  269. assert result["color_name"] == "Basic Red"
  270. assert result["color_name_is_synthesized"] is True
  271. def test_color_name_none_when_both_fields_empty(self):
  272. """If neither color_name nor a usable subtype exists, return None — UI
  273. falls back to its own 'Unknown color' string rather than showing a
  274. misleading material-only label.
  275. """
  276. spool = {
  277. **MINIMAL_SPOOL,
  278. "filament": {
  279. **MINIMAL_SPOOL["filament"],
  280. "name": "PLA", # name == material → subtype becomes None
  281. },
  282. }
  283. result = _map_spoolman_spool(spool)
  284. assert result["subtype"] is None
  285. assert result["color_name"] is None
  286. # No synth happened — nothing to fall back to.
  287. assert result["color_name_is_synthesized"] is False
  288. def test_color_hex_with_hash_prefix_stripped(self):
  289. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "#00FF00"}}
  290. result = _map_spoolman_spool(spool)
  291. assert result["rgba"] == "00FF00FF"
  292. def test_color_hex_lowercase_normalised(self):
  293. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "color_hex": "ff0000"}}
  294. result = _map_spoolman_spool(spool)
  295. assert result["rgba"] == "FF0000FF"
  296. def test_none_filament(self):
  297. spool = {**MINIMAL_SPOOL, "filament": None}
  298. result = _map_spoolman_spool(spool)
  299. assert result["material"] == ""
  300. assert result["rgba"] == "808080FF"
  301. assert result["label_weight"] == 1000
  302. def test_archived_spool_has_archived_at(self):
  303. spool = {**MINIMAL_SPOOL, "archived": True}
  304. result = _map_spoolman_spool(spool)
  305. assert result["archived_at"] is not None
  306. def test_subtype_strips_material_prefix(self):
  307. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "material": "PLA", "name": "PLA Basic"}}
  308. result = _map_spoolman_spool(spool)
  309. assert result["subtype"] == "Basic"
  310. def test_brand_from_vendor(self):
  311. result = _map_spoolman_spool(MINIMAL_SPOOL)
  312. assert result["brand"] == "Bambu Lab"
  313. def test_no_vendor_brand_is_none(self):
  314. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "vendor": None}}
  315. result = _map_spoolman_spool(spool)
  316. assert result["brand"] is None
  317. def test_spoolman_location_mapped_to_storage_location(self):
  318. spool = {**MINIMAL_SPOOL, "location": "Shelf A"}
  319. result = _map_spoolman_spool(spool)
  320. assert result["storage_location"] == "Shelf A"
  321. def test_no_location_gives_none_storage_location(self):
  322. result = _map_spoolman_spool(MINIMAL_SPOOL)
  323. assert result["storage_location"] is None
  324. def test_empty_location_gives_none_storage_location(self):
  325. spool = {**MINIMAL_SPOOL, "location": ""}
  326. result = _map_spoolman_spool(spool)
  327. assert result["storage_location"] is None
  328. def test_spoolman_location_key_not_in_result(self):
  329. spool = {**MINIMAL_SPOOL, "location": "Shelf A"}
  330. result = _map_spoolman_spool(spool)
  331. assert "spoolman_location" not in result
  332. def test_core_weight_from_filament_spool_weight(self):
  333. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": 196}}
  334. result = _map_spoolman_spool(spool)
  335. assert result["core_weight"] == 196
  336. def test_core_weight_fallback_when_spool_weight_missing(self):
  337. result = _map_spoolman_spool(MINIMAL_SPOOL)
  338. assert result["core_weight"] == 250
  339. def test_core_weight_fallback_when_spool_weight_none(self):
  340. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": None}}
  341. result = _map_spoolman_spool(spool)
  342. assert result["core_weight"] == 250
  343. def test_core_weight_float_truncated_to_int(self):
  344. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": 180.9}}
  345. result = _map_spoolman_spool(spool)
  346. assert result["core_weight"] == 180
  347. def test_spool_level_spool_weight_takes_priority_over_filament(self):
  348. spool = {**MINIMAL_SPOOL, "spool_weight": 300, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": 196}}
  349. assert _map_spoolman_spool(spool)["core_weight"] == 300
  350. def test_spool_level_zero_spool_weight_not_treated_as_missing(self):
  351. spool = {**MINIMAL_SPOOL, "spool_weight": 0, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": 196}}
  352. assert _map_spoolman_spool(spool)["core_weight"] == 0
  353. def test_spool_level_none_falls_back_to_filament(self):
  354. spool = {**MINIMAL_SPOOL, "spool_weight": None, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": 196}}
  355. assert _map_spoolman_spool(spool)["core_weight"] == 196
  356. def test_spool_level_absent_falls_back_to_filament(self):
  357. spool = {**MINIMAL_SPOOL, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": 196}}
  358. assert _map_spoolman_spool(spool)["core_weight"] == 196
  359. def test_both_levels_none_uses_fallback(self):
  360. spool = {**MINIMAL_SPOOL, "spool_weight": None, "filament": {**MINIMAL_SPOOL["filament"], "spool_weight": None}}
  361. assert _map_spoolman_spool(spool)["core_weight"] == 250
  362. # ---------------------------------------------------------------------------
  363. # F4: _safe_optional_float unit tests
  364. # ---------------------------------------------------------------------------
  365. class TestSafeOptionalFloat:
  366. """F4: Direct unit tests for _safe_optional_float (NaN/Inf safety)."""
  367. def test_normal_value(self):
  368. import pytest
  369. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  370. assert _safe_optional_float(9.99) == pytest.approx(9.99)
  371. def test_none_returns_none(self):
  372. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  373. assert _safe_optional_float(None) is None
  374. def test_nan_returns_none(self):
  375. import math
  376. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  377. assert _safe_optional_float(math.nan) is None
  378. def test_inf_returns_none(self):
  379. import math
  380. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  381. assert _safe_optional_float(math.inf) is None
  382. def test_neg_inf_returns_none(self):
  383. import math
  384. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  385. assert _safe_optional_float(-math.inf) is None
  386. def test_zero_returns_zero(self):
  387. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  388. assert _safe_optional_float(0.0) == 0.0
  389. def test_string_numeric(self):
  390. import pytest
  391. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  392. assert _safe_optional_float("3.14") == pytest.approx(3.14)
  393. def test_string_non_numeric_returns_none(self):
  394. from backend.app.api.routes._spoolman_helpers import _safe_optional_float
  395. assert _safe_optional_float("bad") is None
  396. class TestMapSpoolmanSpoolSlicerFilament:
  397. """slicer_filament round-trip via Spoolman extra dict.
  398. Spoolman has no native slicer_filament field, so we persist BambuStudio
  399. presets under bambu_slicer_filament[_name] keys in the spool's extra
  400. dict (JSON-encoded strings, like every Spoolman extra value). The map
  401. function unwraps those values and exposes them as slicer_filament /
  402. slicer_filament_name on the InventorySpool shape. Without this round-trip
  403. the user's selected slicer preset is silently dropped on save (#1114).
  404. """
  405. def test_slicer_filament_unwrapped_from_extra(self):
  406. spool = {
  407. **MINIMAL_SPOOL,
  408. "extra": {
  409. "bambu_slicer_filament": '"PFUSf543b298f8ea66"',
  410. "bambu_slicer_filament_name": '"Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle (Custom)"',
  411. },
  412. }
  413. result = _map_spoolman_spool(spool)
  414. assert result["slicer_filament"] == "PFUSf543b298f8ea66"
  415. assert result["slicer_filament_name"] == "Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle (Custom)"
  416. def test_slicer_filament_falls_back_to_filament_name(self):
  417. # Spool has no bambu_slicer_filament_name override → use Spoolman's filament.name
  418. spool = {**MINIMAL_SPOOL, "extra": {}}
  419. result = _map_spoolman_spool(spool)
  420. assert result["slicer_filament"] is None
  421. assert result["slicer_filament_name"] == "PLA Basic" # from filament.name
  422. def test_empty_string_extra_treated_as_unset(self):
  423. # JSON-encoded empty string is how the user clears the field
  424. spool = {
  425. **MINIMAL_SPOOL,
  426. "extra": {
  427. "bambu_slicer_filament": '""',
  428. "bambu_slicer_filament_name": '""',
  429. },
  430. }
  431. result = _map_spoolman_spool(spool)
  432. assert result["slicer_filament"] is None
  433. # Falls back to filament.name when the override is cleared
  434. assert result["slicer_filament_name"] == "PLA Basic"
  435. def test_non_json_extra_value_passed_through(self):
  436. # Tolerate bare-string values written without JSON encoding
  437. # (older data, manual writes via Spoolman UI, etc.)
  438. spool = {
  439. **MINIMAL_SPOOL,
  440. "extra": {"bambu_slicer_filament": "GFL05"},
  441. }
  442. result = _map_spoolman_spool(spool)
  443. assert result["slicer_filament"] == "GFL05"
  444. class TestExtractExtraStr:
  445. """JSON-encoded extra-string unwrapper used by _map_spoolman_spool."""
  446. def test_unwraps_quoted_string(self):
  447. from backend.app.api.routes._spoolman_helpers import _extract_extra_str
  448. assert _extract_extra_str({"k": '"hello"'}, "k") == "hello"
  449. def test_returns_empty_for_missing_key(self):
  450. from backend.app.api.routes._spoolman_helpers import _extract_extra_str
  451. assert _extract_extra_str({}, "k") == ""
  452. def test_returns_empty_for_non_string_value(self):
  453. from backend.app.api.routes._spoolman_helpers import _extract_extra_str
  454. # Spoolman extra values are stringified; numeric values shouldn't sneak in
  455. # but if they do we treat them as unset rather than crashing
  456. assert _extract_extra_str({"k": 42}, "k") == ""
  457. def test_returns_empty_for_json_null(self):
  458. from backend.app.api.routes._spoolman_helpers import _extract_extra_str
  459. # null isn't a string after decode → treat as unset
  460. assert _extract_extra_str({"k": "null"}, "k") == ""
  461. def test_passes_through_bare_string_on_decode_error(self):
  462. from backend.app.api.routes._spoolman_helpers import _extract_extra_str
  463. # Tolerate non-JSON-encoded values
  464. assert _extract_extra_str({"k": "GFL05"}, "k") == "GFL05"
  465. class TestMapSpoolmanSpoolPrice:
  466. """F4: NaN/Inf price in _map_spoolman_spool gives None cost_per_kg."""
  467. def test_nan_price_gives_none_cost_per_kg(self):
  468. import math
  469. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  470. spool = {**MINIMAL_SPOOL, "price": math.nan}
  471. assert _map_spoolman_spool(spool)["cost_per_kg"] is None
  472. def test_inf_price_gives_none_cost_per_kg(self):
  473. import math
  474. from backend.app.api.routes._spoolman_helpers import _map_spoolman_spool
  475. spool = {**MINIMAL_SPOOL, "price": math.inf}
  476. assert _map_spoolman_spool(spool)["cost_per_kg"] is None