gabriel / musehub public
test_rest_casing_310.py python
112 lines 4.5 KB
Raw
sha256:8157b0df0e2312254edef68f882db2e510f21a94655f46def61a00abc850c106 Merge branch 'task/wave-hub-rest-310-312' into dev Opus 5.5 minor ⚠ breaking 1 day ago
1 """musehub#310: REST responses are camelCase, with no snake_case exceptions for labels and topics.
2
3 ``LabelResponse`` (``labelId``, ``repoId``; the list envelope is ``labels``), the repo-topics response (``repoId``)
4 and ``TopicItem`` (``repoCount``) are ``CamelModel``s like every other response. The schema walk enforces one casing
5 across every response model reachable from an ``/api`` 2xx response; the allow-list names the two models that are
6 deliberately snake_case, with the reason.
7 """
8 from __future__ import annotations
9
10 import pytest
11 from httpx import AsyncClient
12 from sqlalchemy.ext.asyncio import AsyncSession
13
14 from musehub.main import app
15 from musehub.types.json_types import StrDict
16 from tests.factories import create_repo
17
18 # Deliberately snake_case, outside the owner's #310 decision:
19 _SNAKE_ALLOWED = {
20 "CapsResponse", # GET /api/caps: the wire capability contract the Muse CLI reads before a push
21 "TakedownResponse", # POST /api/admin/takedown: operator tooling, not a public client surface
22 }
23
24
25 def _refs(node: object, out: set[str]) -> None:
26 if isinstance(node, dict):
27 for key, value in node.items():
28 if key == "$ref" and isinstance(value, str):
29 out.add(value.rsplit("/", 1)[1])
30 else:
31 _refs(value, out)
32 elif isinstance(node, list):
33 for value in node:
34 _refs(value, out)
35
36
37 def _response_schemas() -> tuple[dict, set[str]]:
38 spec = app.openapi()
39 schemas = spec["components"]["schemas"]
40 stack: list[str] = []
41 for path, ops in spec["paths"].items():
42 if not path.startswith("/api"):
43 continue
44 for op in ops.values():
45 for code, resp in op.get("responses", {}).items():
46 if code.startswith("2"):
47 found: set[str] = set()
48 _refs(resp, found)
49 stack.extend(found)
50 seen: set[str] = set()
51 while stack:
52 name = stack.pop()
53 if name in seen:
54 continue
55 seen.add(name)
56 nested: set[str] = set()
57 _refs(schemas[name], nested)
58 stack.extend(nested - seen)
59 return schemas, seen
60
61
62 def test_every_response_model_is_camel_case() -> None:
63 schemas, reachable = _response_schemas()
64 assert {"LabelResponse", "LabelListResponse", "RepoTopicsResponse", "TopicItem"} <= reachable
65 snake = {n: sorted(p for p in schemas[n].get("properties", {}) if "_" in p)
66 for n in reachable - _SNAKE_ALLOWED}
67 assert {n: p for n, p in snake.items() if p} == {}
68
69
70 def test_the_allow_list_is_still_needed() -> None:
71 schemas, reachable = _response_schemas()
72 for name in _SNAKE_ALLOWED:
73 assert name in reachable and any("_" in p for p in schemas[name]["properties"]), name
74
75
76 @pytest.mark.asyncio
77 async def test_label_list_and_create_are_camel_case(
78 client: AsyncClient, db_session: AsyncSession, auth_headers: StrDict
79 ) -> None:
80 repo = await create_repo(db_session, owner="testuser", slug="casing-310", visibility="public")
81 rid = str(repo.repo_id)
82 created = await client.post(f"/api/repos/{rid}/labels", json={"name": "needs-review", "color": "#123456"},
83 headers=auth_headers)
84 assert created.status_code == 201, created.text
85 label = created.json()
86 assert set(label) == {"labelId", "repoId", "name", "color", "description"}
87 assert label["repoId"] == rid
88
89 listed = (await client.get(f"/api/repos/{rid}/labels")).json()
90 assert set(listed) == {"labels", "total"}
91 assert label["labelId"] in {lbl["labelId"] for lbl in listed["labels"]}
92
93 patched = await client.patch(f"/api/repos/{rid}/labels/{label['labelId']}", json={"color": "#654321"},
94 headers=auth_headers)
95 assert patched.status_code == 200 and patched.json()["labelId"] == label["labelId"]
96
97
98 @pytest.mark.asyncio
99 async def test_topic_responses_are_camel_case(
100 client: AsyncClient, db_session: AsyncSession, auth_headers: StrDict
101 ) -> None:
102 repo = await create_repo(db_session, owner="testuser", slug="topics-310", visibility="public")
103 rid = str(repo.repo_id)
104 resp = await client.put(f"/api/repos/{rid}/topics", json={"topics": ["jazz"]}, headers=auth_headers)
105 assert resp.status_code == 200, resp.text
106 assert resp.json() == {"repoId": rid, "topics": ["jazz"]}
107
108 topics = (await client.get("/api/topics")).json()["topics"]
109 assert {"name": "jazz", "repoCount": 1} in topics
110
111 index = (await client.get("/topics?format=json")).json() # the topics page script reads repoCount
112 assert {"name": "jazz", "repoCount": 1} in index["allTopics"]
File History 3 commits
sha256:8157b0df0e2312254edef68f882db2e510f21a94655f46def61a00abc850c106 Merge branch 'task/wave-hub-rest-310-312' into dev Opus 5.5 minor ⚠ 1 day ago
sha256:157f2b8f3de428f54183520d5e16e7b0627b03322fc6a68f44a4d40b58e887b1 feat(rest): current user, release delete, repo topics GET/P… Opus 5.5 minor ⚠ 1 day ago
sha256:adcba83c3f339337ce2a7d7233d02752c77a3eb236ab38affa548699dba957dd fix(rest): label and topic responses are camelCase (#310) Opus 5.5 minor ⚠ 1 day ago