test_github_restore_api.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. """Integration tests for the Git backup restore API endpoints (#2656)."""
  2. from unittest.mock import AsyncMock, patch
  3. import pytest
  4. from httpx import AsyncClient
  5. @pytest.fixture(autouse=True)
  6. def _mock_private_repo_check():
  7. """POST /config refuses to save unless the repo is confirmed private."""
  8. with patch(
  9. "backend.app.services.github_backup.github_backup_service.test_connection",
  10. new=AsyncMock(
  11. return_value={
  12. "success": True,
  13. "message": "Connection successful",
  14. "repo_name": "test/repo",
  15. "permissions": {"push": True},
  16. "is_private": True,
  17. }
  18. ),
  19. ) as m:
  20. yield m
  21. async def _create_config(async_client: AsyncClient) -> dict:
  22. response = await async_client.post(
  23. "/api/v1/github-backup/config",
  24. json={
  25. "repository_url": "https://github.com/test/repo",
  26. "access_token": "ghp_testtoken123",
  27. "branch": "main",
  28. "backup_kprofiles": True,
  29. "backup_spools": True,
  30. "backup_archives": True,
  31. "backup_settings": True,
  32. "enabled": True,
  33. },
  34. )
  35. assert response.status_code == 200
  36. return response.json()
  37. class TestCommitsEndpoint:
  38. @pytest.mark.asyncio
  39. @pytest.mark.integration
  40. async def test_404_when_not_configured(self, async_client: AsyncClient):
  41. response = await async_client.get("/api/v1/github-backup/commits")
  42. assert response.status_code == 404
  43. assert "Configure backup first" in response.json()["detail"]
  44. @pytest.mark.asyncio
  45. @pytest.mark.integration
  46. async def test_returns_commits_from_the_provider(self, async_client: AsyncClient):
  47. await _create_config(async_client)
  48. commits = [
  49. {"sha": "aaa1111", "message": "Bambuddy backup", "author": "Bambuddy", "date": "2026-07-02T10:00:00Z"}
  50. ]
  51. with patch(
  52. "backend.app.services.git_providers.github.GitHubBackend.list_commits",
  53. new=AsyncMock(return_value={"success": True, "message": "OK", "commits": commits}),
  54. ):
  55. response = await async_client.get("/api/v1/github-backup/commits")
  56. assert response.status_code == 200
  57. body = response.json()
  58. assert body["success"] is True
  59. assert body["branch"] == "main"
  60. assert body["commits"][0]["sha"] == "aaa1111"
  61. @pytest.mark.asyncio
  62. @pytest.mark.integration
  63. async def test_provider_failure_is_reported_not_raised(self, async_client: AsyncClient):
  64. await _create_config(async_client)
  65. with patch(
  66. "backend.app.services.git_providers.github.GitHubBackend.list_commits",
  67. new=AsyncMock(return_value={"success": False, "message": "Invalid access token", "commits": []}),
  68. ):
  69. response = await async_client.get("/api/v1/github-backup/commits")
  70. assert response.status_code == 200
  71. assert response.json()["success"] is False
  72. assert response.json()["commits"] == []
  73. @pytest.mark.asyncio
  74. @pytest.mark.integration
  75. async def test_limit_is_bounded(self, async_client: AsyncClient):
  76. await _create_config(async_client)
  77. assert (await async_client.get("/api/v1/github-backup/commits?limit=0")).status_code == 422
  78. assert (await async_client.get("/api/v1/github-backup/commits?limit=101")).status_code == 422
  79. class TestPreviewEndpoint:
  80. @pytest.mark.asyncio
  81. @pytest.mark.integration
  82. async def test_404_when_not_configured(self, async_client: AsyncClient):
  83. response = await async_client.get("/api/v1/github-backup/restore/preview")
  84. assert response.status_code == 404
  85. @pytest.mark.asyncio
  86. @pytest.mark.integration
  87. async def test_reports_available_and_missing_categories(self, async_client: AsyncClient):
  88. await _create_config(async_client)
  89. preview = {
  90. "success": True,
  91. "message": "OK",
  92. "ref": "aaa1111",
  93. "commit": None,
  94. "metadata_version": "1.0",
  95. "categories": [
  96. {"category": "kprofiles", "available": False, "item_count": 0, "detail": "Not present"},
  97. {"category": "settings", "available": True, "item_count": 12, "detail": None},
  98. {"category": "spools", "available": True, "item_count": 4, "detail": "plus 9 usage records"},
  99. {"category": "archives", "available": True, "item_count": 30, "detail": "Metadata only"},
  100. ],
  101. }
  102. with patch(
  103. "backend.app.services.github_restore.github_restore_service.preview",
  104. new=AsyncMock(return_value=preview),
  105. ):
  106. response = await async_client.get("/api/v1/github-backup/restore/preview?ref=aaa1111")
  107. assert response.status_code == 200
  108. body = response.json()
  109. assert body["metadata_version"] == "1.0"
  110. by_name = {c["category"]: c for c in body["categories"]}
  111. assert by_name["kprofiles"]["available"] is False
  112. assert by_name["spools"]["item_count"] == 4
  113. @pytest.mark.asyncio
  114. @pytest.mark.integration
  115. @pytest.mark.parametrize("ref", ["main", "abc", "../../etc/passwd", "zzzzzzz"])
  116. async def test_rejects_refs_that_are_not_object_names(self, async_client: AsyncClient, ref):
  117. await _create_config(async_client)
  118. response = await async_client.get(f"/api/v1/github-backup/restore/preview?ref={ref}")
  119. assert response.status_code == 422
  120. @pytest.mark.asyncio
  121. @pytest.mark.integration
  122. async def test_defaults_to_head(self, async_client: AsyncClient):
  123. await _create_config(async_client)
  124. mock = AsyncMock(return_value={"success": True, "message": "OK", "ref": "aaa1111", "categories": []})
  125. with patch("backend.app.services.github_restore.github_restore_service.preview", new=mock):
  126. response = await async_client.get("/api/v1/github-backup/restore/preview")
  127. assert response.status_code == 200
  128. assert mock.await_args.kwargs["ref"] == "HEAD"
  129. class TestRestoreEndpoint:
  130. @pytest.mark.asyncio
  131. @pytest.mark.integration
  132. async def test_404_when_not_configured(self, async_client: AsyncClient):
  133. response = await async_client.post("/api/v1/github-backup/restore", json={"categories": ["spools"]})
  134. assert response.status_code == 404
  135. @pytest.mark.asyncio
  136. @pytest.mark.integration
  137. async def test_applies_selected_categories(self, async_client: AsyncClient):
  138. await _create_config(async_client)
  139. outcome = {
  140. "success": True,
  141. "message": "Restored 5 item(s) from aaa1111",
  142. "log_id": 3,
  143. "ref": "aaa1111",
  144. "results": {
  145. "spools": {"restored": 4, "skipped": 1, "failed": 0, "notes": []},
  146. "settings": {"restored": 1, "skipped": 2, "failed": 0, "notes": ["1 credential-like key(s) skipped"]},
  147. },
  148. }
  149. with patch(
  150. "backend.app.services.github_restore.github_restore_service.run_restore",
  151. new=AsyncMock(return_value=outcome),
  152. ) as mock:
  153. response = await async_client.post(
  154. "/api/v1/github-backup/restore",
  155. json={"ref": "aaa1111", "categories": ["spools", "settings"], "overwrite_existing": True},
  156. )
  157. assert response.status_code == 200
  158. body = response.json()
  159. assert body["results"]["spools"]["restored"] == 4
  160. assert body["results"]["settings"]["notes"] == ["1 credential-like key(s) skipped"]
  161. assert mock.await_args.kwargs["overwrite_existing"] is True
  162. assert mock.await_args.kwargs["ref"] == "aaa1111"
  163. @pytest.mark.asyncio
  164. @pytest.mark.integration
  165. async def test_rejects_empty_category_list(self, async_client: AsyncClient):
  166. await _create_config(async_client)
  167. response = await async_client.post("/api/v1/github-backup/restore", json={"categories": []})
  168. assert response.status_code == 422
  169. @pytest.mark.asyncio
  170. @pytest.mark.integration
  171. async def test_rejects_unknown_category(self, async_client: AsyncClient):
  172. await _create_config(async_client)
  173. response = await async_client.post("/api/v1/github-backup/restore", json={"categories": ["cloud_profiles"]})
  174. assert response.status_code == 422
  175. @pytest.mark.asyncio
  176. @pytest.mark.integration
  177. async def test_rejects_malformed_ref(self, async_client: AsyncClient):
  178. await _create_config(async_client)
  179. response = await async_client.post(
  180. "/api/v1/github-backup/restore", json={"ref": "main", "categories": ["spools"]}
  181. )
  182. assert response.status_code == 422
  183. @pytest.mark.asyncio
  184. @pytest.mark.integration
  185. async def test_defaults_overwrite_to_false(self, async_client: AsyncClient):
  186. """The safe default: a restore only inserts what's missing."""
  187. await _create_config(async_client)
  188. mock = AsyncMock(return_value={"success": True, "message": "ok", "results": {}})
  189. with patch("backend.app.services.github_restore.github_restore_service.run_restore", new=mock):
  190. response = await async_client.post("/api/v1/github-backup/restore", json={"categories": ["spools"]})
  191. assert response.status_code == 200
  192. assert mock.await_args.kwargs["overwrite_existing"] is False
  193. @pytest.mark.asyncio
  194. @pytest.mark.integration
  195. async def test_service_failure_is_reported_in_body(self, async_client: AsyncClient):
  196. await _create_config(async_client)
  197. with patch(
  198. "backend.app.services.github_restore.github_restore_service.run_restore",
  199. new=AsyncMock(
  200. return_value={
  201. "success": False,
  202. "message": "A backup is currently running. Wait for it to finish before restoring.",
  203. "results": {},
  204. }
  205. ),
  206. ):
  207. response = await async_client.post("/api/v1/github-backup/restore", json={"categories": ["spools"]})
  208. assert response.status_code == 200
  209. assert response.json()["success"] is False
  210. assert "backup is currently running" in response.json()["message"]
  211. class TestStatusExposesRestoreState:
  212. @pytest.mark.asyncio
  213. @pytest.mark.integration
  214. async def test_restore_running_is_false_when_idle(self, async_client: AsyncClient):
  215. await _create_config(async_client)
  216. response = await async_client.get("/api/v1/github-backup/status")
  217. assert response.status_code == 200
  218. assert response.json()["restore_running"] is False
  219. @pytest.mark.asyncio
  220. @pytest.mark.integration
  221. async def test_restore_running_is_reported(self, async_client: AsyncClient):
  222. """The UI disables both action buttons off this flag."""
  223. await _create_config(async_client)
  224. from backend.app.services.github_restore import github_restore_service
  225. github_restore_service._running_restore = True
  226. github_restore_service._progress = "Restoring spool inventory..."
  227. try:
  228. response = await async_client.get("/api/v1/github-backup/status")
  229. finally:
  230. github_restore_service._running_restore = False
  231. github_restore_service._progress = None
  232. assert response.json()["restore_running"] is True
  233. assert response.json()["progress"] == "Restoring spool inventory..."
  234. @pytest.mark.asyncio
  235. @pytest.mark.integration
  236. async def test_unconfigured_status_still_has_the_field(self, async_client: AsyncClient):
  237. response = await async_client.get("/api/v1/github-backup/status")
  238. assert response.status_code == 200
  239. assert response.json()["restore_running"] is False