oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package designstep
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14
15 "amadan.net/oficina/equipo/internal/runner/renderpage"
16 "amadan.net/oficina/equipo/internal/wire"
17)
18
19var digest = strings.Repeat("d", 64)
20
21// rig is an Attempt whose render_page writes the captures it is told to
22// into its directory, and records what asked what, in order.
23type rig struct {
24 a *Attempt
25 dir string
26 events []string
27 confirm error
28 next [][]string
29 saved [][]wire.DesignOption
30}
31
32func newRig(t *testing.T) *rig {
33 t.Helper()
34 r := &rig{dir: filepath.Join(t.TempDir(), "render")}
35 if err := os.Mkdir(r.dir, 0o700); err != nil {
36 t.Fatal(err)
37 }
38 r.a = &Attempt{Dir: r.dir}
39 r.a.Confirm = func(context.Context) error {
40 r.events = append(r.events, "confirm")
41 return r.confirm
42 }
43 r.a.Render = func(_ context.Context, raw json.RawMessage) (string, []renderpage.Capture, error) {
44 r.events = append(r.events, "render")
45 var files []string
46 if len(r.next) > 0 {
47 files, r.next = r.next[0], r.next[1:]
48 }
49 var caps []renderpage.Capture
50 for _, f := range files {
51 if err := os.WriteFile(filepath.Join(r.dir, f), []byte("png of "+f), 0o600); err != nil {
52 return "", nil, err
53 }
54 caps = append(caps, renderpage.Capture{File: f, Tree: "work", Digest: digest, Bytes: int64(len("png of " + f))})
55 }
56 return "rendered " + strings.Join(files, ","), caps, nil
57 }
58 r.a.Record = func(_ context.Context, opts []wire.DesignOption) error {
59 r.saved = append(r.saved, opts)
60 return nil
61 }
62 return r
63}
64
65func (r *rig) call(name, args string) (string, bool) {
66 return r.a.Call(context.Background(), name, "u", json.RawMessage(args))
67}
68
69const page = `{"tree": "work", "pages": [{"path": "/", "viewport": "phone"}]}`
70
71// TestRenderAsksTheLeaseFirst: every render_page call asks the instance
72// first (wire.LeasePurposeRender), before its input is even read.
73func TestRenderAsksTheLeaseFirst(t *testing.T) {
74 r := newRig(t)
75 r.next = [][]string{{"1-work-1.png"}}
76 if text, isError := r.call(ToolRenderPage, page); isError || text != "rendered 1-work-1.png" {
77 t.Fatalf("%q %v", text, isError)
78 }
79 r.call(ToolRenderPage, `not json`)
80 if strings.Join(r.events, " ") != "confirm render confirm render" {
81 t.Fatalf("events %v", r.events)
82 }
83 r.a.Confirm = nil
84 if text, isError := r.call(ToolRenderPage, page); !isError || text != RenderUnconfirmedText {
85 t.Fatalf("no lease check: %q %v", text, isError)
86 }
87}
88
89// TestRefusedRenderLeaseStopsRendering: once the instance refuses a
90// render, render_page renders nothing more in the step, never asks
91// again, and says why in fixed text; a check that could not be made
92// stops it too, saying so.
93func TestRefusedRenderLeaseStopsRendering(t *testing.T) {
94 for name, tc := range map[string]struct {
95 err error
96 text string
97 }{
98 "refused": {errors.Join(ErrRenderRefused, errors.New("withdrawn")), RenderRefusedText},
99 "unconfirmed": {errors.New("no connection"), RenderUnconfirmedText},
100 } {
101 t.Run(name, func(t *testing.T) {
102 r := newRig(t)
103 r.next = [][]string{{"1-work-1.png"}, {"2-work-1.png"}}
104 r.call(ToolRenderPage, page)
105 r.confirm = tc.err
106 for i := range 3 {
107 text, isError := r.call(ToolRenderPage, page)
108 if !isError || text != tc.text {
109 t.Fatalf("call %d: %q %v", i+2, text, isError)
110 }
111 }
112 if strings.Join(r.events, " ") != "confirm render confirm" {
113 t.Fatalf("events %v", r.events)
114 }
115 r.confirm = nil
116 if text, _ := r.call(ToolRenderPage, page); text != tc.text {
117 t.Fatalf("rendering came back: %q", text)
118 }
119 // What it rendered before the refusal can still be named.
120 if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet", "captures": ["1-work-1.png"]}]}`); isError {
121 t.Fatal(text)
122 }
123 })
124 }
125 if !strings.Contains(RenderRefusedText, "refused") || !strings.Contains(RenderUnconfirmedText, "could not confirm") {
126 t.Fatal("the texts do not say why")
127 }
128}
129
130// TestCancelledRenderLeaseIsNotAStop: a check cut short by the step
131// ending is no refusal.
132func TestCancelledRenderLeaseIsNotAStop(t *testing.T) {
133 r := newRig(t)
134 ctx, cancel := context.WithCancel(context.Background())
135 cancel()
136 r.a.Confirm = func(ctx context.Context) error { return ctx.Err() }
137 if text, isError := r.a.Call(ctx, ToolRenderPage, "u", json.RawMessage(page)); !isError || text == RenderRefusedText || text == RenderUnconfirmedText {
138 t.Fatalf("%q %v", text, isError)
139 }
140 r.a.Confirm = func(context.Context) error { return nil }
141 r.next = [][]string{{"1-work-1.png"}}
142 if text, isError := r.call(ToolRenderPage, page); isError {
143 t.Fatalf("stopped after a cancelled check: %q", text)
144 }
145}
146
147// TestSubmitCandidateRecordsOptions: submit_candidate records the
148// options' names and, for each capture it names, the SHA-256 and tree
149// digest of the file render_page wrote in this attempt; a later call
150// replaces them.
151func TestSubmitCandidateRecordsOptions(t *testing.T) {
152 r := newRig(t)
153 r.next = [][]string{{"1-work-1.png", "1-work-2.png"}}
154 r.call(ToolRenderPage, page)
155 text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet editorial", "captures": ["1-work-1.png"]}, {"name": "Market stall", "captures": ["1-work-2.png"]}]}`)
156 if isError || !strings.HasPrefix(text, "Recorded 2 options with 2 captures.") {
157 t.Fatalf("%q %v", text, isError)
158 }
159 sum := sha256.Sum256([]byte("png of 1-work-1.png"))
160 want := wire.DesignCapture{ID: "1-work-1.png", SHA256: hex.EncodeToString(sum[:]), TreeDigest: digest}
161 got := r.a.Options()
162 if len(got) != 2 || got[0].Name != "Quiet editorial" || len(got[0].Captures) != 1 || got[0].Captures[0] != want || got[1].Name != "Market stall" {
163 t.Fatalf("options %+v", got)
164 }
165 if len(r.saved) != 1 || len(r.saved[0]) != 2 {
166 t.Fatalf("recorded %+v", r.saved)
167 }
168 if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet editorial", "captures": []}]}`); isError {
169 t.Fatal(text)
170 }
171 if got := r.a.Options(); len(got) != 1 || len(got[0].Captures) != 0 {
172 t.Fatalf("not replaced: %+v", got)
173 }
174 r.a.Record = func(context.Context, []wire.DesignOption) error { return errors.New("disk") }
175 if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Again", "captures": ["1-work-1.png"]}]}`); !isError || text != submitUnrecordedText {
176 t.Fatalf("unrecorded: %q %v", text, isError)
177 }
178 if got := r.a.Options(); len(got) != 1 || got[0].Name != "Quiet editorial" {
179 t.Fatalf("an unrecorded call changed them: %+v", got)
180 }
181}
182
183// TestSubmitCandidateRefusals: only captures render_page made in this
184// attempt, named once; the wire's bounds; strict input. A refusal
185// records nothing.
186func TestSubmitCandidateRefusals(t *testing.T) {
187 r := newRig(t)
188 var many []string
189 for i := 1; i <= 13; i++ {
190 many = append(many, "1-work-"+itoa(i)+".png")
191 }
192 r.next = [][]string{many}
193 r.call(ToolRenderPage, `{"tree": "work", "pages": []}`)
194 // A file in the render directory that no reply of this attempt gave
195 // (another attempt's, or planted).
196 if err := os.WriteFile(filepath.Join(r.dir, "9-work-1.png"), []byte("other"), 0o600); err != nil {
197 t.Fatal(err)
198 }
199 quoted := func(ids ...string) string {
200 raw, _ := json.Marshal(ids)
201 return string(raw)
202 }
203 for name, args := range map[string]string{
204 // These two must be refused for what they are, whatever else.
205 "not this attempt's: is not a capture": `{"options": [{"name": "A", "captures": ["9-work-1.png"]}]}`,
206 "never made: is not a capture": `{"options": [{"name": "A", "captures": ["2-work-1.png"]}]}`,
207 "not this attempt's": `{"options": [{"name": "A", "captures": ["9-work-1.png"]}]}`,
208 "never made": `{"options": [{"name": "A", "captures": ["2-work-1.png"]}]}`,
209 "not a capture id": `{"options": [{"name": "A", "captures": ["../state.db"]}]}`,
210 "twice": `{"options": [{"name": "A", "captures": ["1-work-1.png"]}, {"name": "B", "captures": ["1-work-1.png"]}]}`,
211 "13 captures": `{"options": [{"name": "A", "captures": ` + quoted(many...) + `}]}`,
212 "5 options": `{"options": [{"name": "A", "captures": []}, {"name": "B", "captures": []}, {"name": "C", "captures": []}, {"name": "D", "captures": []}, {"name": "E", "captures": []}]}`,
213 "a name twice": `{"options": [{"name": "A", "captures": []}, {"name": "a", "captures": []}]}`,
214 "a bad name": `{"options": [{"name": "<b>A</b>", "captures": []}]}`,
215 "unknown field": `{"options": [], "summary": "x"}`,
216 "unknown option part": `{"options": [{"name": "A", "captures": [], "url": "x"}]}`,
217 "no options": `{}`,
218 "trailing": `{"options": []} {}`,
219 "not an object": `[]`,
220 } {
221 text, isError := r.call(ToolSubmitCandidate, args)
222 if !isError || !strings.HasPrefix(text, "submit_candidate refused:") {
223 t.Errorf("%s: %q %v", name, text, isError)
224 }
225 if _, why, ok := strings.Cut(name, ": "); ok && !strings.Contains(text, why) {
226 t.Errorf("%s: %q", name, text)
227 }
228 }
229 if len(r.saved) != 0 || r.a.Options() != nil {
230 t.Fatalf("a refusal recorded %+v", r.saved)
231 }
232 if text, isError := r.call(ToolSubmitCandidate, `{"options": []}`); isError {
233 t.Fatalf("no options at all: %q", text)
234 }
235}
236
237// TestAskPersonSaysNobodyCanAnswer: ask_person's reply is fixed.
238func TestAskPersonSaysNobodyCanAnswer(t *testing.T) {
239 r := newRig(t)
240 if text, isError := r.call(ToolAskPerson, `{"question": "which?"}`); isError || text != AskText || !strings.HasPrefix(text, "Nobody can answer") {
241 t.Fatalf("%q %v", text, isError)
242 }
243 if _, isError := r.call("submit_render", `{}`); !isError {
244 t.Fatal("another tool answered")
245 }
246 if len(r.events) != 0 {
247 t.Fatalf("events %v", r.events)
248 }
249}
250
251// TestFilesAreTheNamedCapturesOfTheAttempt: the upload is exactly the
252// named captures, read from the attempt's own render directory, each
253// as valid render_file chunks bound to the task, step and attempt that
254// reassemble to the file; a capture that is not the file recorded, or
255// not a regular file there, refuses the upload.
256func TestFilesAreTheNamedCapturesOfTheAttempt(t *testing.T) {
257 r := newRig(t)
258 big := make([]byte, 300<<10)
259 for i := range big {
260 big[i] = byte(i * 7)
261 }
262 r.next = [][]string{{"1-work-1.png", "1-work-2.png"}}
263 r.call(ToolRenderPage, page)
264 if err := os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), big, 0o600); err != nil {
265 t.Fatal(err)
266 }
267 // The capture as render_page left it is the big one (rewritten
268 // before it was recorded would be a lie: record it again).
269 r.a.captures = nil
270 r.a.keep([]renderpage.Capture{{File: "1-work-1.png", Digest: digest}, {File: "1-work-2.png", Digest: digest}})
271 if text, isError := r.call(ToolSubmitCandidate, `{"options": [{"name": "Quiet", "captures": ["1-work-1.png"]}]}`); isError {
272 t.Fatal(text)
273 }
274 os.WriteFile(filepath.Join(r.dir, "3-work-1.png"), []byte("planted"), 0o600)
275 files, err := Files(r.dir, "tk1", "st1", 2, r.a.Options())
276 if err != nil {
277 t.Fatal(err)
278 }
279 if len(files) != 1 {
280 t.Fatalf("%d files uploaded", len(files))
281 }
282 var whole []byte
283 for i, f := range files[0] {
284 if !wire.ValidRenderFile(f) || f.TaskID != "tk1" || f.StepID != "st1" || f.Attempt != 2 || f.CaptureID != "1-work-1.png" || f.Index != i || f.Total != 3 || f.Size != int64(len(big)) {
285 t.Fatalf("chunk %d: %+v", i, f)
286 }
287 part, _ := base64.StdEncoding.DecodeString(f.Data)
288 whole = append(whole, part...)
289 }
290 if string(whole) != string(big) || files[0][0].SHA256 != r.a.Options()[0].Captures[0].SHA256 {
291 t.Fatal("the chunks are not the capture")
292 }
293 if files, err := Files(r.dir, "tk1", "st1", 2, nil); err != nil || len(files) != 0 {
294 t.Fatalf("no options: %v %v", files, err)
295 }
296 opts := r.a.Options()
297 for name, change := range map[string]func(){
298 "changed": func() { os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), []byte("other bytes"), 0o600) },
299 "gone": func() { os.Remove(filepath.Join(r.dir, "1-work-1.png")) },
300 "a link": func() {
301 // To a file of the same bytes: only the link itself is wrong.
302 os.WriteFile(filepath.Join(r.dir, "5-work-1.png"), big, 0o600)
303 os.Remove(filepath.Join(r.dir, "1-work-1.png"))
304 os.Symlink("5-work-1.png", filepath.Join(r.dir, "1-work-1.png"))
305 },
306 "too large": func() {
307 os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), make([]byte, wire.MaxCaptureBytes+1), 0o600)
308 },
309 } {
310 os.Remove(filepath.Join(r.dir, "1-work-1.png"))
311 os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), big, 0o600)
312 if _, err := Files(r.dir, "tk1", "st1", 2, opts); err != nil {
313 t.Fatalf("%s: restored: %v", name, err)
314 }
315 change()
316 if _, err := Files(r.dir, "tk1", "st1", 2, opts); err == nil {
317 t.Errorf("%s: uploaded", name)
318 }
319 }
320 os.Remove(filepath.Join(r.dir, "1-work-1.png"))
321 os.WriteFile(filepath.Join(r.dir, "1-work-1.png"), big, 0o600)
322 bad := clone(opts)
323 bad[0].Name = "<b>Quiet</b>"
324 if _, err := Files(r.dir, "tk1", "st1", 2, bad); err == nil {
325 t.Fatal("options the wire refuses uploaded")
326 }
327}
328
329func itoa(i int) string {
330 raw, _ := json.Marshal(i)
331 return string(raw)
332}
333