-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrawl_actions_test.go
More file actions
776 lines (648 loc) · 22.5 KB
/
crawl_actions_test.go
File metadata and controls
776 lines (648 loc) · 22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/chromedp/chromedp"
)
// skipIfNoBrowser skips the test if no Chrome/Chromium is available
// and enforces a shorter timeout than the default browser tests
func skipIfNoBrowser(t *testing.T) {
t.Helper()
if os.Getenv("CI") == "true" {
t.Skip("Skipping browser test in CI")
}
if !commandExists("google-chrome") && !commandExists("chromium") && !commandExists("chromium-browser") {
if !pathExists([]string{"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}) {
t.Skip("No Chrome/Chromium available")
}
}
}
func newTimedBrowserContext(t *testing.T, timeout time.Duration) (context.Context, context.CancelFunc) {
t.Helper()
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", true),
chromedp.Flag("disable-gpu", true),
chromedp.Flag("no-sandbox", true),
)
timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), timeout)
allocCtx, allocCancel := chromedp.NewExecAllocator(timeoutCtx, opts...)
ctx, cancel := chromedp.NewContext(allocCtx)
cleanup := func() {
cancel()
allocCancel()
timeoutCancel()
}
return ctx, cleanup
}
// --- crawlClick tests ---
func TestCrawlClick_Success(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<button id="test-btn" onclick="document.title='btn-clicked'">Click Me</button>
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
err := a.crawlClick(ctx, "click-test", "#test-btn")
if err != nil {
t.Fatalf("crawlClick failed: %v", err)
}
var title string
_ = chromedp.Run(ctx, chromedp.Title(&title))
if title != "btn-clicked" {
t.Errorf("expected title 'btn-clicked', got %q", title)
}
}
func TestCrawlClick_JSFallbackOnHidden(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<button id="hidden-btn" style="display:none" onclick="document.title='js-click'">Hidden</button>
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
// Native click will fail on hidden element, should fallback to JS
err := a.crawlClick(ctx, "js-fallback", "#hidden-btn")
if err != nil {
t.Logf("crawlClick JS fallback returned: %v (may be expected)", err)
}
}
// --- crawlFill tests ---
func TestCrawlFill_Success(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<input id="name-input" type="text" value="old value" />
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
err := a.crawlFill(ctx, "#name-input", "new value")
if err != nil {
t.Fatalf("crawlFill failed: %v", err)
}
var value string
_ = chromedp.Run(ctx, chromedp.Value("#name-input", &value, chromedp.ByQuery))
if value != "new value" {
t.Errorf("expected 'new value', got %q", value)
}
}
// --- crawlSelect tests ---
func TestCrawlSelect_Success(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<select id="lang">
<option value="">Pick</option>
<option value="go">Go</option>
<option value="py">Python</option>
</select>
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
err := a.crawlSelect(ctx, "#lang", "go")
if err != nil {
t.Fatalf("crawlSelect failed: %v", err)
}
var value string
_ = chromedp.Run(ctx, chromedp.Value("#lang", &value, chromedp.ByQuery))
if value != "go" {
t.Errorf("expected 'go', got %q", value)
}
}
// --- crawlComboboxSelect tests ---
func TestCrawlComboboxSelect_NoOptions(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<input id="combo-input" type="text" />
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
err := a.crawlComboboxSelect(ctx, "#combo-input", "test")
// Should return an error because no options are found
if err == nil {
t.Error("expected error when no options available")
}
if err != nil && !strings.Contains(err.Error(), "could not find") {
t.Errorf("unexpected error: %v", err)
}
}
// --- dismissCookieConsent tests ---
func TestDismissCookieConsent_WithAcceptAllButton(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<div id="cookie-overlay">
<p>Cookies?</p>
<button onclick="document.getElementById('cookie-overlay').remove(); document.title='dismissed'">Accept All</button>
</div>
<h1>Content</h1>
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
a.dismissCookieConsent(ctx, "cookie-test")
var title string
_ = chromedp.Run(ctx, chromedp.Title(&title))
if title == "dismissed" {
t.Log("Cookie consent dismissed successfully")
}
}
func TestDismissCookieConsent_NoBannerPresent(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body><h1>No cookies</h1></body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
// Should not panic when no cookie banner exists
a.dismissCookieConsent(ctx, "no-cookie-test")
}
// --- captureSnapshot tests ---
func TestCaptureSnapshot_BasicPage(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><head><title>Snapshot Test</title></head><body><h1>Hello</h1></body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{CloudURL: "http://localhost", AgentID: "test", APIKey: "key"}
session := CrawlSession{SessionID: "snap-basic", URL: ts.URL}
snapshot, err := a.captureSnapshot(ctx, session, 1)
if err != nil {
t.Fatalf("captureSnapshot failed: %v", err)
}
if snapshot.Title != "Snapshot Test" {
t.Errorf("Title: got %q, want 'Snapshot Test'", snapshot.Title)
}
if snapshot.ScreenshotBase64 == "" {
t.Error("ScreenshotBase64 should not be empty")
}
if snapshot.StepNum != 1 {
t.Errorf("StepNum: got %d, want 1", snapshot.StepNum)
}
}
func TestCaptureSnapshot_WithScript(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><head><title>Script Page</title></head><body><button id="b1">Go</button></body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
session := CrawlSession{
SessionID: "snap-script",
URL: ts.URL,
SnapshotScript: `JSON.stringify({interactive_elements:[{tag:"button"}], forms:[], selectors:{"btn":"#b1"}, accessibility_tree:"button: Go"})`,
}
snapshot, err := a.captureSnapshot(ctx, session, 2)
if err != nil {
t.Fatalf("captureSnapshot failed: %v", err)
}
if len(snapshot.InteractiveElements) == 0 {
t.Error("expected interactive elements from script")
}
if snapshot.Selectors["btn"] != "#b1" {
t.Errorf("selector: got %q", snapshot.Selectors["btn"])
}
}
func TestCaptureSnapshot_InvalidScript(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><head><title>Bad Script</title></head><body><p>Page</p></body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
session := CrawlSession{
SessionID: "snap-bad-script",
URL: ts.URL,
SnapshotScript: `throw new Error("script error")`,
}
snapshot, err := a.captureSnapshot(ctx, session, 1)
if err != nil {
t.Fatalf("captureSnapshot should not fail on script error: %v", err)
}
// Script failed but snapshot should still have URL and title
if snapshot.Title != "Bad Script" {
t.Errorf("Title: got %q", snapshot.Title)
}
}
// --- ExecuteCrawlSession tests ---
func TestExecuteCrawlSession_DoneOnFirstStep(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
htmlServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><head><title>Crawl Done</title></head><body><h1>Page</h1></body></html>`)
}))
defer htmlServer.Close()
snapshotCount := 0
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.Contains(r.URL.Path, "/snapshot") {
snapshotCount++
_ = json.NewEncoder(w).Encode(CrawlAction{Action: "done", Reason: "Complete"})
return
}
w.WriteHeader(http.StatusOK)
}))
defer apiServer.Close()
a := &Agent{
CloudURL: apiServer.URL,
AgentID: "crawl-done-agent",
APIKey: "crawl-done-key",
client: &http.Client{Timeout: 30 * time.Second},
}
session := CrawlSession{
SessionID: "done-on-first",
URL: htmlServer.URL,
MaxSteps: 5,
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
a.ExecuteCrawlSession(ctx, session)
if snapshotCount != 1 {
t.Errorf("expected 1 snapshot, got %d", snapshotCount)
}
}
func TestExecuteCrawlSession_ClickThenDone(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
htmlServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><head><title>Click Page</title></head><body>
<button id="btn1" onclick="document.title='clicked'">Click</button>
</body></html>`)
}))
defer htmlServer.Close()
step := 0
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.Contains(r.URL.Path, "/snapshot") {
step++
if step == 1 {
_ = json.NewEncoder(w).Encode(CrawlAction{Action: "click", Selector: "#btn1", Reason: "Click button"})
} else {
_ = json.NewEncoder(w).Encode(CrawlAction{Action: "done", Reason: "Done"})
}
return
}
w.WriteHeader(http.StatusOK)
}))
defer apiServer.Close()
a := &Agent{
CloudURL: apiServer.URL,
AgentID: "crawl-click-agent",
APIKey: "crawl-click-key",
client: &http.Client{Timeout: 30 * time.Second},
}
session := CrawlSession{
SessionID: "click-then-done",
URL: htmlServer.URL,
MaxSteps: 5,
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
a.ExecuteCrawlSession(ctx, session)
if step < 2 {
t.Errorf("expected at least 2 steps, got %d", step)
}
}
func TestExecuteCrawlSession_InvalidURL(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
var errorReported bool
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.Contains(r.URL.Path, "/error") {
errorReported = true
}
w.WriteHeader(http.StatusOK)
}))
defer apiServer.Close()
a := &Agent{
CloudURL: apiServer.URL,
AgentID: "crawl-err-agent",
APIKey: "crawl-err-key",
client: &http.Client{Timeout: 30 * time.Second},
}
session := CrawlSession{
SessionID: "invalid-url-crawl",
URL: "http://127.0.0.1:1/nonexistent", // will fail to navigate
MaxSteps: 1,
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
a.ExecuteCrawlSession(ctx, session)
if !errorReported {
t.Error("expected error to be reported for invalid URL")
}
}
// --- executeCrawlAction tests ---
func TestExecuteCrawlAction_AllActionTypes(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<button id="btn">Click</button>
<input id="input" type="text" />
<select id="sel"><option value="a">A</option><option value="b">B</option></select>
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 20*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
// Test fill action
err := a.executeCrawlAction(ctx, "multi-test", &CrawlAction{Action: "fill", Selector: "#input", Value: "hello"})
if err != nil {
t.Errorf("fill action failed: %v", err)
}
// Test select action
err = a.executeCrawlAction(ctx, "multi-test", &CrawlAction{Action: "select", Selector: "#sel", Value: "b"})
if err != nil {
t.Errorf("select action failed: %v", err)
}
// Test click action
err = a.executeCrawlAction(ctx, "multi-test", &CrawlAction{Action: "click", Selector: "#btn"})
if err != nil {
t.Errorf("click action failed: %v", err)
}
}
func TestExecuteCrawlAction_ComboboxSelect(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
skipIfNoBrowser(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<!DOCTYPE html><html><body>
<input id="combo" type="text" />
</body></html>`)
}))
defer ts.Close()
ctx, cancel := newTimedBrowserContext(t, 15*time.Second)
defer cancel()
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL), chromedp.WaitReady("body")); err != nil {
t.Fatalf("navigation failed: %v", err)
}
a := &Agent{}
err := a.executeCrawlAction(ctx, "combo-test", &CrawlAction{Action: "combobox_select", Selector: "#combo", Value: "test"})
// Expected to fail (no options to select)
if err == nil {
t.Log("combobox_select succeeded (unexpected but not an error)")
}
}
// --- doJSONWithRetry edge cases ---
func TestDoJSONWithRetry_SuccessOnFirstTry(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{"ok":true}`)
}))
defer server.Close()
a := newTestAgent(server.URL)
resp, body, err := a.doJSONWithRetry("GET", server.URL+"/test", nil, nil, 5*time.Second)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
if string(body) != `{"ok":true}` {
t.Errorf("body: %s", body)
}
}
func TestDoJSONWithRetry_WithBody(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
var received map[string]string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewDecoder(r.Body).Decode(&received)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
a := newTestAgent(server.URL)
payload := map[string]string{"key": "val"}
_, _, err := a.doJSONWithRetry("POST", server.URL+"/test", payload, nil, 5*time.Second)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if received["key"] != "val" {
t.Errorf("body: got %v", received)
}
}
// --- PollCrawlSessions edge cases ---
func TestPollCrawlSessions_EmptySession(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Session with empty session_id
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"session": map[string]interface{}{
"session_id": "",
"url": "https://example.com",
},
})
}))
defer server.Close()
a := newTestAgent(server.URL)
session, err := a.PollCrawlSessions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if session != nil {
t.Error("expected nil for empty session_id")
}
}
func TestPollCrawlSessions_InvalidJSON(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, "not json")
}))
defer server.Close()
a := newTestAgent(server.URL)
_, err := a.PollCrawlSessions()
if err == nil {
t.Error("expected error for invalid JSON")
}
}
func TestPollCrawlSessions_CustomStatusCode(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
fmt.Fprint(w, "forbidden")
}))
defer server.Close()
a := newTestAgent(server.URL)
_, err := a.PollCrawlSessions()
if err == nil {
t.Error("expected error for 403 response")
}
}
// --- submitCrawlError edge cases ---
func TestSubmitCrawlError_ServerFails(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer server.Close()
a := newTestAgent(server.URL)
// Should not panic
a.submitCrawlError("sess-fail", "test error")
}
// --- submitSnapshot edge cases ---
func TestSubmitSnapshot_BadRequest(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "bad request")
}))
defer server.Close()
a := newTestAgent(server.URL)
_, err := a.submitSnapshot("sess-bad", &CrawlSnapshot{SessionID: "sess-bad", StepNum: 1})
if err == nil {
t.Error("expected error for 400 response")
}
}
func TestSubmitSnapshot_InvalidResponseJSON(t *testing.T) {
if os.Getenv("QMAX_BROWSER_TESTS") == "" {
t.Skip("Skipping browser test (set QMAX_BROWSER_TESTS=1 to run)")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "not json")
}))
defer server.Close()
a := newTestAgent(server.URL)
_, err := a.submitSnapshot("sess-json", &CrawlSnapshot{SessionID: "sess-json", StepNum: 1})
if err == nil {
t.Error("expected error for invalid JSON response")
}
}