zendriver 0.2.21

Async-first, undetectable browser automation via the Chrome DevTools Protocol
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
//! Phase 4 end-to-end tests against real Chrome + wiremock.
//!
//! Each test serves a tiny HTML fixture via `wiremock`, launches a headless
//! Chrome via `Browser::builder()`, drives the new P4 surface (multi-tab,
//! cookies, storage, frames, nav history, network idle, traversal refresh),
//! and asserts on observable behavior via CDP or DOM state.
//!
//! Gated behind the `integration-tests` feature so CI can skip on
//! Chrome-less runners; CI exercises these on the integration job.

#![cfg(feature = "integration-tests")]
#![allow(clippy::panic, clippy::unwrap_used)]

use std::time::Duration;

use serial_test::serial;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
use zendriver::{Browser, Cookie, SameSite};

/// Spin up a mock HTTP server that returns `html` at `/`. Shared between
/// every test below — keeps fixtures inline + isolated.
async fn fixture_with_html(html: &str) -> MockServer {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(
            ResponseTemplate::new(200).set_body_raw(html.as_bytes().to_vec(), "text/html"),
        )
        .mount(&mock)
        .await;
    mock
}

#[tokio::test]
#[serial]
async fn new_tab_opens_second_tab() {
    // Launch starts with exactly one tab in the registry (the main tab).
    // `Browser::new_tab` issues `Target.createTarget` and waits for the
    // `TabRegistrar` observer to register the new session, so by the time
    // it resolves the registry must have grown to 2.
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    assert_eq!(browser.tab_count().await, 1);

    let _tab2 = browser.new_tab().await.unwrap();
    assert_eq!(
        browser.tabs().await.len(),
        2,
        "new_tab should add a second entry to the tab registry"
    );

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

#[tokio::test]
#[serial]
async fn tab_close_removes_from_registry() {
    // After opening a second tab + closing it, the registry should drop
    // back to the single main tab. The drop happens via the
    // `Target.detachedFromTarget` event the `TabRegistrar` observer
    // listens for, so there is a small async window between `Tab::close`
    // returning and the registry actually shrinking — poll briefly.
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab2 = browser.new_tab().await.unwrap();
    assert_eq!(browser.tab_count().await, 2);

    tab2.close().await.unwrap();

    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    loop {
        if browser.tab_count().await == 1 {
            break;
        }
        if std::time::Instant::now() >= deadline {
            panic!("tab.close did not remove tab from registry within 5s");
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

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

#[tokio::test]
#[serial]
async fn cookies_set_and_all_roundtrip() {
    // Insert two cookies via the browser-scoped jar, then read them back
    // via `all()`. Order from Chrome is unspecified; assert membership by
    // name rather than position.
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let jar = browser.cookies();

    jar.set(Cookie {
        name: "alpha".into(),
        value: "1".into(),
        domain: "example.test".into(),
        path: "/".into(),
        expires: None,
        http_only: false,
        secure: false,
        same_site: Some(SameSite::Lax),
        url: None,
        ..Default::default()
    })
    .await
    .unwrap();
    jar.set(Cookie {
        name: "beta".into(),
        value: "2".into(),
        domain: "example.test".into(),
        path: "/".into(),
        expires: None,
        http_only: true,
        secure: false,
        same_site: None,
        url: None,
        ..Default::default()
    })
    .await
    .unwrap();

    let all = jar.all().await.unwrap();
    let names: std::collections::HashSet<_> = all.iter().map(|c| c.name.clone()).collect();
    assert!(names.contains("alpha"), "alpha cookie missing from all()");
    assert!(names.contains("beta"), "beta cookie missing from all()");

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

#[tokio::test]
#[serial]
async fn cookies_save_and_load_roundtrip() {
    // Save the browser cookie store to a tempfile, then clear + reload it
    // and assert the same cookies come back. The two-cookie set covers
    // both the SameSite::Lax and `same_site = None` paths through the
    // CDP camelCase boundary.
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let jar = browser.cookies();

    jar.set(Cookie {
        name: "saved_a".into(),
        value: "v1".into(),
        domain: "example.test".into(),
        path: "/".into(),
        expires: None,
        http_only: false,
        secure: false,
        same_site: Some(SameSite::Lax),
        url: None,
        ..Default::default()
    })
    .await
    .unwrap();
    jar.set(Cookie {
        name: "saved_b".into(),
        value: "v2".into(),
        domain: "example.test".into(),
        path: "/api".into(),
        expires: None,
        http_only: true,
        secure: false,
        same_site: None,
        url: None,
        ..Default::default()
    })
    .await
    .unwrap();

    let tmp = tempfile::NamedTempFile::new().unwrap();
    let path = tmp.path().to_path_buf();
    jar.save_to_file(&path).await.unwrap();

    // Clear the jar and confirm the wipe took.
    jar.clear().await.unwrap();
    let after_clear = jar.all().await.unwrap();
    assert!(
        !after_clear.iter().any(|c| c.name == "saved_a"),
        "clear() should have removed saved_a"
    );

    // Hydrate from the tempfile and confirm both cookies are back.
    jar.load_from_file(&path).await.unwrap();
    let reloaded = jar.all().await.unwrap();
    let names: std::collections::HashSet<_> = reloaded.iter().map(|c| c.name.clone()).collect();
    assert!(
        names.contains("saved_a"),
        "saved_a missing after load_from_file"
    );
    assert!(
        names.contains("saved_b"),
        "saved_b missing after load_from_file"
    );

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

#[tokio::test]
#[serial]
async fn local_storage_set_get_clear() {
    // Set two keys, read them back, then clear + assert empty. Storage
    // is per-origin so a real navigation is required before any op
    // (DOMStorage rejects requests on `about:blank` because it has no
    // tangible origin).
    let mock =
        fixture_with_html(r#"<!doctype html><html><body><div id="d">x</div></body></html>"#).await;
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab = browser.main_tab();
    tab.goto(&mock.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();

    let storage = tab.local_storage();
    storage.set("theme", "dark").await.unwrap();
    storage.set("lang", "en").await.unwrap();

    let theme = storage.get("theme").await.unwrap();
    assert_eq!(theme.as_deref(), Some("dark"));
    let lang = storage.get("lang").await.unwrap();
    assert_eq!(lang.as_deref(), Some("en"));

    storage.clear().await.unwrap();
    let all = storage.get_all().await.unwrap();
    assert!(all.is_empty(), "storage should be empty after clear()");

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

#[tokio::test]
#[serial]
async fn back_forward_navigation_history() {
    // Goto A, goto B, back should land on A, forward should land on B.
    // Two distinct fixtures via two MockServer instances so the URLs
    // differ unambiguously.
    let mock_a =
        fixture_with_html(r#"<!doctype html><html><body><div id="a">A</div></body></html>"#).await;
    let mock_b =
        fixture_with_html(r#"<!doctype html><html><body><div id="b">B</div></body></html>"#).await;
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab = browser.main_tab();
    tab.goto(&mock_a.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();
    tab.goto(&mock_b.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();

    tab.back().await.unwrap();
    tab.wait_for_load().await.unwrap();
    let url_after_back = tab.url().await.unwrap().to_string();
    assert!(
        url_after_back.starts_with(&mock_a.uri()),
        "back should land on A, got: {url_after_back}"
    );

    tab.forward().await.unwrap();
    tab.wait_for_load().await.unwrap();
    let url_after_fwd = tab.url().await.unwrap().to_string();
    assert!(
        url_after_fwd.starts_with(&mock_b.uri()),
        "forward should land on B, got: {url_after_fwd}"
    );

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

#[tokio::test]
#[serial]
async fn reload_dispatches_page_reload() {
    // Reload should re-execute the page; assert by writing a sentinel
    // into the main world, reloading, and confirming the sentinel is gone
    // because the JS environment was thrown away with the document.
    let mock =
        fixture_with_html(r#"<!doctype html><html><body><div id="d">x</div></body></html>"#).await;
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab = browser.main_tab();
    tab.goto(&mock.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();

    tab.evaluate_main::<serde_json::Value>("window.sentinel = 'pre-reload'; null")
        .await
        .unwrap();
    let before: String = tab.evaluate_main("window.sentinel").await.unwrap();
    assert_eq!(before, "pre-reload");

    tab.reload().await.unwrap();
    tab.wait_for_load().await.unwrap();

    // After a real reload the JS realm is fresh; window.sentinel must
    // be `undefined`, which our null-coalescing eval surfaces as None.
    let after: Option<String> = tab
        .evaluate_main("typeof window.sentinel === 'undefined' ? null : window.sentinel")
        .await
        .unwrap();
    assert_eq!(after, None, "reload should have cleared window.sentinel");

    // Sanity-check the DOM is still present (so we didn't just navigate
    // away to a blank page).
    let id: Option<String> = tab
        .find()
        .css("#d")
        .one()
        .await
        .unwrap()
        .attr("id")
        .await
        .unwrap();
    assert_eq!(id.as_deref(), Some("d"));

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

#[tokio::test]
#[serial]
async fn wait_for_idle_on_spa_with_delayed_xhr() {
    // Regression coverage: `wait_for_idle` must block on a request that is
    // still in flight when it is called, and only resolve once that request
    // completes and the quiet window elapses.
    //
    // Design that makes this deterministic (no dependence on host load):
    //   * The page fires `fetch("/data")` immediately on parse.
    //   * The server holds that response open for `DATA_DELAY` before replying.
    //   * A `fetch` is NOT a document subresource, so the `load` event — and
    //     therefore `wait_for_load` — fires while the request is still pending.
    // So at the instant `wait_for_idle` starts, the `/data` request is
    // guaranteed in flight; idle detection MUST observe it and wait. (The
    // earlier version delayed the XHR with a client-side `setTimeout`, whose
    // firing time relative to the measurement start drifted under CI load, and
    // — separately — relied on the browser reaching a *global* network-idle
    // state that Chrome's New Tab Page startup requests could prevent. The
    // initial tab now launches on `about:blank`, so the only traffic is this
    // fixture's own.)
    //
    // Page and data endpoint share one origin so the fetch is same-origin (a
    // cross-origin fetch would be CORS-blocked and never set `window.x`).
    const DATA_DELAY: Duration = Duration::from_millis(1500);
    const QUIET_WINDOW: Duration = Duration::from_millis(500);

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/data"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string("ok")
                .set_delay(DATA_DELAY),
        )
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(
            ResponseTemplate::new(200).set_body_raw(
                // `<link rel="icon" href="data:,">` suppresses the implicit
                // /favicon.ico request, leaving the document + the XHR as the
                // only network traffic the tab generates.
                r#"<!doctype html><html><head><link rel="icon" href="data:,"></head><body>
          <script>
            fetch("/data").then(r => r.text()).then(t => { window.x = t; });
          </script>
        </body></html>"#
                    .as_bytes()
                    .to_vec(),
                "text/html",
            ),
        )
        .mount(&mock)
        .await;

    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab = browser.main_tab();
    tab.goto(&mock.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();

    let start = std::time::Instant::now();
    // Outer timeout is a generous multiple of the ~2s happy path (DATA_DELAY +
    // QUIET_WINDOW) so a genuinely-stuck request fails fast instead of hanging
    // the suite for 30s, while normal CI jitter never trips it.
    tab.wait_for_idle_with(Duration::from_secs(10), QUIET_WINDOW)
        .await
        .unwrap();
    let elapsed = start.elapsed();

    // Primary, *causal* assertion: `window.x` is only set when the delayed
    // `/data` response arrives at +DATA_DELAY. Had `wait_for_idle` ignored the
    // in-flight request, it would have resolved at the first quiet window
    // (~QUIET_WINDOW) with `window.x` still empty. Independent of wall-clock
    // timing, so it cannot flake.
    let x: String = tab.evaluate_main("window.x || ''").await.unwrap();
    assert_eq!(x, "ok", "XHR result must be present once idle resolves");

    // Secondary: idle cannot resolve until the response is delivered, so the
    // elapsed time must clear the server delay. The floor sits far above the
    // ~QUIET_WINDOW an oblivious wait would take and well below the ~2s
    // expected, so scheduler jitter never trips it either way.
    assert!(
        elapsed >= Duration::from_millis(1200),
        "wait_for_idle returned too early ({elapsed:?}); the in-flight XHR \
         (held {DATA_DELAY:?} server-side) should have kept the tab non-idle"
    );

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

#[tokio::test]
#[serial]
async fn wait_for_idle_opts_resolves_despite_stuck_request() {
    // A request that never completes within the test (server holds it open far
    // longer than the wait) must NOT pin `wait_for_idle_opts` to its outer
    // timeout when `max_inflight_age` is set: once the request has been in
    // flight past that age it is ignored, so idle resolves on the quiet window.
    //
    // Single origin + suppressed favicon so the held `/hang` fetch is the only
    // thing keeping the tab busy.
    const HANG_DELAY: Duration = Duration::from_secs(5); // ≫ the ~0.6s we wait
    const MAX_AGE: Duration = Duration::from_millis(400);
    const QUIET_WINDOW: Duration = Duration::from_millis(200);

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/hang"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string("late")
                .set_delay(HANG_DELAY),
        )
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(
            ResponseTemplate::new(200).set_body_raw(
                r#"<!doctype html><html><head><link rel="icon" href="data:,"></head><body>
          <script>fetch("/hang");</script>
        </body></html>"#
                    .as_bytes()
                    .to_vec(),
                "text/html",
            ),
        )
        .mount(&mock)
        .await;

    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab = browser.main_tab();
    tab.goto(&mock.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();

    let start = std::time::Instant::now();
    tab.wait_for_idle_opts(zendriver::IdleOptions {
        timeout: Duration::from_secs(10),
        quiet_window: QUIET_WINDOW,
        max_inflight_age: Some(MAX_AGE),
    })
    .await
    .unwrap();
    let elapsed = start.elapsed();

    // Resolved by eviction, not by the request finishing (it can't — held 5s)
    // and not by the 10s outer timeout. So elapsed clears MAX_AGE + window but
    // stays far below HANG_DELAY.
    assert!(
        elapsed >= Duration::from_millis(500),
        "resolved too early ({elapsed:?}); eviction age + quiet window not enforced"
    );
    assert!(
        elapsed < Duration::from_secs(3),
        "resolved too late ({elapsed:?}); the stuck /hang request should have been \
         evicted at {MAX_AGE:?}, not awaited"
    );

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

#[tokio::test]
#[serial]
async fn frame_find_inside_iframe() {
    // Fixture page hosts an iframe with `srcdoc` content. After load the
    // tab's frame registry should contain the main frame + the iframe;
    // querying inside the child frame must locate its scoped element.
    //
    // `srcdoc` keeps the iframe same-origin so it routes through the
    // standard same-session frame path (not the OOPIF observer chain).
    let mock = fixture_with_html(
        r#"<!doctype html><html><body>
          <iframe id="f" srcdoc="<button id='b'>x</button>"></iframe>
        </body></html>"#,
    )
    .await;
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab = browser.main_tab();
    tab.goto(&mock.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();

    // The iframe registers via a `Page.frameAttached` event the lifecycle
    // subscriber consumes asynchronously — poll briefly until the
    // registry shows the second frame.
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    let child = loop {
        let frames = tab.frames().await.unwrap();
        if let Some(child) = frames.into_iter().find(|f| !f.is_main()) {
            break child;
        }
        if std::time::Instant::now() >= deadline {
            panic!("iframe never registered as a child frame within 5s");
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    };

    // The child frame's document holds the `<button id="b">`; querying
    // through the frame must locate it. The main tab's document does NOT
    // contain that button — confirms the query is frame-scoped.
    let btn = child.find().css("#b").one().await.unwrap();
    let id: Option<String> = btn.attr("id").await.unwrap();
    assert_eq!(id.as_deref(), Some("b"));

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

#[tokio::test]
#[serial]
async fn traversal_refresh_survives_reload() {
    // Find an element + its parent traversal, then `location.reload()`
    // and confirm the parent traversal still resolves — the chain
    // refresh re-runs the original selector against the fresh document.
    let mock = fixture_with_html(
        r#"<!doctype html><html><body>
          <div id="root"><span id="child">x</span></div>
        </body></html>"#,
    )
    .await;
    let browser = Browser::builder().headless(true).launch().await.unwrap();
    let tab = browser.main_tab();
    tab.goto(&mock.uri()).await.unwrap();
    tab.wait_for_load().await.unwrap();

    let child = tab.find().css("#child").one().await.unwrap();

    // Trigger a real reload, then wait for the new document so the
    // original element handles are stale.
    tab.evaluate_main::<serde_json::Value>("location.reload(); null")
        .await
        .ok(); // reload tears down the eval context — error is fine.
    tab.wait_for_load().await.unwrap();

    // `parent()` carries a `Traversal { Parent }` origin whose ancestor
    // is the `Query/TabMain { Css("#child"), nth=0 }` origin. After the
    // reload the cached backend/remote ids are stale; auto-refresh
    // re-runs `document.querySelectorAll("#child")` against the fresh
    // document and re-traverses `this.parentElement`.
    let parent = child.parent().await.unwrap().expect("#child has a parent");
    let parent_id: Option<String> = parent.attr("id").await.unwrap();
    assert_eq!(
        parent_id.as_deref(),
        Some("root"),
        "traversal parent should still resolve to #root after reload"
    );

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