test_server.py 4.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import io
  2. import json
  3. import tempfile
  4. import unittest
  5. import zipfile
  6. from pathlib import Path
  7. from unittest.mock import patch
  8. from fastapi.testclient import TestClient
  9. from d2c import server
  10. from d2c.artifacts import validate_files, write_result
  11. class ServerTests(unittest.TestCase):
  12. def setUp(self):
  13. self.temp = tempfile.TemporaryDirectory()
  14. self.root_patch = patch.object(server, "RUN_ROOT", Path(self.temp.name) / "runs")
  15. self.root_patch.start()
  16. self.client = TestClient(server.app)
  17. def tearDown(self):
  18. self.client.close()
  19. self.root_patch.stop()
  20. self.temp.cleanup()
  21. def test_full_demo_preview_files_download(self):
  22. response = self.client.post("/api/runs", json={"source": "sample", "mode": "demo"})
  23. self.assertEqual(response.status_code, 202, response.text)
  24. run_id = response.json()["id"]
  25. run = self.client.get(f"/api/runs/{run_id}").json()
  26. self.assertEqual(run["status"], "completed", run.get("error"))
  27. self.assertTrue(run["events"])
  28. self.assertEqual(run["result"]["mode"], "demo")
  29. paths = {item["path"] for item in run["result"]["files"]}
  30. self.assertTrue({"src/App.tsx", "preview.html", "review-report.json"} <= paths)
  31. preview = self.client.get(f"/api/runs/{run_id}/preview")
  32. self.assertEqual(preview.status_code, 200)
  33. self.assertIn("sandbox", preview.headers["content-security-policy"])
  34. source = self.client.get(f"/api/runs/{run_id}/files", params={"path": "src/App.tsx"})
  35. self.assertIn("data-node-id", source.text)
  36. self.assertEqual(self.client.get(f"/api/runs/{run_id}/files", params={"path": "../../.env"}).status_code, 404)
  37. archive = self.client.get(f"/api/runs/{run_id}/download")
  38. with zipfile.ZipFile(io.BytesIO(archive.content)) as zipped:
  39. self.assertTrue(paths <= set(zipped.namelist()))
  40. report = json.loads(zipped.read("review-report.json"))
  41. self.assertEqual(report["mode"], "demo")
  42. def test_invalid_import_becomes_failed_run(self):
  43. response = self.client.post("/api/runs", json={"source": "json", "payload": {}})
  44. run = self.client.get("/api/runs/" + response.json()["id"]).json()
  45. self.assertEqual(run["status"], "failed")
  46. self.assertTrue(run["error"])
  47. self.assertEqual(self.client.get("/api/runs/" + run["id"] + "/download").status_code, 409)
  48. def test_missing_credentials_do_not_fallback(self):
  49. with patch.dict("os.environ", {}, clear=True):
  50. self.assertFalse(self.client.get("/api/health").json()["live_available"])
  51. self.assertEqual(self.client.post("/api/runs", json={"mode": "live"}).status_code, 400)
  52. self.assertEqual(self.client.post("/api/runs", json={"source": "figma", "figma_url": "https://figma.com/design/abc?node-id=1-2"}).status_code, 400)
  53. def test_validation_and_cross_site_guard(self):
  54. self.assertEqual(self.client.post("/api/runs", json={"source": "json"}).status_code, 400)
  55. self.assertEqual(self.client.post("/api/runs", json={"mode": "unknown"}).status_code, 422)
  56. self.assertEqual(self.client.post("/api/runs", json={}, headers={"origin": "https://evil.test"}).status_code, 403)
  57. self.assertEqual(self.client.get("/api/runs/invalid").status_code, 404)
  58. self.assertEqual(self.client.post("/api/runs", content=b"x" * (2 * 1024 * 1024 + 1)).status_code, 413)
  59. def test_concurrency_limit(self):
  60. self.assertTrue(server._slots.acquire(False))
  61. self.assertTrue(server._slots.acquire(False))
  62. try:
  63. self.assertEqual(self.client.post("/api/runs", json={}).status_code, 429)
  64. finally:
  65. server._slots.release()
  66. server._slots.release()
  67. def test_secret_error_redacted(self):
  68. with patch.dict("os.environ", {"LLM_API_KEY": "test-secret-value"}):
  69. self.assertNotIn("test-secret-value", server._safe_error(RuntimeError("key test-secret-value failed")))
  70. def test_artifact_path_guard_and_no_overwrite(self):
  71. for path in ("../../secrets.txt", "/tmp/escape", "src\\escape"):
  72. with self.subTest(path=path), self.assertRaises(ValueError):
  73. validate_files({path: "bad"})
  74. result = {"files": {"test.txt": "hello"}, "design": {}, "events": [], "review": {}, "metrics": {}, "mode": "demo", "plan": {}}
  75. output = Path(self.temp.name) / "project"
  76. write_result(result, output)
  77. with self.assertRaises(FileExistsError):
  78. write_result(result, output)
  79. self.assertEqual((output / "test.txt").read_text(), "hello")
  80. if __name__ == "__main__":
  81. unittest.main()