oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package plan3test
2
3import (
4 "encoding/json"
5 "net/http"
6 "os"
7 "reflect"
8 "strings"
9 "testing"
10
11 "amadan.net/oficina/equipo/internal/equipo/personapi"
12 "github.com/go-chi/chi/v5"
13)
14
15func TestPersonAPIContractCoverage(t *testing.T) { personAPIContractCoverage(t) }
16
17// personAPIRoutes are the routes the person API registers, by path:
18// the methods, space separated.
19func personAPIRoutes() map[string]string {
20 required := map[string]string{
21 "/me": "GET", "/capabilities": "GET", "/me/settings": "GET PATCH", "/people": "GET",
22 "/conversation": "GET", "/conversation/messages": "POST", "/conversation/cards": "GET", "/cards/{id}": "GET",
23 "/tasks": "GET POST", "/tasks/{id}": "GET", "/tasks/{id}/cancel": "POST", "/tasks/{id}/thread": "GET", "/tasks/{id}/thread/messages": "POST", "/conversation/messages/{id}/route": "POST",
24 "/tasks/{id}/plan": "GET PATCH", "/tasks/{id}/plan/approve": "POST", "/tasks/{id}/project": "POST",
25 "/questions/{id}": "GET", "/questions/{id}/answer": "POST", "/tasks/{id}/rendered-approval": "POST", "/tasks/{id}/acknowledge-merge": "POST",
26 "/journey": "GET", "/needs-you": "GET", "/preferences": "GET POST", "/preferences/{id}": "PATCH DELETE",
27 "/coordinator": "GET PATCH", "/coordinator/reset": "POST", "/coordinator/retry": "POST", "/coordinator/limits": "PATCH",
28 }
29 for path, methods := range map[string]string{
30 "/auth/devices/native": "POST", "/auth/devices": "GET POST", "/auth/devices/exchange": "POST", "/auth/devices/{id}/approve": "POST", "/auth/devices/{id}": "DELETE",
31 "/roster": "GET", "/roster/{address}": "PUT", "/budgets": "GET PUT",
32 "/teams": "GET", "/teams/links": "POST", "/teams/links/{id}": "PATCH DELETE",
33 "/accounts": "GET POST", "/projects": "GET POST", "/projects/{id}": "GET PATCH", "/projects/{id}/settings": "GET PATCH", "/projects/{id}/my-settings": "PATCH",
34 "/specialists": "GET POST", "/specialists/{id}": "GET PATCH DELETE", "/playbooks": "GET POST", "/playbooks/{id}": "GET PATCH DELETE",
35 "/templates": "GET", "/templates/{id}": "GET", "/templates/{id}/install": "POST", "/specialists/{id}/template-diff": "GET", "/playbooks/{id}/template-diff": "GET", "/specialists/{id}/template-update": "POST", "/playbooks/{id}/template-update": "POST",
36 "/connections": "GET", "/connections/{id}": "GET PATCH DELETE", "/projects/{id}/connections": "PUT", "/tasks/{id}/steps/{key}/selection": "POST",
37 "/runners": "GET", "/runners/{id}": "GET DELETE", "/runners/enrol/approve": "POST", "/onboarding": "GET", "/onboarding/advance": "POST", "/account-setups": "POST", "/account-setups/{id}": "GET DELETE",
38 "/notifications": "GET", "/notification-subscriptions": "POST", "/notification-subscriptions/{id}": "DELETE", "/notification-subscriptions/{id}/ack": "POST",
39 "/invites": "POST", "/invites/{id}": "GET DELETE", "/invites/{id}/accept": "POST",
40 } {
41 required[path] = methods
42 }
43 return required
44}
45
46func personAPIContractCoverage(t *testing.T) {
47 t.Helper()
48 raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json")
49 must(t, err)
50 var doc struct {
51 OpenAPI string `json:"openapi"`
52 Info struct {
53 Version string `json:"version"`
54 } `json:"info"`
55 Paths map[string]map[string]json.RawMessage `json:"paths"`
56 }
57 must(t, json.Unmarshal(raw, &doc))
58 if doc.OpenAPI != "3.1.0" || doc.Info.Version != "1.0.0" {
59 t.Fatal("wrong API version")
60 }
61 required := personAPIRoutes()
62
63 // The Assistant lane's routes (chat.MountAssistant) are Base's, not
64 // personapi registrations: documented here under their own schemas,
65 // with the device bearer alone.
66 assistant := map[string]string{
67 "/assistant/snapshot": "GET", "/assistant/messages": "GET POST", "/assistant/turns/{id}/cancel": "POST",
68 "/assistant/cards/{id}/answer": "POST", "/assistant/events": "GET", "/assistant/host": "PUT",
69 "/assistant/cards/{id}/carry_on": "POST", "/assistant/time-zone": "PUT",
70 "/assistant/abilities": "GET", "/assistant/abilities/refresh": "POST",
71 }
72
73 f := newFixture(t)
74 registered := map[string]bool{}
75 assistantRoutes := map[string]bool{}
76 // The conversation engine's own routes, and those it shares with this
77 // API, are TestPersonAPIDeviceContract's.
78 engine := deviceEngineRoutes(t, f)
79 shared := func(key string) bool { return engine[key] && deviceShared[key] != "" }
80 thin := map[string]bool{}
81 for key := range engine {
82 method, path, _ := strings.Cut(key, " ")
83 if !strings.Contains(" "+required[path]+" ", " "+method+" ") && !strings.HasPrefix(path, "/assistant/") {
84 thin[key] = true
85 }
86 }
87 must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
88 // The app-owned preview capability has a separate contract test.
89 if method == "POST" && path == "/tasks/{id}/preview-pass" {
90 return nil
91 }
92 if thin[method+" "+path] {
93 return nil
94 }
95 if strings.Contains(" "+assistant[path]+" ", " "+method+" ") {
96 assistantRoutes[method+" "+path] = true
97 return nil
98 }
99 registered[method+" "+path] = true
100 return nil
101 }))
102 operationIDs := map[string]string{}
103 for _, r := range personapi.Routes {
104 operationIDs[r.Method+" "+r.Path] = personapi.OperationID(r)
105 }
106 var document map[string]any
107 must(t, json.Unmarshal(raw, &document))
108 var checkRefs func(any)
109 checkRefs = func(v any) {
110 switch value := v.(type) {
111 case map[string]any:
112 for k, x := range value {
113 if k == "$ref" {
114 ref := x.(string)
115 var node any = document
116 for _, part := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") {
117 m, ok := node.(map[string]any)
118 if !ok || m[part] == nil {
119 t.Fatalf("missing schema reference %s", ref)
120 }
121 node = m[part]
122 }
123 } else {
124 checkRefs(x)
125 }
126 }
127 case []any:
128 for _, x := range value {
129 checkRefs(x)
130 }
131 }
132 }
133 checkRefs(document)
134 schemes := document["components"].(map[string]any)["securitySchemes"].(map[string]any)
135 if schemes["personBearer"] == nil {
136 t.Fatal("person bearer is undocumented")
137 }
138 codes := document["components"].(map[string]any)["schemas"].(map[string]any)["Error"].(map[string]any)["properties"].(map[string]any)["code"].(map[string]any)["enum"].([]any)
139 for _, code := range []string{"device_expired", "slow_down", "authorization_pending", "subscription_expired"} {
140 found := false
141 for _, value := range codes {
142 if value == code {
143 found = true
144 }
145 }
146 if !found {
147 t.Fatal("missing device error schema", code)
148 }
149 }
150
151 // person is the person API's operation for a route it registers: on a
152 // path the engine shares, the earlier operation kept in
153 // x-earlierPersonAPI; nil where the engine replaced it.
154 person := func(method, path string) map[string]any {
155 op, _ := document["paths"].(map[string]any)[path].(map[string]any)[strings.ToLower(method)].(map[string]any)
156 switch {
157 case !shared(method + " " + path):
158 return op
159 case deviceShared[method+" "+path] == "replaced" || op == nil:
160 return nil
161 }
162 earlier, _ := op["x-earlierPersonAPI"].(map[string]any)
163 inner, _ := earlier["operation"].(map[string]any)
164 if inner == nil {
165 t.Fatal("missing earlier operation", method, path)
166 }
167 return inner
168 }
169 for _, r := range personapi.Routes {
170 if r.Input == nil || deviceShared[r.Method+" "+r.Path] == "replaced" {
171 continue
172 }
173 name := reflect.TypeOf(r.Input()).Elem().Name()
174 if name == "" {
175 name = "Empty"
176 }
177 operation := person(r.Method, r.Path)
178 if operation == nil {
179 t.Fatal("missing OpenAPI operation", r.Method, r.Path)
180 }
181 body := operation["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)
182 if body["$ref"] != "#/components/schemas/"+name {
183 t.Fatal("request schema differs from registered DTO", r.Path, name, body)
184 }
185 }
186
187 count := 0
188 for path, methods := range required {
189 for _, method := range strings.Fields(methods) {
190 count++
191 if !registered[method+" "+path] {
192 t.Fatal("missing 3a route", method, path)
193 }
194 if _, ok := doc.Paths[path][strings.ToLower(method)]; !ok {
195 t.Fatal("missing OpenAPI operation", method, path)
196 }
197 if deviceShared[method+" "+path] == "replaced" {
198 continue
199 }
200 operation, err := json.Marshal(person(method, path))
201 must(t, err)
202 var value struct {
203 OperationID string `json:"operationId"`
204 Parameters []struct {
205 Name string
206 Required bool
207 }
208 Responses map[string]struct {
209 Content map[string]struct{ Schema json.RawMessage }
210 }
211 RequestBody struct {
212 Required bool
213 Content map[string]struct{ Schema json.RawMessage }
214 }
215 }
216 must(t, json.Unmarshal(operation, &value))
217 if value.OperationID != operationIDs[method+" "+path] {
218 t.Fatal("operation ID differs from registration", method, path, value.OperationID)
219 }
220 if len(value.Responses["200"].Content["application/json"].Schema) == 0 {
221 t.Fatal("untyped response", method, path)
222 }
223 if method != "GET" {
224 if !value.RequestBody.Required || len(value.RequestBody.Content["application/json"].Schema) == 0 {
225 t.Fatal("untyped mutation", method, path)
226 }
227 key := false
228 for _, p := range value.Parameters {
229 if p.Name == "Idempotency-Key" && p.Required {
230 key = true
231 }
232 }
233 if !key && path != "/auth/devices/native" {
234 t.Fatal("missing request key contract", method, path)
235 }
236 }
237 }
238 }
239 if count != len(registered) {
240 t.Fatal("unexpected API route", count, len(registered))
241 }
242 documented := 0
243 for path, methods := range assistant {
244 for _, method := range strings.Fields(methods) {
245 documented++
246 if !assistantRoutes[method+" "+path] {
247 t.Fatal("missing Assistant route", method, path)
248 }
249 operation, ok := doc.Paths[path][strings.ToLower(method)]
250 if !ok {
251 t.Fatal("missing OpenAPI operation", method, path)
252 }
253 var value struct {
254 OperationID string `json:"operationId"`
255 Security []map[string][]string `json:"security"`
256 Responses map[string]struct {
257 Content map[string]struct{ Schema json.RawMessage }
258 }
259 RequestBody struct {
260 Content map[string]struct{ Schema json.RawMessage }
261 }
262 }
263 must(t, json.Unmarshal(operation, &value))
264 if value.OperationID != personapi.OperationID(personapi.Route{Method: method, Path: path}) {
265 t.Fatal("operation ID differs from the route", method, path, value.OperationID)
266 }
267 if len(value.Security) != 1 || len(value.Security[0]) != 1 || value.Security[0]["personBearer"] == nil {
268 t.Fatal("an Assistant route takes the device bearer alone", method, path, value.Security)
269 }
270 typed := false
271 for status, r := range value.Responses {
272 for _, c := range r.Content {
273 typed = typed || status[0] == '2' && len(c.Schema) > 0
274 }
275 }
276 if !typed {
277 t.Fatal("untyped response", method, path)
278 }
279 if method != "GET" && len(value.RequestBody.Content["application/json"].Schema) == 0 {
280 t.Fatal("untyped mutation", method, path)
281 }
282 }
283 }
284 if documented != len(assistantRoutes) {
285 t.Fatal("unexpected Assistant route", documented, len(assistantRoutes))
286 }
287 p := proposed(t, f)
288 w := apiRequest(t, f, owner, "GET", "/api/v1/conversation/cards", "", "", "")
289 expectHTTP(t, w, 200)
290 cards := apiValue[personapi.Page[personapi.Card]](t, w)
291 found := false
292 for _, c := range cards.Items {
293 if c.ResourceID == p.TaskID {
294 found = true
295 expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/cards/"+c.ID, "", "", ""), 200)
296 expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/cards/"+c.ID, "", "", ""), 404)
297 }
298 }
299 if !found {
300 t.Fatal("missing current task card")
301 }
302}
303