test_archives_api.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. """Integration tests for Archives API endpoints.
  2. Tests the full request/response cycle for /api/v1/archives/ endpoints.
  3. """
  4. import pytest
  5. from httpx import AsyncClient
  6. class TestArchivesAPI:
  7. """Integration tests for /api/v1/archives/ endpoints."""
  8. # ========================================================================
  9. # List endpoints
  10. # ========================================================================
  11. @pytest.mark.asyncio
  12. @pytest.mark.integration
  13. async def test_list_archives_empty(self, async_client: AsyncClient):
  14. """Verify empty list is returned when no archives exist."""
  15. response = await async_client.get("/api/v1/archives/")
  16. assert response.status_code == 200
  17. data = response.json()
  18. assert isinstance(data, list)
  19. assert len(data) == 0
  20. @pytest.mark.asyncio
  21. @pytest.mark.integration
  22. async def test_list_archives_with_data(
  23. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  24. ):
  25. """Verify list returns existing archives."""
  26. printer = await printer_factory()
  27. await archive_factory(printer.id, print_name="Test Archive")
  28. response = await async_client.get("/api/v1/archives/")
  29. assert response.status_code == 200
  30. data = response.json()
  31. assert isinstance(data, list)
  32. assert len(data) >= 1
  33. assert any(a["print_name"] == "Test Archive" for a in data)
  34. @pytest.mark.asyncio
  35. @pytest.mark.integration
  36. async def test_list_archives_pagination(
  37. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  38. ):
  39. """Verify pagination works correctly."""
  40. printer = await printer_factory()
  41. # Create 5 archives
  42. for i in range(5):
  43. await archive_factory(printer.id, print_name=f"Archive {i}")
  44. # Get first page with limit 2
  45. response = await async_client.get("/api/v1/archives/?limit=2&offset=0")
  46. assert response.status_code == 200
  47. data = response.json()
  48. assert isinstance(data, list)
  49. assert len(data) == 2
  50. @pytest.mark.asyncio
  51. @pytest.mark.integration
  52. async def test_list_archives_filter_by_printer(
  53. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  54. ):
  55. """Verify filtering by printer_id works."""
  56. printer1 = await printer_factory(name="Printer 1", serial_number="00M09A000000001")
  57. printer2 = await printer_factory(name="Printer 2", serial_number="00M09A000000002")
  58. await archive_factory(printer1.id, print_name="Printer 1 Archive")
  59. await archive_factory(printer2.id, print_name="Printer 2 Archive")
  60. response = await async_client.get(f"/api/v1/archives/?printer_id={printer1.id}")
  61. assert response.status_code == 200
  62. data = response.json()
  63. assert all(a["printer_id"] == printer1.id for a in data)
  64. # ========================================================================
  65. # Get single endpoint
  66. # ========================================================================
  67. @pytest.mark.asyncio
  68. @pytest.mark.integration
  69. async def test_get_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  70. """Verify single archive can be retrieved."""
  71. printer = await printer_factory()
  72. archive = await archive_factory(printer.id, print_name="Get Test Archive")
  73. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  74. assert response.status_code == 200
  75. result = response.json()
  76. assert result["id"] == archive.id
  77. assert result["print_name"] == "Get Test Archive"
  78. @pytest.mark.asyncio
  79. @pytest.mark.integration
  80. async def test_get_archive_not_found(self, async_client: AsyncClient):
  81. """Verify 404 for non-existent archive."""
  82. response = await async_client.get("/api/v1/archives/9999")
  83. assert response.status_code == 404
  84. # ========================================================================
  85. # Update endpoints
  86. # ========================================================================
  87. @pytest.mark.asyncio
  88. @pytest.mark.integration
  89. async def test_update_archive_name(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  90. """Verify archive name can be updated."""
  91. printer = await printer_factory()
  92. archive = await archive_factory(printer.id, print_name="Original Name")
  93. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"print_name": "Updated Name"})
  94. assert response.status_code == 200
  95. assert response.json()["print_name"] == "Updated Name"
  96. @pytest.mark.asyncio
  97. @pytest.mark.integration
  98. async def test_update_archive_notes(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  99. """Verify archive notes can be updated."""
  100. printer = await printer_factory()
  101. archive = await archive_factory(printer.id)
  102. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Great print!"})
  103. assert response.status_code == 200
  104. assert response.json()["notes"] == "Great print!"
  105. @pytest.mark.asyncio
  106. @pytest.mark.integration
  107. async def test_update_archive_favorite(
  108. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  109. ):
  110. """Verify archive favorite status can be updated."""
  111. printer = await printer_factory()
  112. archive = await archive_factory(printer.id)
  113. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"is_favorite": True})
  114. assert response.status_code == 200
  115. assert response.json()["is_favorite"] is True
  116. @pytest.mark.asyncio
  117. @pytest.mark.integration
  118. async def test_update_archive_external_url(
  119. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  120. ):
  121. """Verify archive external_url can be updated."""
  122. printer = await printer_factory()
  123. archive = await archive_factory(printer.id)
  124. response = await async_client.patch(
  125. f"/api/v1/archives/{archive.id}", json={"external_url": "https://printables.com/model/12345"}
  126. )
  127. assert response.status_code == 200
  128. assert response.json()["external_url"] == "https://printables.com/model/12345"
  129. # Verify it can be cleared
  130. response = await async_client.patch(f"/api/v1/archives/{archive.id}", json={"external_url": None})
  131. assert response.status_code == 200
  132. assert response.json()["external_url"] is None
  133. # ========================================================================
  134. # Delete endpoints
  135. # ========================================================================
  136. @pytest.mark.asyncio
  137. @pytest.mark.integration
  138. async def test_delete_archive(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  139. """Verify archive can be deleted."""
  140. printer = await printer_factory()
  141. archive = await archive_factory(printer.id)
  142. archive_id = archive.id
  143. response = await async_client.delete(f"/api/v1/archives/{archive_id}")
  144. assert response.status_code == 200
  145. # Verify deleted
  146. response = await async_client.get(f"/api/v1/archives/{archive_id}")
  147. assert response.status_code == 404
  148. @pytest.mark.asyncio
  149. @pytest.mark.integration
  150. async def test_delete_nonexistent_archive(self, async_client: AsyncClient):
  151. """Verify deleting non-existent archive returns 404."""
  152. response = await async_client.delete("/api/v1/archives/9999")
  153. assert response.status_code == 404
  154. # ========================================================================
  155. # Statistics endpoints
  156. # ========================================================================
  157. @pytest.mark.asyncio
  158. @pytest.mark.integration
  159. async def test_get_archive_stats(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  160. """Verify archive statistics can be retrieved."""
  161. printer = await printer_factory()
  162. await archive_factory(
  163. printer.id,
  164. status="completed",
  165. print_time_seconds=3600,
  166. filament_used_grams=50.0,
  167. )
  168. await archive_factory(
  169. printer.id,
  170. status="completed",
  171. print_time_seconds=7200,
  172. filament_used_grams=100.0,
  173. )
  174. response = await async_client.get("/api/v1/archives/stats")
  175. assert response.status_code == 200
  176. result = response.json()
  177. # Check for actual stats fields
  178. assert "total_prints" in result
  179. assert "successful_prints" in result
  180. class TestArchivesSlimAPI:
  181. """Integration tests for /api/v1/archives/slim endpoint."""
  182. @pytest.mark.asyncio
  183. @pytest.mark.integration
  184. async def test_slim_empty(self, async_client: AsyncClient):
  185. """Verify empty list when no archives exist."""
  186. response = await async_client.get("/api/v1/archives/slim")
  187. assert response.status_code == 200
  188. assert response.json() == []
  189. @pytest.mark.asyncio
  190. @pytest.mark.integration
  191. async def test_slim_returns_only_expected_fields(
  192. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  193. ):
  194. """Verify response contains only slim fields, not full archive data."""
  195. printer = await printer_factory()
  196. await archive_factory(
  197. printer.id,
  198. print_name="Slim Test",
  199. status="completed",
  200. filament_type="PLA",
  201. filament_color="#FF0000",
  202. filament_used_grams=50.0,
  203. print_time_seconds=3600,
  204. cost=1.50,
  205. quantity=2,
  206. )
  207. response = await async_client.get("/api/v1/archives/slim")
  208. assert response.status_code == 200
  209. data = response.json()
  210. assert len(data) == 1
  211. item = data[0]
  212. # Expected fields present
  213. assert item["printer_id"] == printer.id
  214. assert item["print_name"] == "Slim Test"
  215. assert item["status"] == "completed"
  216. assert item["filament_type"] == "PLA"
  217. assert item["filament_color"] == "#FF0000"
  218. assert item["filament_used_grams"] == 50.0
  219. assert item["print_time_seconds"] == 3600
  220. assert item["cost"] == 1.50
  221. assert item["quantity"] == 2
  222. assert "created_at" in item
  223. # Full archive fields must NOT be present
  224. assert "id" not in item
  225. assert "filename" not in item
  226. assert "file_path" not in item
  227. assert "file_size" not in item
  228. assert "extra_data" not in item
  229. assert "notes" not in item
  230. assert "tags" not in item
  231. assert "photos" not in item
  232. assert "thumbnail_path" not in item
  233. assert "content_hash" not in item
  234. assert "duplicates" not in item
  235. assert "duplicate_count" not in item
  236. @pytest.mark.asyncio
  237. @pytest.mark.integration
  238. async def test_slim_computes_actual_time(
  239. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  240. ):
  241. """Verify actual_time_seconds is computed from started_at/completed_at."""
  242. from datetime import datetime, timezone
  243. printer = await printer_factory()
  244. started = datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
  245. completed = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc) # 2 hours = 7200s
  246. await archive_factory(
  247. printer.id,
  248. status="completed",
  249. started_at=started,
  250. completed_at=completed,
  251. )
  252. response = await async_client.get("/api/v1/archives/slim")
  253. assert response.status_code == 200
  254. item = response.json()[0]
  255. assert item["actual_time_seconds"] == 7200
  256. @pytest.mark.asyncio
  257. @pytest.mark.integration
  258. async def test_slim_actual_time_null_for_failed(
  259. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  260. ):
  261. """Verify actual_time_seconds is null for non-completed prints."""
  262. from datetime import datetime, timezone
  263. printer = await printer_factory()
  264. await archive_factory(
  265. printer.id,
  266. status="failed",
  267. started_at=datetime(2024, 1, 1, 10, 0, 0, tzinfo=timezone.utc),
  268. completed_at=datetime(2024, 1, 1, 11, 0, 0, tzinfo=timezone.utc),
  269. )
  270. response = await async_client.get("/api/v1/archives/slim")
  271. assert response.status_code == 200
  272. item = response.json()[0]
  273. assert item["actual_time_seconds"] is None
  274. @pytest.mark.asyncio
  275. @pytest.mark.integration
  276. async def test_slim_date_filtering(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  277. """Verify date_from and date_to filters work."""
  278. from datetime import datetime, timezone
  279. printer = await printer_factory()
  280. await archive_factory(
  281. printer.id,
  282. print_name="Old Print",
  283. created_at=datetime(2024, 1, 1, tzinfo=timezone.utc),
  284. )
  285. await archive_factory(
  286. printer.id,
  287. print_name="New Print",
  288. created_at=datetime(2024, 6, 15, tzinfo=timezone.utc),
  289. )
  290. # Filter to only June 2024
  291. response = await async_client.get("/api/v1/archives/slim?date_from=2024-06-01&date_to=2024-06-30")
  292. assert response.status_code == 200
  293. data = response.json()
  294. assert len(data) == 1
  295. assert data[0]["print_name"] == "New Print"
  296. @pytest.mark.asyncio
  297. @pytest.mark.integration
  298. async def test_slim_pagination(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  299. """Verify limit and offset work."""
  300. printer = await printer_factory()
  301. for i in range(5):
  302. await archive_factory(printer.id, print_name=f"Print {i}")
  303. response = await async_client.get("/api/v1/archives/slim?limit=2&offset=0")
  304. assert response.status_code == 200
  305. assert len(response.json()) == 2
  306. class TestArchiveDataIntegrity:
  307. """Tests for archive data integrity."""
  308. @pytest.mark.asyncio
  309. @pytest.mark.integration
  310. async def test_archive_linked_to_printer(
  311. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  312. ):
  313. """Verify archive is properly linked to printer."""
  314. printer = await printer_factory(name="My Printer")
  315. archive = await archive_factory(printer.id)
  316. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  317. assert response.status_code == 200
  318. result = response.json()
  319. assert result["printer_id"] == printer.id
  320. @pytest.mark.asyncio
  321. @pytest.mark.integration
  322. async def test_archive_stores_print_data(
  323. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  324. ):
  325. """Verify archive stores all print data correctly."""
  326. printer = await printer_factory()
  327. archive = await archive_factory(
  328. printer.id,
  329. print_name="Test Print",
  330. filename="test.3mf",
  331. status="completed",
  332. filament_type="PLA",
  333. filament_used_grams=75.5,
  334. print_time_seconds=5400,
  335. )
  336. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  337. assert response.status_code == 200
  338. result = response.json()
  339. assert result["print_name"] == "Test Print"
  340. assert result["filename"] == "test.3mf"
  341. assert result["status"] == "completed"
  342. assert result["filament_type"] == "PLA"
  343. assert result["filament_used_grams"] == 75.5
  344. assert result["print_time_seconds"] == 5400
  345. @pytest.mark.asyncio
  346. @pytest.mark.integration
  347. async def test_archive_update_persists(
  348. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  349. ):
  350. """CRITICAL: Verify archive updates persist."""
  351. printer = await printer_factory()
  352. archive = await archive_factory(printer.id, notes="Original notes")
  353. # Update
  354. await async_client.patch(f"/api/v1/archives/{archive.id}", json={"notes": "Updated notes", "is_favorite": True})
  355. # Verify persistence
  356. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  357. result = response.json()
  358. assert result["notes"] == "Updated notes"
  359. assert result["is_favorite"] is True
  360. class TestArchiveF3DEndpoints:
  361. """Tests for F3D (Fusion 360 design file) attachment endpoints."""
  362. @pytest.mark.asyncio
  363. @pytest.mark.integration
  364. async def test_archive_response_includes_f3d_path(
  365. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  366. ):
  367. """Verify f3d_path is included in archive response."""
  368. printer = await printer_factory()
  369. archive = await archive_factory(printer.id, f3d_path="archives/test/design.f3d")
  370. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  371. assert response.status_code == 200
  372. result = response.json()
  373. assert "f3d_path" in result
  374. assert result["f3d_path"] == "archives/test/design.f3d"
  375. @pytest.mark.asyncio
  376. @pytest.mark.integration
  377. async def test_archive_response_f3d_path_null_when_not_set(
  378. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  379. ):
  380. """Verify f3d_path is null when no F3D file attached."""
  381. printer = await printer_factory()
  382. archive = await archive_factory(printer.id)
  383. response = await async_client.get(f"/api/v1/archives/{archive.id}")
  384. assert response.status_code == 200
  385. result = response.json()
  386. assert "f3d_path" in result
  387. assert result["f3d_path"] is None
  388. @pytest.mark.asyncio
  389. @pytest.mark.integration
  390. async def test_upload_f3d_to_nonexistent_archive(self, async_client: AsyncClient):
  391. """Verify 404 when uploading F3D to non-existent archive."""
  392. # Create a minimal file-like upload
  393. files = {"file": ("design.f3d", b"fake f3d content", "application/octet-stream")}
  394. response = await async_client.post("/api/v1/archives/9999/f3d", files=files)
  395. assert response.status_code == 404
  396. @pytest.mark.asyncio
  397. @pytest.mark.integration
  398. async def test_download_f3d_not_found_when_no_file(
  399. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  400. ):
  401. """Verify 404 when downloading F3D from archive without F3D file."""
  402. printer = await printer_factory()
  403. archive = await archive_factory(printer.id)
  404. response = await async_client.get(f"/api/v1/archives/{archive.id}/f3d")
  405. assert response.status_code == 404
  406. @pytest.mark.asyncio
  407. @pytest.mark.integration
  408. async def test_download_f3d_nonexistent_archive(self, async_client: AsyncClient):
  409. """Verify 404 when downloading F3D from non-existent archive."""
  410. response = await async_client.get("/api/v1/archives/9999/f3d")
  411. assert response.status_code == 404
  412. @pytest.mark.asyncio
  413. @pytest.mark.integration
  414. async def test_delete_f3d_nonexistent_archive(self, async_client: AsyncClient):
  415. """Verify 404 when deleting F3D from non-existent archive."""
  416. response = await async_client.delete("/api/v1/archives/9999/f3d")
  417. assert response.status_code == 404
  418. @pytest.mark.asyncio
  419. @pytest.mark.integration
  420. async def test_delete_f3d_when_no_file(
  421. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  422. ):
  423. """Verify 404 when deleting F3D from archive without F3D file."""
  424. printer = await printer_factory()
  425. archive = await archive_factory(printer.id)
  426. response = await async_client.delete(f"/api/v1/archives/{archive.id}/f3d")
  427. assert response.status_code == 404
  428. @pytest.mark.asyncio
  429. @pytest.mark.integration
  430. async def test_list_archives_includes_f3d_path(
  431. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  432. ):
  433. """Verify f3d_path is included in archive list responses."""
  434. printer = await printer_factory()
  435. await archive_factory(printer.id, print_name="With F3D", f3d_path="archives/test/design.f3d")
  436. await archive_factory(printer.id, print_name="Without F3D")
  437. response = await async_client.get("/api/v1/archives/")
  438. assert response.status_code == 200
  439. data = response.json()
  440. assert len(data) >= 2
  441. with_f3d = next((a for a in data if a["print_name"] == "With F3D"), None)
  442. without_f3d = next((a for a in data if a["print_name"] == "Without F3D"), None)
  443. assert with_f3d is not None
  444. assert with_f3d["f3d_path"] == "archives/test/design.f3d"
  445. assert without_f3d is not None
  446. assert without_f3d["f3d_path"] is None
  447. # ========================================================================
  448. # Multi-Plate 3MF endpoints (Issue #93)
  449. # ========================================================================
  450. @pytest.mark.asyncio
  451. @pytest.mark.integration
  452. async def test_get_archive_plates_not_found(self, async_client: AsyncClient):
  453. """Verify 404 when fetching plates for non-existent archive."""
  454. response = await async_client.get("/api/v1/archives/999999/plates")
  455. assert response.status_code == 404
  456. @pytest.mark.asyncio
  457. @pytest.mark.integration
  458. async def test_get_plate_thumbnail_not_found(self, async_client: AsyncClient):
  459. """Verify 404 when fetching plate thumbnail for non-existent archive."""
  460. response = await async_client.get("/api/v1/archives/999999/plate-thumbnail/1")
  461. assert response.status_code == 404
  462. @pytest.mark.asyncio
  463. @pytest.mark.integration
  464. async def test_filament_requirements_not_found(self, async_client: AsyncClient):
  465. """Verify filament-requirements returns 404 for non-existent archive."""
  466. response = await async_client.get("/api/v1/archives/999999/filament-requirements")
  467. assert response.status_code == 404
  468. @pytest.mark.asyncio
  469. @pytest.mark.integration
  470. async def test_filament_requirements_with_plate_id_not_found(self, async_client: AsyncClient):
  471. """Verify filament-requirements with plate_id returns 404 for non-existent archive."""
  472. response = await async_client.get("/api/v1/archives/999999/filament-requirements?plate_id=1")
  473. assert response.status_code == 404
  474. # ========================================================================
  475. # Tag Management endpoints (Issue #183)
  476. # ========================================================================
  477. @pytest.mark.asyncio
  478. @pytest.mark.integration
  479. async def test_get_tags_empty(self, async_client: AsyncClient):
  480. """Verify empty list when no tags exist."""
  481. response = await async_client.get("/api/v1/archives/tags")
  482. assert response.status_code == 200
  483. data = response.json()
  484. assert isinstance(data, list)
  485. assert len(data) == 0
  486. @pytest.mark.asyncio
  487. @pytest.mark.integration
  488. async def test_get_tags_with_data(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  489. """Verify tags are returned with counts."""
  490. printer = await printer_factory()
  491. await archive_factory(printer.id, print_name="Archive 1", tags="functional, test")
  492. await archive_factory(printer.id, print_name="Archive 2", tags="functional, calibration")
  493. await archive_factory(printer.id, print_name="Archive 3", tags="test")
  494. response = await async_client.get("/api/v1/archives/tags")
  495. assert response.status_code == 200
  496. data = response.json()
  497. assert isinstance(data, list)
  498. # Convert to dict for easier lookup
  499. tags_dict = {t["name"]: t["count"] for t in data}
  500. assert tags_dict.get("functional") == 2
  501. assert tags_dict.get("test") == 2
  502. assert tags_dict.get("calibration") == 1
  503. @pytest.mark.asyncio
  504. @pytest.mark.integration
  505. async def test_get_tags_sorted_by_count(
  506. self, async_client: AsyncClient, archive_factory, printer_factory, db_session
  507. ):
  508. """Verify tags are sorted by count descending, then by name."""
  509. printer = await printer_factory()
  510. await archive_factory(printer.id, tags="alpha")
  511. await archive_factory(printer.id, tags="beta, alpha")
  512. await archive_factory(printer.id, tags="gamma, beta, alpha")
  513. response = await async_client.get("/api/v1/archives/tags")
  514. assert response.status_code == 200
  515. data = response.json()
  516. # alpha=3, beta=2, gamma=1
  517. assert data[0]["name"] == "alpha"
  518. assert data[0]["count"] == 3
  519. assert data[1]["name"] == "beta"
  520. assert data[1]["count"] == 2
  521. assert data[2]["name"] == "gamma"
  522. assert data[2]["count"] == 1
  523. @pytest.mark.asyncio
  524. @pytest.mark.integration
  525. async def test_rename_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  526. """Verify renaming a tag updates all archives."""
  527. printer = await printer_factory()
  528. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="old-tag, other")
  529. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="old-tag")
  530. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  531. response = await async_client.put("/api/v1/archives/tags/old-tag", json={"new_name": "new-tag"})
  532. assert response.status_code == 200
  533. data = response.json()
  534. assert data["affected"] == 2
  535. # Verify the archives were updated
  536. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  537. assert "new-tag" in response.json()["tags"]
  538. assert "old-tag" not in response.json()["tags"]
  539. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  540. assert response.json()["tags"] == "new-tag"
  541. @pytest.mark.asyncio
  542. @pytest.mark.integration
  543. async def test_rename_tag_no_change(self, async_client: AsyncClient):
  544. """Verify renaming to same name returns 0 affected."""
  545. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": "some-tag"})
  546. assert response.status_code == 200
  547. assert response.json()["affected"] == 0
  548. @pytest.mark.asyncio
  549. @pytest.mark.integration
  550. async def test_rename_tag_empty_name_error(self, async_client: AsyncClient):
  551. """Verify renaming to empty name returns error."""
  552. response = await async_client.put("/api/v1/archives/tags/some-tag", json={"new_name": ""})
  553. assert response.status_code == 400
  554. @pytest.mark.asyncio
  555. @pytest.mark.integration
  556. async def test_delete_tag(self, async_client: AsyncClient, archive_factory, printer_factory, db_session):
  557. """Verify deleting a tag removes it from all archives."""
  558. printer = await printer_factory()
  559. a1 = await archive_factory(printer.id, print_name="Archive 1", tags="delete-me, keep")
  560. a2 = await archive_factory(printer.id, print_name="Archive 2", tags="delete-me")
  561. await archive_factory(printer.id, print_name="Archive 3", tags="different")
  562. response = await async_client.delete("/api/v1/archives/tags/delete-me")
  563. assert response.status_code == 200
  564. data = response.json()
  565. assert data["affected"] == 2
  566. # Verify the archives were updated
  567. response = await async_client.get(f"/api/v1/archives/{a1.id}")
  568. assert response.json()["tags"] == "keep"
  569. response = await async_client.get(f"/api/v1/archives/{a2.id}")
  570. # Should be None or empty when last tag is removed
  571. assert response.json()["tags"] is None or response.json()["tags"] == ""
  572. @pytest.mark.asyncio
  573. @pytest.mark.integration
  574. async def test_delete_tag_not_found(self, async_client: AsyncClient):
  575. """Verify deleting non-existent tag returns 0 affected."""
  576. response = await async_client.delete("/api/v1/archives/tags/nonexistent-tag")
  577. assert response.status_code == 200
  578. assert response.json()["affected"] == 0