playwright-rs 0.12.3

Rust bindings for Microsoft Playwright
Documentation
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
use playwright_rs::protocol::{BrowserContextOptions, Geolocation, Playwright, Viewport};
use std::env;

#[tokio::test]
async fn test_new_context() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    tracing::info!("✓ Context created");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_multiple_contexts() {
    let (_pw, browser, context1) = crate::common::setup_context().await;

    // Create a second context
    let context2 = browser
        .new_context()
        .await
        .expect("Failed to create context 2");

    tracing::info!("✓ Created 2 contexts");

    // Cleanup
    context1.close().await.expect("Failed to close context 1");
    context2.close().await.expect("Failed to close context 2");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_with_viewport() {
    crate::common::init_tracing();
    // Test creating context with custom viewport
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder()
        .viewport(Viewport {
            width: 1024,
            height: 768,
        })
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with viewport");

    let page = context.new_page().await.expect("Failed to create page");

    // Verify viewport dimensions via JavaScript
    let width = page
        .evaluate_value("window.innerWidth")
        .await
        .expect("Failed to evaluate width");
    assert_eq!(width.parse::<i32>().unwrap(), 1024);

    let height = page
        .evaluate_value("window.innerHeight")
        .await
        .expect("Failed to evaluate height");
    assert_eq!(height.parse::<i32>().unwrap(), 768);

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_with_user_agent() {
    crate::common::init_tracing();
    // Test creating context with custom user agent
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let custom_ua = "CustomBot/1.0";
    let options = BrowserContextOptions::builder()
        .user_agent(custom_ua.to_string())
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with user agent");

    let page = context.new_page().await.expect("Failed to create page");

    // Verify user agent via JavaScript
    let ua = page
        .evaluate_value("navigator.userAgent")
        .await
        .expect("Failed to evaluate user agent");
    assert_eq!(ua, custom_ua);

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_with_locale() {
    crate::common::init_tracing();
    // Test creating context with custom locale
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder()
        .locale("fr-FR".to_string())
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with locale");

    let page = context.new_page().await.expect("Failed to create page");

    // Verify locale via JavaScript
    let locale = page
        .evaluate_value("navigator.language")
        .await
        .expect("Failed to evaluate locale");
    assert_eq!(locale, "fr-FR");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_with_timezone() {
    crate::common::init_tracing();
    // Test creating context with custom timezone
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder()
        .timezone_id("America/New_York".to_string())
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with timezone");

    let page = context.new_page().await.expect("Failed to create page");

    // Verify timezone via JavaScript
    let tz = page
        .evaluate_value("Intl.DateTimeFormat().resolvedOptions().timeZone")
        .await
        .expect("Failed to evaluate timezone");
    assert_eq!(tz, "America/New_York");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_with_geolocation() {
    crate::common::init_tracing();
    // Test creating context with geolocation
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder()
        .geolocation(Geolocation {
            latitude: 48.8584, // Paris
            longitude: 2.2945,
            accuracy: Some(100.0),
        })
        .permissions(vec!["geolocation".to_string()])
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with geolocation");

    let page = context.new_page().await.expect("Failed to create page");

    // Verify geolocation permission is granted by checking navigator.permissions
    // (actual geolocation requires page navigation which may be complex in tests)
    // Just verify the context was created successfully with geolocation options
    let has_geolocation = page
        .evaluate_value("'geolocation' in navigator")
        .await
        .expect("Failed to check geolocation");
    assert_eq!(has_geolocation, "true");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_offline_mode() {
    crate::common::init_tracing();
    // Test creating context in offline mode
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder().offline(true).build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context in offline mode");

    let page = context.new_page().await.expect("Failed to create page");

    // Try to navigate to a real website - should fail due to offline mode
    let result = page.goto("https://example.com", None).await;
    assert!(result.is_err(), "Navigation should fail in offline mode");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_combined_options() {
    crate::common::init_tracing();
    // Test creating context with multiple options combined
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder()
        .viewport(Viewport {
            width: 800,
            height: 600,
        })
        .user_agent("CustomBot/2.0".to_string())
        .locale("de-DE".to_string())
        .timezone_id("Europe/Berlin".to_string())
        .color_scheme("dark".to_string())
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with combined options");

    let page = context.new_page().await.expect("Failed to create page");

    // Verify viewport
    let width = page
        .evaluate_value("window.innerWidth")
        .await
        .expect("Failed to evaluate width");
    assert_eq!(width.parse::<i32>().unwrap(), 800);

    // Verify user agent
    let ua = page
        .evaluate_value("navigator.userAgent")
        .await
        .expect("Failed to evaluate user agent");
    assert_eq!(ua, "CustomBot/2.0");

    // Verify locale
    let locale = page
        .evaluate_value("navigator.language")
        .await
        .expect("Failed to evaluate locale");
    assert_eq!(locale, "de-DE");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_no_viewport() {
    crate::common::init_tracing();
    // Test creating context with no viewport (null viewport)
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder().no_viewport(true).build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with no viewport");

    let page = context.new_page().await.expect("Failed to create page");

    // With no viewport, dimensions should match the browser window
    // This is typically larger than the default 1280x720
    let width = page
        .evaluate_value("window.innerWidth")
        .await
        .expect("Failed to evaluate width");

    // Just verify we got a reasonable width (should be different from default 1280)
    let width_val = width.parse::<i32>().unwrap();
    assert!(width_val > 0, "Width should be positive");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
#[ignore]
async fn test_context_cross_browser_options() {
    crate::common::init_tracing();
    // Verify context options work across Chromium, Firefox, and WebKit
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");

    for browser_name in &["chromium", "firefox", "webkit"] {
        let browser = match *browser_name {
            "chromium" => playwright.chromium().launch().await.unwrap(),
            "firefox" => playwright.firefox().launch().await.unwrap(),
            "webkit" => playwright.webkit().launch().await.unwrap(),
            _ => unreachable!(),
        };

        let options = BrowserContextOptions::builder()
            .viewport(Viewport {
                width: 640,
                height: 480,
            })
            .locale("en-US".to_string())
            .build();

        let context = browser
            .new_context_with_options(options)
            .await
            .unwrap_or_else(|e| panic!("Failed to create context in {}: {}", browser_name, e));

        let page = context
            .new_page()
            .await
            .unwrap_or_else(|e| panic!("Failed to create page in {}: {}", browser_name, e));

        // Verify viewport works in all browsers
        let width = page
            .evaluate_value("window.innerWidth")
            .await
            .unwrap_or_else(|e| panic!("Failed to evaluate in {}: {}", browser_name, e));
        assert_eq!(width.parse::<i32>().unwrap(), 640);

        context.close().await.unwrap();
        browser.close().await.unwrap();
    }
}

// ============================================================================
// StorageState Tests (Issue #6)
// ============================================================================

#[tokio::test]
async fn test_context_with_storage_state_inline() {
    use playwright_rs::protocol::{Cookie, LocalStorageItem, Origin, StorageState};
    crate::common::init_tracing();

    // Test creating context with inline storage state
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    // Create storage state with cookies and localStorage
    let storage_state = StorageState {
        cookies: vec![Cookie {
            name: "test_cookie".to_string(),
            value: "test_value".to_string(),
            domain: ".example.com".to_string(),
            path: "/".to_string(),
            expires: -1.0,
            http_only: false,
            secure: false,
            same_site: Some("Lax".to_string()),
        }],
        origins: vec![Origin {
            origin: "https://example.com".to_string(),
            local_storage: vec![LocalStorageItem {
                name: "test_key".to_string(),
                value: "test_storage_value".to_string(),
            }],
        }],
    };

    let options = BrowserContextOptions::builder()
        .storage_state(storage_state)
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with storage state");

    let page = context.new_page().await.expect("Failed to create page");

    // Navigate to example.com to verify storage state was loaded
    page.goto("https://example.com", None)
        .await
        .expect("Failed to navigate");

    // Verify cookie was set
    let cookie_value = page
        .evaluate_value("document.cookie")
        .await
        .expect("Failed to evaluate cookie");
    assert!(
        cookie_value.contains("test_cookie=test_value"),
        "Cookie should be set"
    );

    // Verify localStorage was set
    let storage_value = page
        .evaluate_value("localStorage.getItem('test_key')")
        .await
        .expect("Failed to evaluate localStorage");
    assert_eq!(storage_value, "test_storage_value");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
async fn test_context_with_storage_state_from_file() {
    crate::common::init_tracing();

    // Test creating context with storage state from file
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    // Create a temporary storage state file
    let temp_dir = std::env::temp_dir();
    let storage_file = temp_dir.join("test_storage_state.json");

    // Write storage state to file
    let storage_json = r#"{
        "cookies": [{
            "name": "file_cookie",
            "value": "file_value",
            "domain": ".example.com",
            "path": "/",
            "expires": -1,
            "httpOnly": false,
            "secure": false,
            "sameSite": "Lax"
        }],
        "origins": [{
            "origin": "https://example.com",
            "localStorage": [{
                "name": "file_key",
                "value": "file_storage_value"
            }]
        }]
    }"#;

    std::fs::write(&storage_file, storage_json).expect("Failed to write storage file");

    let options = BrowserContextOptions::builder()
        .storage_state_path(storage_file.to_str().unwrap().to_string())
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with storage state from file");

    let page = context.new_page().await.expect("Failed to create page");

    // Navigate to example.com to verify storage state was loaded
    page.goto("https://example.com", None)
        .await
        .expect("Failed to navigate");

    // Verify cookie was set
    let cookie_value = page
        .evaluate_value("document.cookie")
        .await
        .expect("Failed to evaluate cookie");
    assert!(
        cookie_value.contains("file_cookie=file_value"),
        "Cookie from file should be set"
    );

    // Verify localStorage was set
    let storage_value = page
        .evaluate_value("localStorage.getItem('file_key')")
        .await
        .expect("Failed to evaluate localStorage");
    assert_eq!(storage_value, "file_storage_value");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");

    // Cleanup
    std::fs::remove_file(&storage_file).ok();
}

#[tokio::test]
async fn test_context_storage_state_invalid_file() {
    crate::common::init_tracing();

    // Test that invalid storage state file path returns error
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let options = BrowserContextOptions::builder()
        .storage_state_path("/nonexistent/path/to/storage.json".to_string())
        .build();

    let result = browser.new_context_with_options(options).await;

    // Should fail with error about missing file
    assert!(
        result.is_err(),
        "Creating context with non-existent storage file should fail"
    );

    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
#[ignore]
async fn test_context_storage_state_cross_browser() {
    use playwright_rs::protocol::{Cookie, LocalStorageItem, Origin, StorageState};
    crate::common::init_tracing();

    // Verify storage state works across Chromium, Firefox, and WebKit
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");

    for browser_name in &["chromium", "firefox", "webkit"] {
        let browser = match *browser_name {
            "chromium" => playwright.chromium().launch().await.unwrap(),
            "firefox" => playwright.firefox().launch().await.unwrap(),
            "webkit" => playwright.webkit().launch().await.unwrap(),
            _ => unreachable!(),
        };

        // Create storage state with cookies
        let storage_state = StorageState {
            cookies: vec![Cookie {
                name: "browser_test_cookie".to_string(),
                value: format!("{}_value", browser_name),
                domain: ".example.com".to_string(),
                path: "/".to_string(),
                expires: -1.0,
                http_only: false,
                secure: false,
                same_site: Some("Lax".to_string()),
            }],
            origins: vec![Origin {
                origin: "https://example.com".to_string(),
                local_storage: vec![LocalStorageItem {
                    name: "browser_key".to_string(),
                    value: format!("{}_storage", browser_name),
                }],
            }],
        };

        let options = BrowserContextOptions::builder()
            .storage_state(storage_state)
            .build();

        let context = browser
            .new_context_with_options(options)
            .await
            .unwrap_or_else(|e| {
                panic!(
                    "Failed to create context with storage state in {}: {}",
                    browser_name, e
                )
            });

        let page = context
            .new_page()
            .await
            .unwrap_or_else(|e| panic!("Failed to create page in {}: {}", browser_name, e));

        // Navigate to example.com
        page.goto("https://example.com", None)
            .await
            .unwrap_or_else(|e| panic!("Failed to navigate in {}: {}", browser_name, e));

        // Verify cookie was set
        let cookie_value = page
            .evaluate_value("document.cookie")
            .await
            .unwrap_or_else(|e| panic!("Failed to evaluate cookie in {}: {}", browser_name, e));
        assert!(
            cookie_value.contains(&format!("browser_test_cookie={}_value", browser_name)),
            "Cookie should be set in {}",
            browser_name
        );

        context.close().await.unwrap();
        browser.close().await.unwrap();
    }
}

#[tokio::test]
async fn test_context_storage_state_empty() {
    use playwright_rs::protocol::StorageState;
    crate::common::init_tracing();

    // Test creating context with empty storage state (should work fine)
    let playwright = Playwright::launch()
        .await
        .expect("Failed to launch Playwright");
    let browser = playwright
        .chromium()
        .launch()
        .await
        .expect("Failed to launch browser");

    let storage_state = StorageState {
        cookies: vec![],
        origins: vec![],
    };

    let options = BrowserContextOptions::builder()
        .storage_state(storage_state)
        .build();

    let context = browser
        .new_context_with_options(options)
        .await
        .expect("Failed to create context with empty storage state");

    let page = context.new_page().await.expect("Failed to create page");

    // Should work fine with no cookies/storage
    page.goto("https://example.com", None)
        .await
        .expect("Failed to navigate");

    context.close().await.expect("Failed to close context");
    browser.close().await.expect("Failed to close browser");
}

// Tests for BrowserContext.pages() and BrowserContext.browser() methods
//
// This test module verifies:
// - context.pages() returns empty vec initially
// - context.pages() includes pages after new_page()
// - context.pages() includes initial page in persistent context with --app
// - context.browser() returns Browser for regular contexts
// - context.browser() returns None for persistent contexts (Playwright behavior)
// - Cross-browser compatibility

#[tokio::test]
async fn test_context_pages_empty_initially() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Initially, context should have no pages
    let pages = context.pages();
    assert_eq!(pages.len(), 0, "New context should have no pages");

    context.close().await.unwrap();
    browser.close().await.unwrap();
}

#[tokio::test]
async fn test_context_pages_includes_new_page() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Create a page
    let page1 = context.new_page().await.unwrap();

    // Context should now include the page
    let pages = context.pages();
    assert_eq!(pages.len(), 1, "Context should have 1 page");

    // Verify it's the same page (by URL initially at about:blank)
    assert_eq!(pages[0].url(), page1.url());

    // Create another page
    let _page2 = context.new_page().await.unwrap();

    // Context should now include both pages
    let pages = context.pages();
    assert_eq!(pages.len(), 2, "Context should have 2 pages");

    context.close().await.unwrap();
    browser.close().await.unwrap();
}

#[tokio::test]
async fn test_context_pages_includes_initial_app_mode_page() {
    let playwright = Playwright::launch().await.unwrap();
    let chromium = playwright.chromium();

    // Create temp user data dir
    let user_data_dir = env::temp_dir()
        .join(format!(
            "pw-rust-test-app-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ))
        .to_string_lossy()
        .to_string();

    // Launch persistent context with --app mode
    let options = playwright_rs::protocol::BrowserContextOptions::builder()
        .headless(true)
        .args(vec!["--app=https://example.com".to_string()])
        .build();

    let context = chromium
        .launch_persistent_context_with_options(&user_data_dir, options)
        .await
        .unwrap();

    // In app mode, Playwright creates an initial page automatically
    let pages = context.pages();
    assert!(
        !pages.is_empty(),
        "Persistent context with --app should have initial page"
    );

    // The initial page should be navigating to or at the app URL
    // (may still be loading, so just check it exists)
    let initial_page = &pages[0];
    assert!(
        !initial_page.url().is_empty(),
        "Initial app mode page should have a URL"
    );

    context.close().await.unwrap();

    // Cleanup temp directory
    let _ = tokio::fs::remove_dir_all(&user_data_dir).await;
}

#[tokio::test]
async fn test_context_browser_returns_browser_for_regular_context() {
    let (_pw, browser, context) = crate::common::setup_context().await;

    // Regular context should return the browser
    let context_browser = context.browser();
    assert!(
        context_browser.is_some(),
        "Regular context should return Some(Browser)"
    );

    // Verify it's the same browser by checking name and version
    let ctx_browser = context_browser.unwrap();
    assert_eq!(ctx_browser.name(), browser.name());
    assert_eq!(ctx_browser.version(), browser.version());

    context.close().await.unwrap();
    browser.close().await.unwrap();
}

#[tokio::test]
async fn test_context_browser_returns_browser_for_persistent_context() {
    let playwright = Playwright::launch().await.unwrap();
    let chromium = playwright.chromium();

    // Create temp user data dir
    let user_data_dir = env::temp_dir()
        .join(format!(
            "pw-rust-test-persist-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ))
        .to_string_lossy()
        .to_string();

    // Launch persistent context
    let options = playwright_rs::protocol::BrowserContextOptions::builder()
        .headless(true)
        .build();

    let context = chromium
        .launch_persistent_context_with_options(&user_data_dir, options)
        .await
        .unwrap();

    // Persistent context should ALSO return the browser (Playwright behavior)
    // Only Android/Electron contexts return None
    let context_browser = context.browser();
    assert!(
        context_browser.is_some(),
        "Persistent context should return Some(Browser)"
    );

    // Verify it's a valid browser
    let browser = context_browser.unwrap();
    assert_eq!(browser.name(), "chromium");
    assert!(!browser.version().is_empty());

    context.close().await.unwrap();

    // Cleanup temp directory
    let _ = tokio::fs::remove_dir_all(&user_data_dir).await;
}

#[tokio::test]
#[ignore]
async fn test_context_pages_cross_browser() {
    let playwright = Playwright::launch().await.unwrap();

    // Test on all three browsers
    let browser_types = vec![
        ("chromium", playwright.chromium()),
        ("firefox", playwright.firefox()),
        ("webkit", playwright.webkit()),
    ];

    for (name, browser_type) in browser_types {
        println!("Testing context.pages() on {}", name);

        let browser = browser_type.launch().await.unwrap();
        let context = browser.new_context().await.unwrap();

        // Empty initially
        let pages = context.pages();
        assert_eq!(pages.len(), 0, "New {} context should have no pages", name);

        // Create page
        let _page = context.new_page().await.unwrap();

        // Should include page
        let pages = context.pages();
        assert_eq!(pages.len(), 1, "{} context should have 1 page", name);

        context.close().await.unwrap();
        browser.close().await.unwrap();
    }
}

#[tokio::test]
async fn test_browser_context_is_closed() {
    let (_pw, browser, context) = crate::common::setup_context().await;
    assert!(
        !context.is_closed(),
        "Newly created context should not be closed"
    );
    context.close().await.expect("Failed to close context");
    assert!(
        context.is_closed(),
        "Context should be closed after close()"
    );
    browser.close().await.expect("Failed to close browser");
}

#[tokio::test]
#[ignore]
async fn test_context_browser_cross_browser() {
    let playwright = Playwright::launch().await.unwrap();

    // Test on all three browsers
    let browser_types = vec![
        ("chromium", playwright.chromium()),
        ("firefox", playwright.firefox()),
        ("webkit", playwright.webkit()),
    ];

    for (name, browser_type) in browser_types {
        println!("Testing context.browser() on {}", name);

        let browser = browser_type.launch().await.unwrap();
        let context = browser.new_context().await.unwrap();

        // Should return browser
        let context_browser = context.browser();
        assert!(
            context_browser.is_some(),
            "{} context should return Some(Browser)",
            name
        );

        let ctx_browser = context_browser.unwrap();
        assert_eq!(ctx_browser.name(), browser.name());
        assert_eq!(ctx_browser.version(), browser.version());

        context.close().await.unwrap();
        browser.close().await.unwrap();
    }
}