package thintest import ( "bufio" "bytes" "context" "encoding/json" "fmt" "io" "net/http" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // The native apps (native/apple, EquipoKit) read the person API with a // device bearer, as this suite does. Their test fixtures are this // instance's own answers, captured from the rollup rig with // EQUIPO_UPDATE_NATIVE_FIXTURES=1. Every run checks that each checked-in // fixture still decodes strictly into its wire type: a field the server // no longer sends, or one it never sent, fails here. const nativeFixtureDir = "../../native/apple/Tests/EquipoKitTests/Fixtures/thin" var nativeFixtureTypes = map[string]func() any{ "snapshot": func() any { return &wire.Snapshot{} }, "tasks": func() any { return &wire.TaskList{} }, "needs-you": func() any { return &wire.TaskList{} }, "projects": func() any { return &wire.ProjectList{} }, "task": func() any { return &wire.Task{} }, "messages": func() any { return &wire.MessagePage{} }, "sent": func() any { return &wire.Sent{} }, "answered": func() any { return &wire.Answered{} }, "card-conflict": func() any { return &wire.CardConflict{} }, "thread-entry": func() any { return &wire.ThreadEntry{} }, "events": func() any { return &[]wire.Event{} }, } func TestNativeFixtures(t *testing.T) { if os.Getenv("EQUIPO_UPDATE_NATIVE_FIXTURES") == "1" { captureNativeFixtures(t) } for name, typ := range nativeFixtureTypes { raw, err := os.ReadFile(filepath.Join(nativeFixtureDir, name+".json")) if err != nil { t.Fatalf("%s: %v (capture with EQUIPO_UPDATE_NATIVE_FIXTURES=1)", name, err) } d := json.NewDecoder(bytes.NewReader(raw)) d.DisallowUnknownFields() if err := d.Decode(typ()); err != nil { t.Errorf("%s.json no longer matches its wire type: %v", name, err) } } } func captureNativeFixtures(t *testing.T) { r := newRollupRig(t) ctx := r.ctx get := func(path string) []byte { return nativeRaw(t, ctx, r.client, "GET", path, nil, 200) } write := func(name string, raw []byte) { var v any if err := json.Unmarshal(raw, &v); err != nil { t.Fatalf("%s: %v", name, err) } pretty, _ := json.MarshalIndent(v, "", " ") if err := os.MkdirAll(nativeFixtureDir, 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(nativeFixtureDir, name+".json"), append(pretty, '\n'), 0o644); err != nil { t.Fatal(err) } } write("snapshot", get("/api/v1/snapshot")) write("tasks", get("/api/v1/tasks")) write("needs-you", get("/api/v1/needs-you")) write("projects", get("/api/v1/projects")) write("task", get("/api/v1/tasks/"+r.asked)) write("messages", get("/api/v1/messages?limit=20")) write("thread-entry", nativeRaw(t, ctx, r.client, "POST", "/api/v1/tasks/"+r.asked+"/thread", wire.PostThread{Text: "Does this cover the iPad too?", IdempotencyKey: "native-fixture-thread"}, 0)) write("sent", nativeRaw(t, ctx, r.client, "POST", "/api/v1/messages", wire.SendMessage{Text: "What is left?", IdempotencyKey: "native-fixture-send"}, 0)) // Answer the open merge card with its last choice, then again with the // revision it had: the second is the conflict a stale native view gets. card := r.askCard choice := card.Options[len(card.Options)-1] write("answered", nativeRaw(t, ctx, r.client, "POST", "/api/v1/cards/"+card.ID+"/answer", wire.AnswerCard{Choice: choice, Revision: card.Revision}, 200)) write("card-conflict", nativeRaw(t, ctx, r.client, "POST", "/api/v1/cards/"+card.ID+"/answer", wire.AnswerCard{Choice: choice, Revision: card.Revision}, 409)) write("events", nativeEvents(t, ctx, r.client)) } // nativeRaw sends one request with the device bearer and returns the body. // want 0 accepts any 2xx. func nativeRaw(t *testing.T, ctx context.Context, c *Client, method, path string, body any, want int) []byte { t.Helper() var reader io.Reader if body != nil { raw, _ := json.Marshal(body) reader = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, c.Origin+path, reader) if err != nil { t.Fatal(err) } req.Header.Set("Authorization", "Bearer "+c.Token) if body != nil { req.Header.Set("Content-Type", "application/json") req.Header.Set("Idempotency-Key", fmt.Sprintf("native-fixture-%d", time.Now().UnixNano())) } res, err := c.HTTP.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20)) if (want != 0 && res.StatusCode != want) || (want == 0 && res.StatusCode/100 != 2) { t.Fatalf("%s %s = %d: %s", method, path, res.StatusCode, raw) } return raw } // nativeEvents reads the conversation's event stream from the start for a // moment and returns the events it carried, as a JSON array. func nativeEvents(t *testing.T, ctx context.Context, c *Client) []byte { t.Helper() ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() req, _ := http.NewRequestWithContext(ctx, "GET", c.Origin+"/api/v1/events?after=0", nil) req.Header.Set("Authorization", "Bearer "+c.Token) res, err := c.HTTP.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() var events []json.RawMessage s := bufio.NewScanner(res.Body) s.Buffer(make([]byte, 1<<20), 4<<20) for s.Scan() && len(events) < 12 { if line := s.Text(); strings.HasPrefix(line, "data: ") { events = append(events, json.RawMessage(strings.TrimPrefix(line, "data: "))) } } if len(events) == 0 { t.Fatal("the event stream carried nothing") } raw, _ := json.Marshal(events) return raw }