-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathe2e_chromium_test.go
More file actions
812 lines (698 loc) · 26.1 KB
/
e2e_chromium_test.go
File metadata and controls
812 lines (698 loc) · 26.1 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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
package e2e
import (
"archive/zip"
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"log/slog"
_ "github.com/glebarez/sqlite"
logctx "github.com/onkernel/kernel-images/server/lib/logger"
instanceoapi "github.com/onkernel/kernel-images/server/lib/oapi"
"github.com/samber/lo"
"github.com/stretchr/testify/require"
)
const (
defaultHeadfulImage = "onkernel/chromium-headful-test:latest"
defaultHeadlessImage = "onkernel/chromium-headless-test:latest"
containerName = "server-e2e-test"
// With host networking, the API listens on 10001 directly on the host
apiBaseURL = "http://127.0.0.1:10001"
)
var (
headfulImage = defaultHeadfulImage
headlessImage = defaultHeadlessImage
)
func init() {
// Prefer fully-specified images if provided
if v := os.Getenv("E2E_CHROMIUM_HEADFUL_IMAGE"); v != "" {
headfulImage = v
}
if v := os.Getenv("E2E_CHROMIUM_HEADLESS_IMAGE"); v != "" {
headlessImage = v
}
// Otherwise, if a tag/sha is provided, use the CI-built images
tag := os.Getenv("E2E_IMAGE_TAG")
if tag == "" {
tag = os.Getenv("E2E_IMAGE_SHA")
}
if tag != "" {
if os.Getenv("E2E_CHROMIUM_HEADFUL_IMAGE") == "" {
headfulImage = "onkernel/chromium-headful:" + tag
}
if os.Getenv("E2E_CHROMIUM_HEADLESS_IMAGE") == "" {
headlessImage = "onkernel/chromium-headless:" + tag
}
}
}
// getPlaywrightPath returns the path to the playwright script
func getPlaywrightPath() string {
return "./playwright"
}
// ensurePlaywrightDeps ensures playwright dependencies are installed
func ensurePlaywrightDeps(t *testing.T) {
t.Helper()
nodeModulesPath := getPlaywrightPath() + "/node_modules"
if _, err := os.Stat(nodeModulesPath); os.IsNotExist(err) {
t.Log("Installing playwright dependencies...")
cmd := exec.Command("pnpm", "install")
cmd.Dir = getPlaywrightPath()
output, err := cmd.CombinedOutput()
require.NoError(t, err, "Failed to install playwright dependencies: %v\nOutput: %s", err, string(output))
t.Log("Playwright dependencies installed successfully")
}
}
func TestDisplayResolutionChange(t *testing.T) {
image := headlessImage
name := containerName + "-display"
logger := slog.New(slog.NewTextHandler(t.Output(), &slog.HandlerOptions{Level: slog.LevelInfo}))
baseCtx := logctx.AddToContext(context.Background(), logger)
if _, err := exec.LookPath("docker"); err != nil {
require.NoError(t, err, "docker not available: %v", err)
}
// Clean slate
_ = stopContainer(baseCtx, name)
// Start with default resolution
env := map[string]string{
"WIDTH": "1024",
"HEIGHT": "768",
}
// Start container
_, exitCh, err := runContainer(baseCtx, image, name, env)
require.NoError(t, err, "failed to start container: %v", err)
defer stopContainer(baseCtx, name)
ctx, cancel := context.WithTimeout(baseCtx, 3*time.Minute)
defer cancel()
logger.Info("[setup]", "action", "waiting for API", "url", apiBaseURL+"/spec.yaml")
require.NoError(t, waitHTTPOrExit(ctx, apiBaseURL+"/spec.yaml", exitCh), "api not ready: %v", err)
client, err := apiClient()
require.NoError(t, err, "failed to create API client: %v", err)
// Get initial Xvfb resolution
logger.Info("[test]", "action", "getting initial Xvfb resolution")
initialWidth, initialHeight, err := getXvfbResolution(ctx)
require.NoError(t, err, "failed to get initial Xvfb resolution: %v", err)
logger.Info("[test]", "initial_resolution", fmt.Sprintf("%dx%d", initialWidth, initialHeight))
require.Equal(t, 1024, initialWidth, "expected initial width 1024")
require.Equal(t, 768, initialHeight, "expected initial height 768")
// Test first resolution change: 1920x1080
logger.Info("[test]", "action", "changing resolution to 1920x1080")
width1 := 1920
height1 := 1080
req1 := instanceoapi.PatchDisplayJSONRequestBody{
Width: &width1,
Height: &height1,
}
rsp1, err := client.PatchDisplayWithResponse(ctx, req1)
require.NoError(t, err, "PATCH /display request failed: %v", err)
require.Equal(t, http.StatusOK, rsp1.StatusCode(), "unexpected status: %s body=%s", rsp1.Status(), string(rsp1.Body))
require.NotNil(t, rsp1.JSON200, "expected JSON200 response, got nil")
require.NotNil(t, rsp1.JSON200.Width, "expected width in response")
require.Equal(t, width1, *rsp1.JSON200.Width, "expected width %d in response", width1)
require.NotNil(t, rsp1.JSON200.Height, "expected height in response")
require.Equal(t, height1, *rsp1.JSON200.Height, "expected height %d in response", height1)
// Wait a bit for Xvfb to fully restart
logger.Info("[test]", "action", "waiting for Xvfb to stabilize")
time.Sleep(3 * time.Second)
// Verify new resolution via ps aux
logger.Info("[test]", "action", "verifying new Xvfb resolution")
newWidth1, newHeight1, err := getXvfbResolution(ctx)
require.NoError(t, err, "failed to get new Xvfb resolution: %v", err)
logger.Info("[test]", "new_resolution", fmt.Sprintf("%dx%d", newWidth1, newHeight1))
require.Equal(t, width1, newWidth1, "expected Xvfb resolution %dx%d, got %dx%d", width1, height1, newWidth1, newHeight1)
require.Equal(t, height1, newHeight1, "expected Xvfb resolution %dx%d, got %dx%d", width1, height1, newWidth1, newHeight1)
// Test second resolution change: 1280x720
logger.Info("[test]", "action", "changing resolution to 1280x720")
width2 := 1280
height2 := 720
req2 := instanceoapi.PatchDisplayJSONRequestBody{
Width: &width2,
Height: &height2,
}
rsp2, err := client.PatchDisplayWithResponse(ctx, req2)
require.NoError(t, err, "PATCH /display request failed: %v", err)
require.Equal(t, http.StatusOK, rsp2.StatusCode(), "unexpected status: %s body=%s", rsp2.Status(), string(rsp2.Body))
require.NotNil(t, rsp2.JSON200, "expected JSON200 response, got nil")
require.NotNil(t, rsp2.JSON200.Width, "expected width in response")
require.Equal(t, width2, *rsp2.JSON200.Width, "expected width %d in response", width2)
require.NotNil(t, rsp2.JSON200.Height, "expected height in response")
require.Equal(t, height2, *rsp2.JSON200.Height, "expected height %d in response", height2)
// Wait a bit for Xvfb to fully restart
logger.Info("[test]", "action", "waiting for Xvfb to stabilize")
time.Sleep(3 * time.Second)
// Verify second resolution change via ps aux
logger.Info("[test]", "action", "verifying second Xvfb resolution")
newWidth2, newHeight2, err := getXvfbResolution(ctx)
require.NoError(t, err, "failed to get second Xvfb resolution: %v", err)
logger.Info("[test]", "final_resolution", fmt.Sprintf("%dx%d", newWidth2, newHeight2))
require.Equal(t, width2, newWidth2, "expected Xvfb resolution %dx%d, got %dx%d", width2, height2, newWidth2, newHeight2)
require.Equal(t, height2, newHeight2, "expected Xvfb resolution %dx%d, got %dx%d", width2, height2, newWidth2, newHeight2)
logger.Info("[test]", "result", "all resolution changes verified successfully")
}
func TestExtensionUploadAndActivation(t *testing.T) {
ensurePlaywrightDeps(t)
image := headlessImage
name := containerName + "-ext"
logger := slog.New(slog.NewTextHandler(t.Output(), &slog.HandlerOptions{Level: slog.LevelInfo}))
baseCtx := logctx.AddToContext(context.Background(), logger)
if _, err := exec.LookPath("docker"); err != nil {
require.NoError(t, err, "docker not available: %v", err)
}
// Clean slate
_ = stopContainer(baseCtx, name)
env := map[string]string{}
// headless uses stealth defaults; no need to set CHROMIUM_FLAGS here
// Start container
_, exitCh, err := runContainer(baseCtx, image, name, env)
require.NoError(t, err, "failed to start container: %v", err)
defer stopContainer(baseCtx, name)
ctx, cancel := context.WithTimeout(baseCtx, 3*time.Minute)
defer cancel()
require.NoError(t, waitHTTPOrExit(ctx, apiBaseURL+"/spec.yaml", exitCh), "api not ready: %v", err)
// Wait for DevTools
_, err = waitDevtoolsWS(ctx)
require.NoError(t, err, "devtools not ready: %v", err)
// Build simple MV3 extension zip in-memory
extDir := t.TempDir()
manifest := `{
"manifest_version": 3,
"version": "1.0",
"name": "My Test Extension",
"description": "Test of a simple browser extension",
"content_scripts": [
{
"matches": [
"https://www.sfmoma.org/*"
],
"js": [
"content-script.js"
]
}
]
}`
contentScript := "document.title += \" -- Title updated by browser extension\";\n"
err = os.WriteFile(filepath.Join(extDir, "manifest.json"), []byte(manifest), 0600)
require.NoError(t, err, "write manifest: %v", err)
err = os.WriteFile(filepath.Join(extDir, "content-script.js"), []byte(contentScript), 0600)
require.NoError(t, err, "write content-script: %v", err)
extZip, err := zipDirToBytes(extDir)
require.NoError(t, err, "zip ext: %v", err)
// Use new API to upload extension and restart Chromium
{
client, err := apiClient()
require.NoError(t, err)
var body bytes.Buffer
w := multipart.NewWriter(&body)
fw, err := w.CreateFormFile("extensions.zip_file", "ext.zip")
require.NoError(t, err)
_, err = io.Copy(fw, bytes.NewReader(extZip))
require.NoError(t, err)
err = w.WriteField("extensions.name", "testext")
require.NoError(t, err)
err = w.Close()
require.NoError(t, err)
start := time.Now()
rsp, err := client.UploadExtensionsAndRestartWithBodyWithResponse(ctx, w.FormDataContentType(), &body)
elapsed := time.Since(start)
require.NoError(t, err, "uploadExtensionsAndRestart request error: %v", err)
require.Equal(t, http.StatusCreated, rsp.StatusCode(), "unexpected status: %s body=%s", rsp.Status(), string(rsp.Body))
t.Logf("/chromium/upload-extensions-and-restart completed in %s (%d ms)", elapsed.String(), elapsed.Milliseconds())
}
// Verify the content script updated the title on an allowed URL
{
cmd := exec.CommandContext(ctx, "pnpm", "exec", "tsx", "index.ts",
"verify-title-contains",
"--url", "https://www.sfmoma.org/",
"--substr", "Title updated by browser extension",
"--ws-url", "ws://127.0.0.1:9222/",
"--timeout", "45000",
)
cmd.Dir = getPlaywrightPath()
out, err := cmd.CombinedOutput()
require.NoError(t, err, "title verify failed: %v output=%s", err, string(out))
}
}
func TestScreenshotHeadless(t *testing.T) {
image := headlessImage
name := containerName + "-screenshot-headless"
logger := slog.New(slog.NewTextHandler(t.Output(), &slog.HandlerOptions{Level: slog.LevelInfo}))
baseCtx := logctx.AddToContext(context.Background(), logger)
if _, err := exec.LookPath("docker"); err != nil {
require.NoError(t, err, "docker not available: %v", err)
}
// Clean slate
_ = stopContainer(baseCtx, name)
env := map[string]string{}
// Start container
_, exitCh, err := runContainer(baseCtx, image, name, env)
require.NoError(t, err, "failed to start container: %v", err)
defer stopContainer(baseCtx, name)
ctx, cancel := context.WithTimeout(baseCtx, 2*time.Minute)
defer cancel()
require.NoError(t, waitHTTPOrExit(ctx, apiBaseURL+"/spec.yaml", exitCh), "api not ready: %v", err)
client, err := apiClient()
require.NoError(t, err)
// Whole-screen screenshot
{
rsp, err := client.TakeScreenshotWithResponse(ctx, instanceoapi.TakeScreenshotJSONRequestBody{})
require.NoError(t, err, "screenshot request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for full screenshot: %s body=%s", rsp.Status(), string(rsp.Body))
require.True(t, isPNG(rsp.Body), "response is not PNG (len=%d)", len(rsp.Body))
}
// Region screenshot (safe small region)
{
region := instanceoapi.ScreenshotRegion{X: 0, Y: 0, Width: 50, Height: 50}
req := instanceoapi.TakeScreenshotJSONRequestBody{Region: ®ion}
rsp, err := client.TakeScreenshotWithResponse(ctx, req)
require.NoError(t, err, "region screenshot request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for region screenshot: %s body=%s", rsp.Status(), string(rsp.Body))
require.True(t, isPNG(rsp.Body), "region response is not PNG (len=%d)", len(rsp.Body))
}
}
func TestScreenshotHeadful(t *testing.T) {
image := headfulImage
name := containerName + "-screenshot-headful"
logger := slog.New(slog.NewTextHandler(t.Output(), &slog.HandlerOptions{Level: slog.LevelInfo}))
baseCtx := logctx.AddToContext(context.Background(), logger)
if _, err := exec.LookPath("docker"); err != nil {
require.NoError(t, err, "docker not available: %v", err)
}
// Clean slate
_ = stopContainer(baseCtx, name)
env := map[string]string{
"WIDTH": "1024",
"HEIGHT": "768",
}
// Start container
_, exitCh, err := runContainer(baseCtx, image, name, env)
require.NoError(t, err, "failed to start container: %v", err)
defer stopContainer(baseCtx, name)
ctx, cancel := context.WithTimeout(baseCtx, 2*time.Minute)
defer cancel()
require.NoError(t, waitHTTPOrExit(ctx, apiBaseURL+"/spec.yaml", exitCh), "api not ready: %v", err)
client, err := apiClient()
require.NoError(t, err)
// Whole-screen screenshot
{
rsp, err := client.TakeScreenshotWithResponse(ctx, instanceoapi.TakeScreenshotJSONRequestBody{})
require.NoError(t, err, "screenshot request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for full screenshot: %s body=%s", rsp.Status(), string(rsp.Body))
require.True(t, isPNG(rsp.Body), "response is not PNG (len=%d)", len(rsp.Body))
}
// Region screenshot
{
region := instanceoapi.ScreenshotRegion{X: 0, Y: 0, Width: 80, Height: 60}
req := instanceoapi.TakeScreenshotJSONRequestBody{Region: ®ion}
rsp, err := client.TakeScreenshotWithResponse(ctx, req)
require.NoError(t, err, "region screenshot request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for region screenshot: %s body=%s", rsp.Status(), string(rsp.Body))
require.True(t, isPNG(rsp.Body), "region response is not PNG (len=%d)", len(rsp.Body))
}
}
func TestInputEndpointsSmoke(t *testing.T) {
image := headlessImage
name := containerName + "-input-smoke"
logger := slog.New(slog.NewTextHandler(t.Output(), &slog.HandlerOptions{Level: slog.LevelInfo}))
baseCtx := logctx.AddToContext(context.Background(), logger)
if _, err := exec.LookPath("docker"); err != nil {
require.NoError(t, err, "docker not available: %v", err)
}
_ = stopContainer(baseCtx, name)
width, height := 1024, 768
_, exitCh, err := runContainer(baseCtx, image, name, map[string]string{"WIDTH": strconv.Itoa(width), "HEIGHT": strconv.Itoa(height)})
require.NoError(t, err, "failed to start container: %v", err)
defer stopContainer(baseCtx, name)
ctx, cancel := context.WithTimeout(baseCtx, 2*time.Minute)
defer cancel()
require.NoError(t, waitHTTPOrExit(ctx, apiBaseURL+"/spec.yaml", exitCh), "api not ready: %v", err)
client, err := apiClient()
require.NoError(t, err)
// press_key: tap Return
{
rsp, err := client.PressKeyWithResponse(ctx, instanceoapi.PressKeyJSONRequestBody{Keys: []string{"Return"}})
require.NoError(t, err, "press_key request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for press_key: %s body=%s", rsp.Status(), string(rsp.Body))
}
// scroll: small vertical and horizontal ticks at center
cx, cy := width/2, height/2
{
rsp, err := client.ScrollWithResponse(ctx, instanceoapi.ScrollJSONRequestBody{X: cx, Y: cy, DeltaX: lo.ToPtr(2), DeltaY: lo.ToPtr(-3)})
require.NoError(t, err, "scroll request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for scroll: %s body=%s", rsp.Status(), string(rsp.Body))
}
// drag_mouse: simple short drag path
{
rsp, err := client.DragMouseWithResponse(ctx, instanceoapi.DragMouseJSONRequestBody{
Path: [][]int{{cx - 10, cy - 10}, {cx + 10, cy + 10}},
})
require.NoError(t, err, "drag_mouse request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for drag_mouse: %s body=%s", rsp.Status(), string(rsp.Body))
}
}
// isPNG returns true if data starts with the PNG magic header
func isPNG(data []byte) bool {
if len(data) < 8 {
return false
}
sig := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}
for i := 0; i < 8; i++ {
if data[i] != sig[i] {
return false
}
}
return true
}
func runContainer(ctx context.Context, image, name string, env map[string]string) (*exec.Cmd, <-chan error, error) {
logger := logctx.FromContext(ctx)
args := []string{
"run",
"--name", name,
"--privileged",
"-p", "10001:10001", // API server
"-p", "9222:9222", // DevTools proxy
"--tmpfs", "/dev/shm:size=2g",
}
for k, v := range env {
args = append(args, "-e", fmt.Sprintf("%s=%s", k, v))
}
args = append(args, image)
logger.Info("[docker]", "action", "run", "args", strings.Join(args, " "))
cmd := exec.Command("docker", args...)
if err := cmd.Start(); err != nil {
return nil, nil, err
}
exitCh := make(chan error, 1)
go func() {
exitCh <- cmd.Wait()
}()
return cmd, exitCh, nil
}
func stopContainer(ctx context.Context, name string) error {
_ = exec.CommandContext(ctx, "docker", "kill", name).Run()
_ = exec.CommandContext(ctx, "docker", "rm", "-f", name).Run()
// Wait loop to ensure the container is actually gone
const maxWait = 10 * time.Second
const pollInterval = 200 * time.Millisecond
deadline := time.Now().Add(maxWait)
var lastCheckErr error
for {
cmd := exec.CommandContext(ctx, "docker", "ps", "-a", "--filter", fmt.Sprintf("name=%s", name), "--format", "{{.Names}}")
out, err := cmd.Output()
if err != nil {
// If docker itself fails, break out (maybe docker is gone)
lastCheckErr = err
break
}
names := strings.Fields(string(out))
found := false
for _, n := range names {
if n == name {
found = true
break
}
}
if !found {
break // container is gone
}
if time.Now().After(deadline) {
lastCheckErr = fmt.Errorf("timeout waiting for container %s to be removed", name)
break // give up after maxWait
}
time.Sleep(pollInterval)
}
if lastCheckErr != nil {
return lastCheckErr
}
return nil
}
func waitHTTPOrExit(ctx context.Context, url string, exitCh <-chan error) error {
client := &http.Client{Timeout: 5 * time.Second}
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := client.Do(req)
if err == nil && resp.StatusCode >= 200 && resp.StatusCode < 500 {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
return nil
}
if resp != nil && resp.Body != nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
select {
case <-ctx.Done():
return ctx.Err()
case err := <-exitCh:
if err != nil {
return fmt.Errorf("container exited while waiting for %s: %w", url, err)
}
return fmt.Errorf("container exited while waiting for %s", url)
case <-ticker.C:
}
}
}
func waitTCP(ctx context.Context, hostport string) error {
d := net.Dialer{Timeout: 2 * time.Second}
ticker := time.NewTicker(300 * time.Millisecond)
defer ticker.Stop()
for {
conn, err := d.DialContext(ctx, "tcp", hostport)
if err == nil {
conn.Close()
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}
func waitDevtoolsWS(ctx context.Context) (string, error) {
if err := waitTCP(ctx, "127.0.0.1:9222"); err != nil {
return "", err
}
return "ws://127.0.0.1:9222/", nil
}
func apiClient() (*instanceoapi.ClientWithResponses, error) {
return instanceoapi.NewClientWithResponses(apiBaseURL, instanceoapi.WithHTTPClient(http.DefaultClient))
}
// RemoteExecError represents a non-zero exit from a remote exec, exposing exit code and combined output
type RemoteExecError struct {
Command string
Args []string
ExitCode int
Output string
}
func (e *RemoteExecError) Error() string {
return fmt.Sprintf("remote exec %s exited with code %d", e.Command, e.ExitCode)
}
// execCombinedOutput runs a command via the remote API and returns combined stdout+stderr and an error if exit code != 0
func execCombinedOutput(ctx context.Context, command string, args []string) (string, error) {
client, err := apiClient()
if err != nil {
return "", err
}
req := instanceoapi.ProcessExecJSONRequestBody{
Command: command,
Args: &args,
}
rsp, err := client.ProcessExecWithResponse(ctx, req)
if err != nil {
return "", err
}
if rsp.JSON200 == nil {
return "", fmt.Errorf("remote exec failed: %s body=%s", rsp.Status(), string(rsp.Body))
}
var stdout, stderr string
if rsp.JSON200.StdoutB64 != nil && *rsp.JSON200.StdoutB64 != "" {
if b, decErr := base64.StdEncoding.DecodeString(*rsp.JSON200.StdoutB64); decErr == nil {
stdout = string(b)
}
}
if rsp.JSON200.StderrB64 != nil && *rsp.JSON200.StderrB64 != "" {
if b, decErr := base64.StdEncoding.DecodeString(*rsp.JSON200.StderrB64); decErr == nil {
stderr = string(b)
}
}
combined := stdout + stderr
exitCode := 0
if rsp.JSON200.ExitCode != nil {
exitCode = *rsp.JSON200.ExitCode
}
if exitCode != 0 {
return combined, &RemoteExecError{Command: command, Args: args, ExitCode: exitCode, Output: combined}
}
return combined, nil
}
// zipDirToBytes zips the contents of dir (no extra top-level folder) to bytes
func zipDirToBytes(dir string) ([]byte, error) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
defer zw.Close()
// Walk dir
root := filepath.Clean(dir)
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if path == root {
return nil
}
rel, err := filepath.Rel(root, path)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
if info.IsDir() {
_, err := zw.Create(rel + "/")
return err
}
fh, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
fh.Name = rel
fh.Method = zip.Deflate
w, err := zw.CreateHeader(fh)
if err != nil {
return err
}
f, err := os.Open(path)
if err != nil {
return err
}
_, copyErr := io.Copy(w, f)
f.Close()
return copyErr
})
if err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// getXvfbResolution extracts the Xvfb resolution from the ps aux output
// It looks for the Xvfb command line which contains "-screen 0 WIDTHxHEIGHTx24"
func getXvfbResolution(ctx context.Context) (width, height int, err error) {
logger := logctx.FromContext(ctx)
// Get ps aux output
stdout, err := execCombinedOutput(ctx, "ps", []string{"aux"})
if err != nil {
return 0, 0, fmt.Errorf("failed to execute ps aux: %w, output: %s", err, stdout)
}
logger.Info("[xvfb-resolution]", "action", "parsing ps aux output")
// Look for Xvfb line
// Expected format: "root ... Xvfb :1 -screen 0 1920x1080x24 ..."
lines := strings.Split(stdout, "\n")
for _, line := range lines {
if !strings.Contains(line, "Xvfb") {
continue
}
logger.Info("[xvfb-resolution]", "line", line)
// Parse the screen parameter
// Look for pattern: "-screen 0 WIDTHxHEIGHTx24"
fields := strings.Fields(line)
for i, field := range fields {
if field == "-screen" && i+2 < len(fields) {
// Next field should be "0", and the one after should be the resolution
screenSpec := fields[i+2]
logger.Info("[xvfb-resolution]", "screen_spec", screenSpec)
// Parse WIDTHxHEIGHTx24
parts := strings.Split(screenSpec, "x")
if len(parts) >= 2 {
w, err := strconv.Atoi(parts[0])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse width from %q: %w", screenSpec, err)
}
h, err := strconv.Atoi(parts[1])
if err != nil {
return 0, 0, fmt.Errorf("failed to parse height from %q: %w", screenSpec, err)
}
logger.Info("[xvfb-resolution]", "parsed", fmt.Sprintf("%dx%d", w, h))
return w, h, nil
}
}
}
}
return 0, 0, fmt.Errorf("Xvfb process not found in ps aux output")
}
func TestPlaywrightExecuteAPI(t *testing.T) {
image := headlessImage
name := containerName + "-playwright-api"
logger := slog.New(slog.NewTextHandler(t.Output(), &slog.HandlerOptions{Level: slog.LevelInfo}))
baseCtx := logctx.AddToContext(context.Background(), logger)
if _, err := exec.LookPath("docker"); err != nil {
require.NoError(t, err, "docker not available: %v", err)
}
// Clean slate
_ = stopContainer(baseCtx, name)
env := map[string]string{}
// Start container
_, exitCh, err := runContainer(baseCtx, image, name, env)
require.NoError(t, err, "failed to start container: %v", err)
defer stopContainer(baseCtx, name)
ctx, cancel := context.WithTimeout(baseCtx, 2*time.Minute)
defer cancel()
require.NoError(t, waitHTTPOrExit(ctx, apiBaseURL+"/spec.yaml", exitCh), "api not ready: %v", err)
client, err := apiClient()
require.NoError(t, err)
// Test simple Playwright script that navigates to a page and returns the title
playwrightCode := `
await page.goto('https://example.com');
const title = await page.title();
return title;
`
logger.Info("[test]", "action", "executing playwright code")
req := instanceoapi.ExecutePlaywrightCodeJSONRequestBody{
Code: playwrightCode,
}
rsp, err := client.ExecutePlaywrightCodeWithResponse(ctx, req)
require.NoError(t, err, "playwright execute request error: %v", err)
require.Equal(t, http.StatusOK, rsp.StatusCode(), "unexpected status for playwright execute: %s body=%s", rsp.Status(), string(rsp.Body))
require.NotNil(t, rsp.JSON200, "expected JSON200 response, got nil")
// Log the full response for debugging
if !rsp.JSON200.Success {
var errorMsg string
if rsp.JSON200.Error != nil {
errorMsg = *rsp.JSON200.Error
}
var stdout, stderr string
if rsp.JSON200.Stdout != nil {
stdout = *rsp.JSON200.Stdout
}
if rsp.JSON200.Stderr != nil {
stderr = *rsp.JSON200.Stderr
}
logger.Error("[test]", "error", errorMsg, "stdout", stdout, "stderr", stderr)
}
require.True(t, rsp.JSON200.Success, "expected success=true, got success=false. Error: %s", func() string {
if rsp.JSON200.Error != nil {
return *rsp.JSON200.Error
}
return "nil"
}())
require.NotNil(t, rsp.JSON200.Result, "expected result to be non-nil")
// Verify the result contains "Example Domain" (the title of example.com)
resultBytes, err := json.Marshal(rsp.JSON200.Result)
require.NoError(t, err, "failed to marshal result: %v", err)
resultStr := string(resultBytes)
logger.Info("[test]", "result", resultStr)
require.Contains(t, resultStr, "Example Domain", "expected result to contain 'Example Domain'")
logger.Info("[test]", "result", "playwright execute API test passed")
}