test_assign_preset_cloud_user_3519.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. """A custom cloud preset resolves the same way from an API key and on insert (#3519).
  2. With login on, each user signs in to Bambu Cloud separately and the shared
  3. sign-in is empty. An API key (a SpoolBuddy client) has no signed-in user, and
  4. the replay on insert has none either, so both looked the PFUS preset up with
  5. nobody's sign-in and sent Generic PLA (GFL99) where the web UI sent the
  6. preset's own filament. Both now use a user: the key's owner, and whoever made
  7. the assignment.
  8. """
  9. import logging
  10. from unittest.mock import AsyncMock, MagicMock, patch
  11. import pytest
  12. from httpx import AsyncClient
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.models.spool import Spool
  15. from backend.app.models.spool_assignment import SpoolAssignment
  16. PFUS = "PFUSdfae86e31579cb"
  17. def _status(ams_data):
  18. status = MagicMock()
  19. status.raw_data = {"ams": {"ams": ams_data}}
  20. status.nozzles = [MagicMock(nozzle_diameter="0.4")]
  21. status.ams_extruder_map = None
  22. return status
  23. def _fake_cloud(seen: list):
  24. """build_authenticated_cloud stand-in: records whose sign-in was asked for.
  25. Only a user's own sign-in finds the preset, as on a per-user install
  26. where the shared one is empty.
  27. """
  28. cloud = MagicMock()
  29. cloud.is_authenticated = True
  30. cloud.get_setting_detail = AsyncMock(return_value={"filament_id": "SUN20011", "name": "SUNLU PLA META"})
  31. cloud.close = AsyncMock()
  32. async def build(_db, user):
  33. seen.append(user.id if user is not None else None)
  34. return cloud if user is not None else None
  35. return build
  36. @pytest.fixture
  37. async def auth_on(db_session: AsyncSession):
  38. from backend.app.models.settings import Settings
  39. db_session.add(Settings(key="auth_enabled", value="true"))
  40. await db_session.commit()
  41. @pytest.fixture
  42. async def owner(db_session: AsyncSession):
  43. from backend.app.models.user import User
  44. user = User(username="spoolowner", password_hash="x", role="admin", is_active=True)
  45. db_session.add(user)
  46. await db_session.commit()
  47. await db_session.refresh(user)
  48. return user
  49. @pytest.fixture
  50. async def spool(db_session: AsyncSession):
  51. row = Spool(
  52. material="PLA",
  53. subtype="Basic",
  54. brand="SUNLU",
  55. rgba="FF0000FF",
  56. label_weight=1000,
  57. weight_used=0,
  58. slicer_filament=PFUS,
  59. )
  60. db_session.add(row)
  61. await db_session.commit()
  62. await db_session.refresh(row)
  63. return row
  64. async def _owned_key(db_session: AsyncSession, user_id: int | None) -> str:
  65. from backend.app.core.auth import generate_api_key
  66. from backend.app.models.api_key import APIKey
  67. full_key, key_hash, key_prefix = generate_api_key()
  68. db_session.add(
  69. APIKey(
  70. name="espoolbuddy",
  71. key_hash=key_hash,
  72. key_prefix=key_prefix,
  73. user_id=user_id,
  74. can_manage_inventory=True,
  75. can_read_status=True,
  76. enabled=True,
  77. )
  78. )
  79. await db_session.commit()
  80. return full_key
  81. async def _assign_with_key(async_client: AsyncClient, key: str, printer_id: int, spool_id: int, seen: list):
  82. mock_client = MagicMock()
  83. mock_client.ams_set_filament_setting.return_value = True
  84. mock_client.extrusion_cali_sel.return_value = True
  85. status = _status([{"id": 0, "tray": [{"id": 0, "tray_info_idx": "", "tray_type": "PLA", "state": 11}]}])
  86. with (
  87. patch("backend.app.services.printer_manager.printer_manager") as mock_pm,
  88. patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud(seen)),
  89. ):
  90. mock_pm.get_client.return_value = mock_client
  91. mock_pm.get_status.return_value = status
  92. response = await async_client.post(
  93. "/api/v1/inventory/assignments",
  94. json={"spool_id": spool_id, "printer_id": printer_id, "ams_id": 0, "tray_id": 0},
  95. headers={"X-API-Key": key},
  96. )
  97. return response, mock_client
  98. async def _replay(printer_id: int, seen: list):
  99. from backend.app.main import on_ams_change
  100. ams_data = [{"id": 0, "tray": [{"id": 0, "tray_type": "PLA", "tray_color": "FF0000FF", "state": 11}]}]
  101. mock_client = MagicMock()
  102. mock_client.ams_set_filament_setting.return_value = True
  103. mock_client.extrusion_cali_sel.return_value = True
  104. status = _status(ams_data)
  105. with (
  106. patch("backend.app.main.printer_manager") as mock_pm_main,
  107. patch("backend.app.services.printer_manager.printer_manager") as mock_pm_inv,
  108. patch("backend.app.main.mqtt_relay") as mock_relay,
  109. patch("backend.app.main.ws_manager") as mock_ws,
  110. patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud(seen)),
  111. ):
  112. mock_pm_main.get_printer.return_value = MagicMock(name="H2C", serial_number="0948BB540200427")
  113. mock_pm_main.get_status.return_value = status
  114. mock_pm_main.get_client.return_value = mock_client
  115. mock_pm_main.get_model.return_value = "H2C"
  116. mock_pm_inv.get_client.return_value = mock_client
  117. mock_pm_inv.get_status.return_value = status
  118. mock_relay.on_ams_change = AsyncMock()
  119. mock_ws.send_printer_status = AsyncMock()
  120. mock_ws.broadcast = AsyncMock()
  121. await on_ams_change(printer_id, ams_data)
  122. return mock_client
  123. class TestApiKeyAssign:
  124. @pytest.mark.asyncio
  125. @pytest.mark.integration
  126. async def test_the_keys_owner_resolves_the_preset(
  127. self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
  128. ):
  129. printer = await printer_factory(name="H2C")
  130. key = await _owned_key(db_session, owner.id)
  131. seen: list = []
  132. response, mock_client = await _assign_with_key(async_client, key, printer.id, spool.id, seen)
  133. assert response.status_code == 200
  134. assert seen == [owner.id]
  135. kwargs = mock_client.ams_set_filament_setting.call_args.kwargs
  136. assert kwargs["tray_info_idx"] == "SUN20011"
  137. assert kwargs["setting_id"] == PFUS
  138. @pytest.mark.asyncio
  139. @pytest.mark.integration
  140. async def test_the_assignment_remembers_the_owner(
  141. self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
  142. ):
  143. printer = await printer_factory(name="H2C")
  144. key = await _owned_key(db_session, owner.id)
  145. response, _ = await _assign_with_key(async_client, key, printer.id, spool.id, [])
  146. assert response.status_code == 200
  147. row = await db_session.get(SpoolAssignment, response.json()["id"])
  148. await db_session.refresh(row)
  149. assert row.assigned_by_user_id == owner.id
  150. @pytest.mark.asyncio
  151. @pytest.mark.integration
  152. async def test_an_ownerless_key_still_assigns(
  153. self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, spool
  154. ):
  155. """A key from before keys had owners has no sign-in to use: generic, as before."""
  156. printer = await printer_factory(name="H2C")
  157. key = await _owned_key(db_session, None)
  158. seen: list = []
  159. response, mock_client = await _assign_with_key(async_client, key, printer.id, spool.id, seen)
  160. assert response.status_code == 200
  161. assert seen == [None]
  162. assert mock_client.ams_set_filament_setting.call_args.kwargs["tray_info_idx"] == "GFL99"
  163. class TestReplayOnInsert:
  164. async def _pre_assigned(self, db_session: AsyncSession, printer_id: int, spool_id: int, user_id: int | None):
  165. db_session.add(
  166. SpoolAssignment(
  167. spool_id=spool_id,
  168. printer_id=printer_id,
  169. ams_id=0,
  170. tray_id=0,
  171. fingerprint_color=None,
  172. fingerprint_type=None,
  173. assigned_by_user_id=user_id,
  174. )
  175. )
  176. await db_session.commit()
  177. @pytest.mark.asyncio
  178. @pytest.mark.integration
  179. async def test_the_assigning_user_resolves_the_preset(
  180. self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
  181. ):
  182. printer = await printer_factory(name="H2C")
  183. await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
  184. seen: list = []
  185. mock_client = await _replay(printer.id, seen)
  186. assert seen == [owner.id]
  187. assert mock_client.ams_set_filament_setting.call_args.kwargs["tray_info_idx"] == "SUN20011"
  188. @pytest.mark.asyncio
  189. @pytest.mark.integration
  190. async def test_with_login_off_the_shared_sign_in_applies(
  191. self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, owner, spool
  192. ):
  193. """A user id kept from when login was on doesn't pick a per-user sign-in."""
  194. printer = await printer_factory(name="H2C")
  195. await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
  196. seen: list = []
  197. await _replay(printer.id, seen)
  198. assert seen == [None]
  199. @pytest.mark.asyncio
  200. @pytest.mark.integration
  201. async def test_a_deactivated_user_is_not_used(
  202. self, async_client: AsyncClient, db_session: AsyncSession, printer_factory, auth_on, owner, spool
  203. ):
  204. owner.is_active = False
  205. await db_session.commit()
  206. printer = await printer_factory(name="H2C")
  207. await self._pre_assigned(db_session, printer.id, spool.id, owner.id)
  208. seen: list = []
  209. await _replay(printer.id, seen)
  210. assert seen == [None]
  211. class TestUnresolvedPresetIsLogged:
  212. @pytest.mark.asyncio
  213. @pytest.mark.integration
  214. async def test_a_custom_preset_without_a_sign_in_warns(self, db_session: AsyncSession, caplog):
  215. from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
  216. with (
  217. patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud([])),
  218. caplog.at_level(logging.WARNING, logger="backend.app.services.slicer_filament_resolver"),
  219. ):
  220. await resolve_slicer_filament(
  221. db=db_session, current_user=None, slicer_filament=PFUS, slicer_filament_name=None, material="PLA"
  222. )
  223. assert any("not looked up" in r.getMessage() and PFUS in r.getMessage() for r in caplog.records)
  224. @pytest.mark.asyncio
  225. @pytest.mark.integration
  226. async def test_an_official_preset_does_not(self, db_session: AsyncSession, caplog):
  227. """A GFS id parses without the cloud, so nothing is lost."""
  228. from backend.app.services.slicer_filament_resolver import resolve_slicer_filament
  229. with (
  230. patch("backend.app.api.routes.cloud.build_authenticated_cloud", new=_fake_cloud([])),
  231. caplog.at_level(logging.WARNING, logger="backend.app.services.slicer_filament_resolver"),
  232. ):
  233. await resolve_slicer_filament(
  234. db=db_session, current_user=None, slicer_filament="GFSL05", slicer_filament_name=None, material="PLA"
  235. )
  236. assert not any("not looked up" in r.getMessage() for r in caplog.records)
  237. class TestDeletedUser:
  238. @pytest.mark.asyncio
  239. @pytest.mark.integration
  240. async def test_deleting_the_user_clears_the_assignment_s_user(
  241. self, db_session: AsyncSession, printer_factory, owner, spool
  242. ):
  243. """Or the next user given the freed id would lend the slot their sign-in."""
  244. from sqlalchemy import select
  245. printer = await printer_factory(name="H2C")
  246. db_session.add(
  247. SpoolAssignment(spool_id=spool.id, printer_id=printer.id, ams_id=0, tray_id=0, assigned_by_user_id=owner.id)
  248. )
  249. await db_session.commit()
  250. await db_session.delete(owner)
  251. await db_session.commit()
  252. db_session.expire_all()
  253. row = (await db_session.execute(select(SpoolAssignment))).scalar_one()
  254. assert row.assigned_by_user_id is None