test_shared_tray_usage_3230.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """Several slicer slots charged to one tray (#3230).
  2. The 3MF pass skipped a tray once it had charged it, so a second slicer slot
  3. mapped to the same tray was dropped. The reporter's H2C printed filaments 1 and
  4. 4 from one AMS-HT tray (mapping ``[128, -1, -1, 128, -1]``) and lost filament
  5. 4's 2.13 g. The same skip dropped the last segment of a single-filament print
  6. that switched to another tray and back. A slot is now charged once and a tray
  7. as often as slots use it.
  8. """
  9. from datetime import datetime, timezone
  10. from types import SimpleNamespace
  11. from unittest.mock import AsyncMock, MagicMock, patch
  12. import pytest
  13. from backend.app.models.archive import PrintArchive
  14. from backend.app.models.spool import Spool
  15. from backend.app.services.usage_tracker import _track_from_3mf
  16. pytestmark = pytest.mark.unit
  17. def _spool(spool_id: int):
  18. spool = MagicMock()
  19. spool.id = spool_id
  20. spool.label_weight = 1000
  21. spool.weight_used = 0
  22. spool.cost_per_kg = None
  23. spool.material = "PLA"
  24. spool.rgba = None
  25. return spool
  26. def _db(spools: dict[int, MagicMock]):
  27. archive = MagicMock()
  28. archive.id = 3230
  29. archive.file_path = "archives/3230/test.3mf"
  30. archive.extra_data = None
  31. archive.plate_id = None
  32. async def execute(stmt, *args, **kwargs):
  33. entity = stmt.column_descriptions[0].get("entity")
  34. result = MagicMock()
  35. value = None
  36. if entity is PrintArchive:
  37. value = archive
  38. elif entity is Spool:
  39. value = spools.get(stmt.whereclause.right.value)
  40. result.scalar_one_or_none.return_value = value
  41. result.scalars.return_value.first.return_value = None
  42. result.scalar.return_value = None
  43. return result
  44. db = AsyncMock()
  45. db.execute = execute
  46. db.add = MagicMock()
  47. return db
  48. # HT tray 128 holds spool 7; AMS 0 slot 1 holds spool 8.
  49. ASSIGNED = {(128, 0): 7, (0, 1): 8}
  50. async def _track(ams_mapping, filament_usage, tray_change_log=None, total_layers=0, handled_trays=None, raw_data=None):
  51. spools = {7: _spool(7), 8: _spool(8)}
  52. printer_manager = MagicMock()
  53. printer_manager.get_status.return_value = SimpleNamespace(
  54. progress=100,
  55. layer_num=90,
  56. total_layers=total_layers,
  57. tray_now=128,
  58. last_loaded_tray=-1,
  59. tray_change_log=tray_change_log or [],
  60. raw_data=raw_data or {},
  61. )
  62. async def resolve(printer_id, ams_id, tray_id, **kwargs):
  63. return ASSIGNED.get((ams_id, tray_id))
  64. with (
  65. patch("backend.app.core.config.settings") as mock_settings,
  66. patch("backend.app.utils.threemf_tools.extract_filament_usage_from_3mf", return_value=filament_usage),
  67. patch("backend.app.utils.threemf_tools.extract_layer_filament_usage_from_3mf", return_value=None),
  68. patch("backend.app.utils.threemf_tools.extract_filament_properties_from_3mf", return_value={}),
  69. patch("backend.app.services.usage_tracker._resolve_spool_id_for_tray", side_effect=resolve),
  70. ):
  71. mock_path = MagicMock()
  72. mock_path.exists.return_value = True
  73. mock_settings.base_dir = MagicMock()
  74. mock_settings.base_dir.__truediv__ = MagicMock(return_value=mock_path)
  75. results = await _track_from_3mf(
  76. printer_id=1,
  77. archive_id=3230,
  78. status="completed",
  79. print_name="shared_tray",
  80. handled_trays=handled_trays if handled_trays is not None else set(),
  81. printer_manager=printer_manager,
  82. db=_db(spools),
  83. ams_mapping=ams_mapping,
  84. print_started_at=datetime.now(timezone.utc),
  85. )
  86. return results, spools
  87. def _usage(slot_id: int, used_g: float) -> dict:
  88. return {"slot_id": slot_id, "used_g": used_g, "type": "PLA", "color": "#FFFFFF"}
  89. class TestSharedTray:
  90. @pytest.mark.asyncio
  91. async def test_two_slots_on_one_tray_are_both_charged(self):
  92. # The reporter's job, verbatim mapping and grams.
  93. results, spools = await _track([128, -1, -1, 128, -1], [_usage(1, 1.05), _usage(4, 2.13)])
  94. assert [(r["slot_id"], r["spool_id"], r["weight_used"]) for r in results] == [(1, 7, 1.1), (4, 7, 2.1)]
  95. assert spools[7].weight_used == pytest.approx(3.18)
  96. @pytest.mark.asyncio
  97. async def test_slots_on_different_trays_are_unchanged(self):
  98. results, spools = await _track([128, 1], [_usage(1, 1.0), _usage(2, 2.0)])
  99. assert [r["spool_id"] for r in results] == [7, 8]
  100. assert spools[7].weight_used == pytest.approx(1.0)
  101. assert spools[8].weight_used == pytest.approx(2.0)
  102. @pytest.mark.asyncio
  103. async def test_a_shared_tray_is_still_handed_to_the_remain_fallback_as_covered(self):
  104. handled: set = set()
  105. await _track([128, -1, -1, 128, -1], [_usage(1, 1.05), _usage(4, 2.13)], handled_trays=handled)
  106. assert handled == {(128, 0)}
  107. @pytest.mark.asyncio
  108. async def test_a_slot_listed_once_per_plate_is_charged_once(self):
  109. # With the plate unknown, every plate of the file is listed, so slot 1
  110. # appears once per plate. Charging it per plate would multiply the debit.
  111. results, spools = await _track([128], [_usage(1, 4.0), _usage(1, 4.0), _usage(1, 4.0)])
  112. assert len(results) == 1
  113. assert spools[7].weight_used == pytest.approx(4.0)
  114. class TestReturningToATray:
  115. @pytest.mark.asyncio
  116. async def test_every_segment_is_charged_when_a_print_returns_to_an_earlier_tray(self):
  117. # Single-filament print: HT tray, then AMS 0 slot 1, then back to the HT
  118. # tray. Linear split over 90 layers gives a third per segment.
  119. results, spools = await _track(
  120. [128],
  121. [_usage(1, 9.0)],
  122. tray_change_log=[(128, 0), (1, 30), (128, 60)],
  123. total_layers=90,
  124. )
  125. assert [r["spool_id"] for r in results] == [7, 8, 7]
  126. assert spools[7].weight_used == pytest.approx(6.0)
  127. assert spools[8].weight_used == pytest.approx(3.0)
  128. class TestGuessedTrays:
  129. @pytest.mark.asyncio
  130. async def test_a_guessed_tray_already_charged_is_not_charged_again(self):
  131. # No mapping: slot 1 takes the only loaded tray (AMS 0 slot 1, global
  132. # 1), slot 2 is past the loaded trays and falls back to slot_id - 1,
  133. # the same tray. A position guess says nothing about which spool fed
  134. # slot 2, so it is not added to slot 1's spool.
  135. raw = {"ams": [{"id": "0", "tray": [{"id": "1", "tray_type": "PLA"}]}]}
  136. with patch(
  137. "backend.app.services.spoolman_tracking.build_ams_tray_lookup", return_value={1: {"tray_type": "PLA"}}
  138. ):
  139. results, spools = await _track(None, [_usage(1, 1.0), _usage(2, 2.0)], raw_data=raw)
  140. assert [r["slot_id"] for r in results] == [1]
  141. assert spools[8].weight_used == pytest.approx(1.0)