test_spoolman_inventory_helpers.py 32 KB

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