test_filament_scope.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. """FilamentScope semantics (#3522)."""
  2. from __future__ import annotations
  3. import json
  4. from pathlib import Path
  5. from types import SimpleNamespace
  6. from unittest.mock import AsyncMock, MagicMock, patch
  7. import pytest
  8. from fastapi import HTTPException
  9. from backend.app.core.filament_scope import (
  10. ALL_FILAMENTS,
  11. NO_FILAMENTS,
  12. FilamentRule,
  13. FilamentScope,
  14. GroupFilamentPolicy,
  15. clean_rules,
  16. describe_filament,
  17. ensure_requirements_allowed,
  18. judged_requirements,
  19. policy_for_group,
  20. resolve_user_filament_scope,
  21. resolve_user_id_filament_scope,
  22. )
  23. PETG = FilamentRule("material", "PETG")
  24. PETG_MATTE = FilamentRule("filament_id", "GFG03")
  25. def _block(*rules):
  26. return GroupFilamentPolicy("Friends", "block", tuple(rules))
  27. def _allow(*rules):
  28. return GroupFilamentPolicy("Friends", "allow", tuple(rules))
  29. class TestRule:
  30. def test_material_matches_case_insensitively_and_exactly(self):
  31. assert PETG.matches("petg", None)
  32. assert PETG.matches(" PETG ", "")
  33. assert not PETG.matches("PETG-HF", None)
  34. def test_filament_id_matches_the_tray_info_idx(self):
  35. assert PETG_MATTE.matches("PETG", "gfg03")
  36. assert not PETG_MATTE.matches("PETG", "GFG99")
  37. assert not PETG_MATTE.matches("PETG", None)
  38. def test_empty_value_matches_nothing(self):
  39. assert not FilamentRule("material", " ").matches("", "")
  40. class TestPolicy:
  41. def test_block_list_allows_what_it_does_not_name(self):
  42. policy = _block(PETG_MATTE)
  43. assert not policy.allows("PETG", "GFG03")
  44. assert policy.allows("PETG", "GFG99")
  45. def test_allow_list_allows_only_what_it_names(self):
  46. policy = _allow(FilamentRule("material", "PLA"))
  47. assert policy.allows("PLA", "GFA00")
  48. assert not policy.allows("PETG", "GFG03")
  49. class TestScope:
  50. def test_unrestricted_allows_everything(self):
  51. assert ALL_FILAMENTS.is_unrestricted
  52. assert ALL_FILAMENTS.allows("PAHT-CF", "GFN03")
  53. def test_union_of_groups(self):
  54. scope = FilamentScope((_allow(FilamentRule("material", "PLA")), _allow(FilamentRule("material", "PETG"))))
  55. assert scope.allows("PLA", None)
  56. assert scope.allows("PETG", None)
  57. assert not scope.allows("ABS", None)
  58. def test_block_group_does_not_narrow_an_allow_group(self):
  59. # Allowed by any restricted group means allowed.
  60. scope = FilamentScope((_block(PETG), _allow(PETG)))
  61. assert scope.allows("PETG", None)
  62. def test_unidentifiable_filament_is_allowed(self):
  63. assert FilamentScope((_allow(FilamentRule("material", "PLA")),)).allows("", "")
  64. assert NO_FILAMENTS.allows(None, None)
  65. def test_no_policies_allows_nothing_identifiable(self):
  66. assert not NO_FILAMENTS.allows("PLA", None)
  67. def test_blocked_requirements_and_trays(self):
  68. scope = FilamentScope((_block(PETG_MATTE),))
  69. reqs = [
  70. {"slot_id": 1, "type": "PETG", "tray_info_idx": "GFG03"},
  71. {"slot_id": 2, "type": "PLA", "tray_info_idx": "GFA00"},
  72. ]
  73. assert [r["slot_id"] for r in scope.blocked_requirements(reqs)] == [1]
  74. loaded = [
  75. {"type": "PETG", "tray_info_idx": "GFG03", "global_tray_id": 0},
  76. {"type": "PETG", "tray_info_idx": "GFG99", "global_tray_id": 1},
  77. ]
  78. assert scope.blocked_tray_ids(loaded) == {0}
  79. class TestCleanRules:
  80. def test_strips_dedupes_and_drops_junk(self):
  81. raw = [
  82. {"match": "material", "value": " petg "},
  83. {"match": "material", "value": "PETG"},
  84. {"match": "filament_id", "value": "GFG03"},
  85. {"match": "colour", "value": "red"},
  86. {"match": "material", "value": ""},
  87. "junk",
  88. ]
  89. assert clean_rules(raw) == [
  90. {"match": "material", "value": "PETG"},
  91. {"match": "filament_id", "value": "GFG03"},
  92. ]
  93. def test_accepts_objects_with_attributes(self):
  94. assert clean_rules([SimpleNamespace(match="filament_id", value="GFG03")]) == [
  95. {"match": "filament_id", "value": "GFG03"}
  96. ]
  97. def _group(name, restrict, mode="block", rules=None):
  98. return SimpleNamespace(name=name, restrict_filaments=restrict, filament_rule_mode=mode, filament_rules=rules)
  99. class TestResolveUser:
  100. def test_admin_is_unrestricted(self):
  101. user = SimpleNamespace(
  102. is_admin=True, groups=[_group("Friends", True, rules=[{"match": "material", "value": "PETG"}])]
  103. )
  104. assert resolve_user_filament_scope(user).is_unrestricted
  105. def test_user_in_no_restricted_group_is_unrestricted(self):
  106. user = SimpleNamespace(is_admin=False, groups=[_group("Operators", False)])
  107. assert resolve_user_filament_scope(user).is_unrestricted
  108. def test_only_restricted_groups_count(self):
  109. user = SimpleNamespace(
  110. is_admin=False,
  111. groups=[
  112. _group("Operators", False),
  113. _group("Friends", True, rules=[{"match": "material", "value": "PETG"}]),
  114. ],
  115. )
  116. scope = resolve_user_filament_scope(user)
  117. assert not scope.allows("PETG", None)
  118. assert scope.allows("PLA", None)
  119. def test_policy_for_group_tolerates_missing_values(self):
  120. policy = policy_for_group(_group("Friends", True, mode=None, rules=None))
  121. assert policy.mode == "block"
  122. assert policy.rules == ()
  123. class TestMessages:
  124. def test_describe(self):
  125. assert describe_filament({"type": "PETG", "tray_info_idx": "GFG03"}) == "PETG (GFG03)"
  126. assert describe_filament({"type": "PLA", "tray_info_idx": ""}) == "PLA"
  127. assert describe_filament({"type": "", "tray_info_idx": "GFG03"}) == "GFG03"
  128. def test_ensure_raises_403_naming_the_filament(self):
  129. scope = FilamentScope((_block(PETG_MATTE),))
  130. with pytest.raises(HTTPException) as exc:
  131. ensure_requirements_allowed(scope, [{"type": "PETG", "tray_info_idx": "GFG03"}])
  132. assert exc.value.status_code == 403
  133. assert "PETG (GFG03)" in exc.value.detail
  134. def test_ensure_passes_when_allowed(self):
  135. ensure_requirements_allowed(ALL_FILAMENTS, [{"type": "PETG", "tray_info_idx": "GFG03"}])
  136. def test_ensure_passes_a_restricted_user_whose_filaments_are_all_allowed(self):
  137. scope = FilamentScope((_block(PETG_MATTE),))
  138. ensure_requirements_allowed(
  139. scope, [{"type": "PETG", "tray_info_idx": "GFG99"}, {"type": "PLA", "tray_info_idx": "GFA00"}]
  140. )
  141. async def _resolve_id(user, *, auth_enabled: bool = True, user_id: int | None = 7):
  142. result = MagicMock()
  143. result.scalar_one_or_none.return_value = user
  144. db = MagicMock()
  145. db.execute = AsyncMock(return_value=result)
  146. with patch("backend.app.core.auth.is_auth_enabled", AsyncMock(return_value=auth_enabled)):
  147. return await resolve_user_id_filament_scope(db, user_id), db
  148. def _restricted_user(**fields):
  149. group = SimpleNamespace(
  150. name="Friends",
  151. restrict_filaments=True,
  152. filament_rule_mode="block",
  153. filament_rules=[{"match": "filament_id", "value": "GFG03"}],
  154. )
  155. values = {"is_admin": False, "is_active": True, "groups": [group]}
  156. values.update(fields)
  157. return SimpleNamespace(**values)
  158. @pytest.mark.asyncio
  159. class TestResolveUserId:
  160. """The scheduler and the queue route read a scope by user id (#3522)."""
  161. async def test_auth_off_is_unrestricted_without_a_lookup(self):
  162. scope, db = await _resolve_id(_restricted_user(), auth_enabled=False)
  163. assert scope is ALL_FILAMENTS
  164. db.execute.assert_not_awaited()
  165. async def test_no_user_is_unrestricted(self):
  166. scope, db = await _resolve_id(_restricted_user(), user_id=None)
  167. assert scope is ALL_FILAMENTS
  168. db.execute.assert_not_awaited()
  169. async def test_a_deactivated_user_may_use_nothing_identifiable(self):
  170. scope, _ = await _resolve_id(_restricted_user(is_active=False))
  171. assert scope is NO_FILAMENTS
  172. async def test_a_deleted_user_may_use_nothing_identifiable(self):
  173. scope, _ = await _resolve_id(None)
  174. assert scope is NO_FILAMENTS
  175. async def test_an_active_user_gets_their_groups_rules(self):
  176. scope, _ = await _resolve_id(_restricted_user())
  177. assert not scope.allows("PETG", "GFG03")
  178. assert scope.allows("PETG", "GFG99")
  179. # The print dialog's copy of these rules (``frontend/src/utils/filamentScope.ts``)
  180. # reads the same cases, so the two can't disagree on a filament.
  181. _SHARED_CASES = (
  182. Path(__file__).resolve().parents[3] / "frontend" / "src" / "__tests__" / "utils" / "filamentScopeCases.json"
  183. )
  184. @pytest.mark.parametrize("case", json.loads(_SHARED_CASES.read_text())["cases"], ids=lambda c: c["name"])
  185. def test_shared_cases_with_the_print_dialog(case):
  186. rules = tuple(FilamentRule(r["match"], r["value"]) for r in case["rules"])
  187. scope = FilamentScope((GroupFilamentPolicy("Friends", case["mode"], rules),))
  188. assert scope.allows(case["type"], case["filament_id"]) is case["allowed"]
  189. class TestJudgedRequirements:
  190. """One rule for overrides wherever a file is judged: the queue route, the scheduler, the dialog (#3522)."""
  191. REQS = [
  192. {"slot_id": 1, "type": "PETG", "tray_info_idx": "GFG03"},
  193. {"slot_id": 2, "type": "PLA", "tray_info_idx": "GFA00"},
  194. ]
  195. def test_without_overrides_the_file_is_judged_as_sliced(self):
  196. assert judged_requirements(self.REQS, None) == self.REQS
  197. def test_a_swap_is_left_to_the_tray_matcher(self):
  198. swap = [{"slot_id": 1, "type": "PETG", "color": "#000000", "force_color_match": False}]
  199. assert judged_requirements(self.REQS, swap) == [self.REQS[1]]
  200. def test_a_forced_colour_naming_an_id_is_judged_as_it_names_it(self):
  201. forced = [{"slot_id": 2, "type": "PETG", "tray_info_idx": "GFG03", "force_color_match": True}]
  202. assert judged_requirements(self.REQS, forced) == [
  203. self.REQS[0],
  204. {"slot_id": 2, "type": "PETG", "tray_info_idx": "GFG03"},
  205. ]
  206. def test_a_forced_colour_naming_no_id_is_left_to_the_tray_matcher(self):
  207. forced = [{"slot_id": 1, "type": "PETG", "force_color_match": True}]
  208. assert judged_requirements(self.REQS, forced) == [self.REQS[1]]
  209. def test_junk_entries_are_ignored(self):
  210. assert judged_requirements(self.REQS, ["x", {"slot_id": True}, {"type": "PLA"}]) == self.REQS