browser-test 0.2.1

Small helpers for async browser-driven integration tests.
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
//! Integration tests for public browser runner behavior.

use std::{
    borrow::Cow,
    num::NonZeroUsize,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
};

use assertr::prelude::*;
use browser_test::thirtyfour::{ChromiumLikeCapabilities, WebDriver};
use browser_test::{
    BrowserTest, BrowserTestError, BrowserTestFailurePolicy, BrowserTestParallelism,
    BrowserTestRunner, BrowserTests, BrowserTimeouts, ElementQueryWaitConfig, async_trait,
};
use rootcause::Report;
use rootcause::prelude::ResultExt;
use serial_test::serial;

type RunnerResult = Result<(), Report<BrowserTestError>>;

const FIXTURE_PAGE_URL: &str =
    "data:text/html,%3C!doctype%20html%3E%3Ctitle%3Ebrowser-test%20fixture%3C/title%3E";
const FIXTURE_PAGE_TITLE: &str = "browser-test fixture";

#[derive(Debug)]
struct IntegrationContext {
    page_url: &'static str,
    expected_title: &'static str,
}

impl Default for IntegrationContext {
    fn default() -> Self {
        Self {
            page_url: FIXTURE_PAGE_URL,
            expected_title: FIXTURE_PAGE_TITLE,
        }
    }
}

#[derive(Debug, thiserror::Error)]
enum IntegrationTestError {
    #[error("failed to open test page")]
    OpenTestPage,

    #[error("failed to read browser title")]
    ReadTitle,

    #[error("unexpected browser title: expected {expected:?}, got {actual:?}")]
    UnexpectedTitle {
        expected: &'static str,
        actual: String,
    },

    #[error("intentional browser test failure")]
    IntentionalFailure,
}

struct PageTitleTest {
    name: String,
    started: Option<Arc<AtomicUsize>>,
}

#[async_trait]
impl BrowserTest<IntegrationContext, IntegrationTestError> for PageTitleTest {
    fn name(&self) -> Cow<'_, str> {
        Cow::Borrowed(self.name.as_str())
    }

    async fn run(
        &self,
        driver: &WebDriver,
        context: &IntegrationContext,
    ) -> Result<(), Report<IntegrationTestError>> {
        if let Some(started) = &self.started {
            started.fetch_add(1, Ordering::SeqCst);
        }

        driver
            .goto(context.page_url)
            .await
            .context(IntegrationTestError::OpenTestPage)?;
        let title = driver
            .title()
            .await
            .context(IntegrationTestError::ReadTitle)?;

        if title != context.expected_title {
            return Err(Report::new(IntegrationTestError::UnexpectedTitle {
                expected: context.expected_title,
                actual: title,
            }));
        }

        Ok(())
    }
}

struct IntentionalFailureTest {
    started: Option<Arc<AtomicUsize>>,
}

#[async_trait]
impl BrowserTest<IntegrationContext, IntegrationTestError> for IntentionalFailureTest {
    fn name(&self) -> Cow<'_, str> {
        Cow::Borrowed("intentional failure")
    }

    async fn run(
        &self,
        _driver: &WebDriver,
        _context: &IntegrationContext,
    ) -> Result<(), Report<IntegrationTestError>> {
        if let Some(started) = &self.started {
            started.fetch_add(1, Ordering::SeqCst);
        }

        Err(Report::new(IntegrationTestError::IntentionalFailure))
    }
}

struct PanicTest {
    started: Option<Arc<AtomicUsize>>,
}

#[async_trait]
impl BrowserTest<IntegrationContext, IntegrationTestError> for PanicTest {
    fn name(&self) -> Cow<'_, str> {
        Cow::Borrowed("intentional panic")
    }

    async fn run(
        &self,
        _driver: &WebDriver,
        _context: &IntegrationContext,
    ) -> Result<(), Report<IntegrationTestError>> {
        if let Some(started) = &self.started {
            started.fetch_add(1, Ordering::SeqCst);
        }

        panic!("intentional browser test panic");
    }
}

#[derive(Clone, Copy)]
enum MetadataPanicHook {
    Name,
    WebdriverTimeouts,
    ElementQueryWait,
}

struct MetadataPanicTest {
    panic_in: MetadataPanicHook,
}

#[async_trait]
impl BrowserTest<IntegrationContext, IntegrationTestError> for MetadataPanicTest {
    fn name(&self) -> Cow<'_, str> {
        if matches!(self.panic_in, MetadataPanicHook::Name) {
            panic!("name hook failed");
        }

        Cow::Borrowed("metadata panic")
    }

    fn timeouts(&self) -> Option<BrowserTimeouts> {
        if matches!(self.panic_in, MetadataPanicHook::WebdriverTimeouts) {
            panic!("webdriver timeout hook failed");
        }

        None
    }

    fn element_query_wait(&self) -> Option<ElementQueryWaitConfig> {
        if matches!(self.panic_in, MetadataPanicHook::ElementQueryWait) {
            panic!("element query wait hook failed");
        }

        None
    }

    async fn run(
        &self,
        _driver: &WebDriver,
        _context: &IntegrationContext,
    ) -> Result<(), Report<IntegrationTestError>> {
        Ok(())
    }
}

/// Build a `BrowserTestRunner` pre-configured with the Chrome flags our CI environment needs. Both
/// flags are harmless when set locally, so we apply them unconditionally instead of branching on
/// `CI`.
fn runner() -> BrowserTestRunner {
    BrowserTestRunner::new()
        .with_chrome_capabilities(|caps| {
            // `--no-sandbox` disables Chrome's child-process sandboxing. User-mode tarball
            // extraction can't set the setuid-root bit on `chrome_sandbox` (the privileged helper
            // Chrome execs to install the sandbox), and CI kernels often also restrict
            // unprivileged user namespaces. Without either layer, Chrome exits before chromedriver
            // opens a session.
            caps.add_arg("--no-sandbox")?;

            // `--disable-dev-shm-usage` makes Chrome place its IPC shared-memory segments under
            // `/tmp` instead of `/dev/shm`. CI runners typically expose `/dev/shm` tiny tmpfs,
            // which Chrome can exhaust during session startup.
            caps.add_arg("--disable-dev-shm-usage")?;
            Ok(())
        })
        .with_test_parallelism(BrowserTestParallelism::Sequential)
        .with_failure_policy(BrowserTestFailurePolicy::RunAll)
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn default_sequential_fail_fast_runs_page_title_test() -> RunnerResult {
    runner()
        .run(
            &IntegrationContext::default(),
            BrowserTests::new().with(page_title_test("page title")),
        )
        .await
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn explicit_sequential_runs_page_title_test() -> RunnerResult {
    runner()
        .with_test_parallelism(BrowserTestParallelism::Sequential)
        .run(
            &IntegrationContext::default(),
            BrowserTests::new().with(page_title_test("page title")),
        )
        .await
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn bounded_parallel_runs_page_title_tests() -> RunnerResult {
    runner()
        .with_test_parallelism(BrowserTestParallelism::Parallel(
            NonZeroUsize::new(2).expect("literal parallelism should be non-zero"),
        ))
        .run(
            &IntegrationContext::default(),
            BrowserTests::new()
                .with(page_title_test(String::from("page title one")))
                .with(page_title_test("page title two")),
        )
        .await
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn run_all_runs_successful_page_title_tests() -> RunnerResult {
    runner()
        .with_failure_policy(BrowserTestFailurePolicy::RunAll)
        .run(
            &IntegrationContext::default(),
            BrowserTests::new()
                .with(page_title_test("page title one"))
                .with(page_title_test("page title two")),
        )
        .await
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn run_all_reports_intentional_failure_and_runs_page_title_test() {
    let err = runner()
        .with_failure_policy(BrowserTestFailurePolicy::RunAll)
        .run(
            &IntegrationContext::default(),
            BrowserTests::new()
                .with(IntentionalFailureTest { started: None })
                .with(page_title_test("page title")),
        )
        .await
        .expect_err("run-all should report the intentional failure");

    assert_that!(err.to_string())
        .contains(BrowserTestError::RunTests { failed_tests: 1 }.to_string());
    assert_that!(err.children().len()).is_equal_to(1);
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn run_all_reports_metadata_hook_panics_and_runs_remaining_page_title_test() {
    let started = Arc::new(AtomicUsize::new(0));
    let err = runner()
        .with_failure_policy(BrowserTestFailurePolicy::RunAll)
        .run(
            &IntegrationContext::default(),
            BrowserTests::new()
                .with(MetadataPanicTest {
                    panic_in: MetadataPanicHook::Name,
                })
                .with(MetadataPanicTest {
                    panic_in: MetadataPanicHook::WebdriverTimeouts,
                })
                .with(MetadataPanicTest {
                    panic_in: MetadataPanicHook::ElementQueryWait,
                })
                .with(page_title_test_with_counter(
                    "page title",
                    Arc::clone(&started),
                )),
        )
        .await
        .expect_err("run-all should report metadata hook panics");

    assert_that!(started.load(Ordering::SeqCst)).is_equal_to(1);
    assert_that!(err.to_string())
        .contains(BrowserTestError::RunTests { failed_tests: 3 }.to_string());
    assert_that!(err.children().len()).is_equal_to(3);
    assert_that!(format!("{err:?}")).contains("unnamed test at index 0");
    assert_that!(format!("{err:?}")).contains("webdriver timeout hook failed");
    assert_that!(format!("{err:?}")).contains("element query wait hook failed");
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn parallel_run_all_reports_panic_and_runs_remaining_page_title_tests() {
    let started = Arc::new(AtomicUsize::new(0));
    let err = runner()
        .with_test_parallelism(BrowserTestParallelism::Parallel(
            NonZeroUsize::new(2).expect("literal parallelism should be non-zero"),
        ))
        .with_failure_policy(BrowserTestFailurePolicy::RunAll)
        .run(
            &IntegrationContext::default(),
            BrowserTests::new()
                .with(PanicTest {
                    started: Some(Arc::clone(&started)),
                })
                .with(page_title_test_with_counter(
                    "page title one",
                    Arc::clone(&started),
                ))
                .with(page_title_test_with_counter(
                    "page title two",
                    Arc::clone(&started),
                )),
        )
        .await
        .expect_err("run-all should report the intentional panic");

    assert_that!(started.load(Ordering::SeqCst)).is_equal_to(3);
    assert_that!(err.to_string())
        .contains(BrowserTestError::RunTests { failed_tests: 1 }.to_string());
    assert_that!(err.children().len()).is_equal_to(1);
}

#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn parallel_fail_fast_waits_for_running_page_title_test_without_starting_more() {
    let started = Arc::new(AtomicUsize::new(0));
    let err = runner()
        .with_test_parallelism(BrowserTestParallelism::Parallel(
            NonZeroUsize::new(2).expect("literal parallelism should be non-zero"),
        ))
        .with_failure_policy(BrowserTestFailurePolicy::FailFast)
        .run(
            &IntegrationContext::default(),
            BrowserTests::new()
                .with(IntentionalFailureTest {
                    started: Some(Arc::clone(&started)),
                })
                .with(page_title_test_with_counter(
                    "page title one",
                    Arc::clone(&started),
                ))
                .with(page_title_test_with_counter(
                    "page title two",
                    Arc::clone(&started),
                )),
        )
        .await
        .expect_err("fail-fast should report the intentional failure");

    assert_that!(err.to_string())
        .contains(BrowserTestError::RunTests { failed_tests: 1 }.to_string());
    assert_that!(err.children().len()).is_equal_to(1);
    assert_that!(started.load(Ordering::SeqCst)).is_equal_to(2);
}

fn page_title_test(name: impl Into<String>) -> PageTitleTest {
    PageTitleTest {
        name: name.into(),
        started: None,
    }
}

fn page_title_test_with_counter(
    name: impl Into<String>,
    started: Arc<AtomicUsize>,
) -> PageTitleTest {
    PageTitleTest {
        name: name.into(),
        started: Some(started),
    }
}