oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package render
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "net/url"
9 "strings"
10 "testing"
11 "time"
12)
13
14var testSiteURL, _ = url.Parse("http://127.0.0.1:4000/")
15
16// Every failed load is one of three kinds, or not reported.
17func TestClassifyLoad(t *testing.T) {
18 for _, c := range []struct {
19 url, kind string
20 status int
21 netErr bool
22 want string
23 }{
24 {"https://cdn.example.com/lib.js", "Script", 0, true, LoadExternalBlocked},
25 {"http://1.1.1.1/x.css", "Stylesheet", 0, true, LoadExternalBlocked},
26 {"http://[2606:4700::1111]/x", "Fetch", 0, true, LoadExternalBlocked},
27 // Another port of the sandbox's own loopback is not the site.
28 {"http://127.0.0.1:4001/x", "XHR", 0, true, LoadExternalBlocked},
29 {"https://127.0.0.1:4000/x", "Image", 0, true, LoadExternalBlocked},
30 {"http://cdn.example.com/landing", "Document", 0, true, LoadExternalBlocked},
31 {"http://127.0.0.1:4000/missing.png", "Image", 404, false, LoadNotFound},
32 {"http://127.0.0.1:4000/missing/", "Document", 404, false, LoadNotFound},
33 {"http://127.0.0.1:4000/broken", "Fetch", 500, false, LoadNotFound},
34 {"https://fonts.gstatic.com/a.woff2", "Font", 0, true, LoadFont},
35 {"http://127.0.0.1:4000/f.woff2", "Font", 404, false, LoadFont},
36 // Not failures, or not the page's: nothing reported.
37 {"http://127.0.0.1:4000/ok.png", "Image", 200, false, ""},
38 {"http://127.0.0.1:4000/moved", "Document", 301, false, ""},
39 {"http://127.0.0.1:4000/csp-blocked.js", "Script", 0, true, ""},
40 {"data:text/plain,x", "Image", 0, true, ""},
41 {"chrome-error://chromewebdata/", "Document", 0, true, ""},
42 {"blob:http://127.0.0.1:4000/1", "Fetch", 0, true, ""},
43 {"::not a url", "Script", 0, true, ""},
44 } {
45 got, ok := classifyLoad(testSiteURL, c.url, c.kind, c.status, c.netErr)
46 if got != c.want || ok != (c.want != "") {
47 t.Errorf("%s %s %d %v: %q %v, want %q", c.url, c.kind, c.status, c.netErr, got, ok, c.want)
48 }
49 }
50}
51
52func raw(v any) json.RawMessage {
53 b, _ := json.Marshal(v)
54 return b
55}
56
57func testPage() (*pageState, context.Context) {
58 ctx, cancel := context.WithCancelCause(context.Background())
59 p := newPageState(testSiteURL, "S1", cancel)
60 p.setMain("F1")
61 return p, ctx
62}
63
64// Console errors and failed loads are bounded and counted past the
65// bound; a failed load already listed is not listed or counted again; only errors count; a page's later events are not
66// collected once it is captured.
67func TestPageStateBounds(t *testing.T) {
68 p, _ := testPage()
69 for i := 0; i < 50; i++ {
70 p.event("Runtime.consoleAPICalled", raw(map[string]any{"type": "error", "args": []any{
71 map[string]any{"type": "string", "value": fmt.Sprintf("bad\n\x1b[31m %d\u202e", i)},
72 map[string]any{"type": "number", "value": 7, "description": "7"},
73 map[string]any{"type": "object", "description": "Object"},
74 }}))
75 }
76 p.event("Runtime.consoleAPICalled", raw(map[string]any{"type": "log", "args": []any{map[string]any{"type": "string", "value": "fine"}}}))
77 for i := 0; i < 40; i++ {
78 id := fmt.Sprint("r", i)
79 p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": id, "type": "Script", "request": map[string]any{"url": fmt.Sprintf("https://cdn%d.example.com/x.js", i)}}))
80 p.event("Network.loadingFailed", raw(map[string]any{"requestId": id, "type": "Script", "errorText": "net::ERR_NAME_NOT_RESOLVED"}))
81 // The same failure again is not another entry.
82 p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": id + "b", "type": "Script", "request": map[string]any{"url": fmt.Sprintf("https://cdn%d.example.com/x.js", i)}}))
83 p.event("Network.loadingFailed", raw(map[string]any{"requestId": id + "b", "type": "Script"}))
84 }
85 var r PageReport
86 p.finish(&r)
87 if len(r.ConsoleErrors) != maxConsoleErrors || r.ConsoleErrorsOmitted != 30 || r.ConsoleErrors[0] != "bad [31m 0 7 Object" {
88 t.Fatalf("console %q, %d omitted", r.ConsoleErrors, r.ConsoleErrorsOmitted)
89 }
90 if len(r.FailedLoads) != maxFailedLoads || r.FailedLoadsOmitted != 20 || r.FailedLoads[0] != (FailedLoad{Kind: LoadExternalBlocked, URL: "https://cdn0.example.com/x.js"}) {
91 t.Fatalf("failed %+v, %d omitted", r.FailedLoads, r.FailedLoadsOmitted)
92 }
93 p.event("Runtime.exceptionThrown", raw(map[string]any{"exceptionDetails": map[string]any{"text": "Uncaught"}}))
94 p.event("Network.responseReceived", raw(map[string]any{"requestId": "late", "type": "Fetch", "response": map[string]any{"url": "http://127.0.0.1:4000/late", "status": 404}}))
95 var after PageReport
96 p.finish(&after)
97 if after.ConsoleErrorsOmitted != 30 || after.FailedLoadsOmitted != 20 {
98 t.Fatalf("collected after the capture: %+v", after)
99 }
100}
101
102// An exception is its text and the first line of its description; a
103// cancelled request, one never seen, and one whose id is oversize are
104// not reported; requests in flight are bounded.
105func TestPageStateEvents(t *testing.T) {
106 p, _ := testPage()
107 p.event("Runtime.exceptionThrown", raw(map[string]any{"exceptionDetails": map[string]any{"text": "Uncaught", "exception": map[string]any{"type": "object", "description": "Error: boom\n at x.html:3"}}}))
108 p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": "c", "type": "Image", "request": map[string]any{"url": "https://x.example/a.png"}}))
109 p.event("Network.loadingFailed", raw(map[string]any{"requestId": "c", "canceled": true}))
110 p.event("Network.loadingFailed", raw(map[string]any{"requestId": "never-sent"}))
111 long := strings.Repeat("i", maxRequestID+1)
112 p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": long, "type": "Image", "request": map[string]any{"url": "https://x.example/b.png"}}))
113 p.event("Network.loadingFailed", raw(map[string]any{"requestId": long}))
114 // A same-site redirect to another host keeps the id: the failure is
115 // the new URL's.
116 p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": "rd", "type": "Script", "request": map[string]any{"url": "http://127.0.0.1:4000/go"}}))
117 p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": "rd", "type": "Script", "request": map[string]any{"url": "https://cdn.example.com/went.js"}, "redirectResponse": map[string]any{"status": 302}}))
118 p.event("Network.loadingFailed", raw(map[string]any{"requestId": "rd", "type": "Script"}))
119 p.event("Network.responseReceived", raw(map[string]any{"requestId": "f", "type": "Font", "response": map[string]any{"url": "http://127.0.0.1:4000/f.woff2", "status": 404}}))
120 for i := 0; i < 3*maxTracked; i++ {
121 p.event("Network.requestWillBeSent", raw(map[string]any{"requestId": fmt.Sprint("q", i), "request": map[string]any{"url": "http://127.0.0.1:4000/q"}}))
122 }
123 if len(p.requests) > maxTracked {
124 t.Fatalf("%d requests tracked", len(p.requests))
125 }
126 var r PageReport
127 p.finish(&r)
128 if len(r.ConsoleErrors) != 1 || r.ConsoleErrors[0] != "Uncaught Error: boom" {
129 t.Fatalf("console %q", r.ConsoleErrors)
130 }
131 want := []FailedLoad{{Kind: LoadExternalBlocked, URL: "https://cdn.example.com/went.js"}, {Kind: LoadFont, URL: "http://127.0.0.1:4000/f.woff2", Status: 404}}
132 if fmt.Sprint(r.FailedLoads) != fmt.Sprint(want) {
133 t.Fatalf("failed %+v", r.FailedLoads)
134 }
135}
136
137// Load is the main frame's current document's: an earlier document's,
138// another frame's or a load before the navigation does not count; a
139// new document starts the wait again; idle ends it early, and without
140// idle it ends IdleWait after the load. A crash ends it at once.
141func TestPageStateWaitsForLoad(t *testing.T) {
142 waits := func(p *pageState, ctx context.Context, d time.Duration) error {
143 ctx, cancel := context.WithTimeout(ctx, d)
144 defer cancel()
145 return p.waitLoaded(ctx)
146 }
147 p, ctx := testPage()
148 nav := func(loader string) {
149 p.event("Page.frameNavigated", raw(map[string]any{"frame": map[string]any{"id": "F1", "loaderId": loader}}))
150 }
151 life := func(frame, loader, name string) {
152 p.event("Page.lifecycleEvent", raw(map[string]any{"frameId": frame, "loaderId": loader, "name": name}))
153 }
154 life("F1", "L0", "load")
155 life("F1", "L0", "networkIdle")
156 nav("L1")
157 life("F1", "L0", "load")
158 life("F1", "L0", "networkIdle")
159 life("F2", "L1", "load")
160 life("F2", "L1", "networkIdle")
161 if err := waits(p, ctx, 100*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) {
162 t.Fatalf("loaded early: %v", err)
163 }
164 life("F1", "L1", "load")
165 nav("L2")
166 if err := waits(p, ctx, 100*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) {
167 t.Fatalf("an earlier document's load counted: %v", err)
168 }
169 // A subframe's navigation is not a new main document.
170 p.event("Page.frameNavigated", raw(map[string]any{"frame": map[string]any{"id": "F2", "parentId": "F1", "loaderId": "L9"}}))
171 life("F1", "L2", "load")
172 life("F1", "L2", "networkIdle")
173 if err := waits(p, ctx, 100*time.Millisecond); err != nil {
174 t.Fatalf("idle: %v", err)
175 }
176 // Without idle the wait ends IdleWait after load.
177 p2, ctx2 := testPage()
178 p2.event("Page.frameNavigated", raw(map[string]any{"frame": map[string]any{"id": "F1", "loaderId": "L1"}}))
179 p2.event("Page.lifecycleEvent", raw(map[string]any{"frameId": "F1", "loaderId": "L1", "name": "load"}))
180 p2.mu.Lock()
181 p2.loadedAt = time.Now().Add(-IdleWait + 200*time.Millisecond)
182 p2.mu.Unlock()
183 began := time.Now()
184 if err := waits(p2, ctx2, 3*time.Second); err != nil || time.Since(began) > time.Second {
185 t.Fatalf("no idle: %v after %v", err, time.Since(began))
186 }
187 p3, ctx3 := testPage()
188 go func() {
189 time.Sleep(50 * time.Millisecond)
190 p3.event("Inspector.targetCrashed", nil)
191 }()
192 if err := waits(p3, ctx3, 3*time.Second); !errors.Is(err, errRendererCrashed) {
193 t.Fatalf("crash: %v", err)
194 }
195}
196
197func axn(id, parent, role, name string, ignored bool, children ...string) axNode {
198 n := axNode{NodeID: id, ParentID: parent, Ignored: ignored, ChildIDs: children}
199 if role != "" {
200 n.Role = &axValue{Value: raw(role)}
201 }
202 if name != "" {
203 n.Name = &axValue{Value: raw(name)}
204 }
205 return n
206}
207
208// The outline is the tree's meaningful nodes, indented, bounded, and
209// safe from cycles and lies in the ids.
210func TestOutline(t *testing.T) {
211 nodes := []axNode{
212 axn("1", "", "RootWebArea", "Shop", false, "2", "9"),
213 axn("2", "1", "generic", "", false, "3", "5"),
214 axn("3", "2", "heading", "Welcome\n\u202ehome", false, "4"),
215 axn("4", "3", "StaticText", "Welcome home", false),
216 axn("5", "2", "paragraph", "", false, "6", "6", "1", "5", "missing"),
217 axn("6", "5", "StaticText", "Some words", false, "7"),
218 axn("7", "6", "InlineTextBox", "Some words", false),
219 axn("9", "1", "button", "Hidden", true),
220 }
221 text, cut := outline(nodes, maxOutline)
222 want := "RootWebArea \"Shop\"\n heading \"Welcome home\"\n paragraph\n StaticText \"Some words\"\n"
223 if text != want || cut {
224 t.Fatalf("outline %q %v, want %q", text, cut, want)
225 }
226 // A long tree is cut at whole lines.
227 big := []axNode{axn("r", "", "list", "", false)}
228 for i := 0; i < 1000; i++ {
229 id := fmt.Sprint("i", i)
230 big[0].ChildIDs = append(big[0].ChildIDs, id)
231 big = append(big, axn(id, "r", "listitem", strings.Repeat("x", 300), false))
232 }
233 text, cut = outline(big, maxOutline)
234 if !cut || len(text) > maxOutline || !strings.HasSuffix(text, "\n") {
235 t.Fatalf("cut %v, %d bytes", cut, len(text))
236 }
237 for _, line := range strings.Split(strings.TrimSuffix(text, "\n"), "\n") {
238 if len(line) > 2+len("listitem")+maxName+3 {
239 t.Fatalf("line of %d bytes", len(line))
240 }
241 }
242 if text, _ := outline(nil, maxOutline); text != "" {
243 t.Fatalf("empty tree %q", text)
244 }
245 // Every node claims a parent: no root, no outline, no loop.
246 loop := []axNode{axn("a", "b", "list", "", false, "b"), axn("b", "a", "list", "", false, "a")}
247 if text, _ := outline(loop, maxOutline); text != "" {
248 t.Fatalf("loop %q", text)
249 }
250}
251
252// Page text is valid UTF-8 with no control or format characters, one
253// space for any run of space, within its bound, cut at a rune.
254func TestClean(t *testing.T) {
255 for _, c := range []struct {
256 in string
257 max int
258 want string
259 }{
260 {"plain", 10, "plain"},
261 {" a \n\t b ", 10, "a b"},
262 {"a\x00b\x1bc\u202ed\u200be", 10, "a b c d e"},
263 {"bad \xff utf8", 20, "bad utf8"},
264 {"héllo", 2, "h"},
265 {"héllo", 3, "hé"},
266 {"ab cd", 3, "ab"},
267 {"", 5, ""},
268 } {
269 if got := clean(c.in, c.max); got != c.want {
270 t.Errorf("clean(%q, %d) = %q, want %q", c.in, c.max, got, c.want)
271 }
272 }
273}
274
275// The report's JSON is a fixed schema: these names, empty lists as [].
276func TestReportSchema(t *testing.T) {
277 r := Report{Schema: ReportSchema, ElapsedMS: 1200, Pages: []PageReport{{
278 Path: "/", Viewport: Phone, Width: 390, Height: 844, Capture: "page-1.png", CaptureWidth: 390, CaptureHeight: 844,
279 Title: "Shop", ConsoleErrors: []string{"boom"}, FailedLoads: []FailedLoad{{Kind: LoadNotFound, URL: "http://127.0.0.1:1/x", Status: 404}, {Kind: LoadFont, URL: "https://f.example/a.woff2"}},
280 BrokenLinks: []string{}, LinksChecked: 2, Outline: "RootWebArea \"Shop\"\n",
281 }}}
282 got, err := json.Marshal(r)
283 if err != nil {
284 t.Fatal(err)
285 }
286 want := `{"schema":1,"elapsed_ms":1200,"pages":[{"path":"/","viewport":"phone","width":390,"height":844,"full_page":false,"capture":"page-1.png","capture_width":390,"capture_height":844,"title":"Shop","console_errors":["boom"],"console_errors_omitted":0,"failed_loads":[{"kind":"not found","url":"http://127.0.0.1:1/x","status":404},{"kind":"font","url":"https://f.example/a.woff2"}],"failed_loads_omitted":0,"broken_links":[],"broken_links_omitted":0,"links_checked":2,"outline":"RootWebArea \"Shop\"\n","outline_cut":false}]}`
287 if string(got) != want {
288 t.Fatalf("report\n%s\nwant\n%s", got, want)
289 }
290 r.Error = CodeTimeout
291 if got, _ := json.Marshal(r); !strings.HasPrefix(string(got), `{"schema":1,"error":"timeout",`) {
292 t.Fatalf("with error %s", got)
293 }
294}
295
296// Only the fixed viewports and plain site paths are rendered, at most
297// MaxPages a call.
298func TestCheckPages(t *testing.T) {
299 good := Page{Path: "/a/b.html?x=1", Viewport: Tablet}
300 if err := checkPages([]Page{good}); err != nil {
301 t.Fatal(err)
302 }
303 for _, v := range []Viewport{Phone, Tablet, Desktop} {
304 if w, h, ok := v.Size(); !ok || w == 0 || h == 0 {
305 t.Errorf("%s: %d %d %v", v, w, h, ok)
306 }
307 }
308 if w, h, _ := Phone.Size(); w != 390 || h != 844 {
309 t.Errorf("phone %dx%d", w, h)
310 }
311 if w, h, _ := Tablet.Size(); w != 834 || h != 1194 {
312 t.Errorf("tablet %dx%d", w, h)
313 }
314 if w, h, _ := Desktop.Size(); w != 1440 || h != 900 {
315 t.Errorf("desktop %dx%d", w, h)
316 }
317 seven := make([]Page, MaxPages+1)
318 for i := range seven {
319 seven[i] = good
320 }
321 for name, pages := range map[string][]Page{
322 "none": nil,
323 "seven": seven,
324 "viewport": {{Path: "/", Viewport: "watch"}},
325 "relative": {{Path: "a.html", Viewport: Phone}},
326 "host": {{Path: "//evil.example/", Viewport: Phone}},
327 "scheme": {{Path: "http://evil.example/", Viewport: Phone}},
328 "fragment": {{Path: "/#x", Viewport: Phone}},
329 "space": {{Path: "/a b", Viewport: Phone}},
330 "control": {{Path: "/a\nb", Viewport: Phone}},
331 "backslash": {{Path: "/\\evil.example", Viewport: Phone}},
332 "non-ascii": {{Path: "/é", Viewport: Phone}},
333 "long": {{Path: "/" + strings.Repeat("a", 1024), Viewport: Phone}},
334 "empty": {{Path: "", Viewport: Phone}},
335 } {
336 if checkPages(pages) == nil {
337 t.Errorf("%s: accepted", name)
338 }
339 }
340}
341