thirtyfour 0.37.0

Thirtyfour is a Selenium / WebDriver library for Rust, for automated website UI testing. Tested on Chrome and Firefox, but any webdriver-capable browser should work.
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
use http::Method;
use serde_json::{Value, json};

use crate::IntoArcStr;
use crate::RequestData;
use crate::common::{
    capabilities::desiredcapabilities::make_w3c_caps,
    cookie::Cookie,
    keys::TypingData,
    print::PrintParameters,
    types::{ElementId, OptionRect, SessionId, TimeoutConfiguration, WindowHandle},
};
use std::fmt;
use std::fmt::Debug;
use std::sync::Arc;

/// The W3C element identifier key.
pub const MAGIC_ELEMENTID: &str = "element-6066-11e4-a52e-4f735466cecf";

/// Actions.
#[derive(Debug)]
pub struct Actions(Value);

impl From<Value> for Actions {
    fn from(value: Value) -> Self {
        Actions(value)
    }
}

/// Element Selector representation.
#[derive(Debug, Clone)]
pub struct Selector {
    /// Selector name.
    pub name: Arc<str>,
    /// Selector query.
    pub query: Arc<str>,
}

impl Selector {
    /// Create a new Selector.
    pub fn new(name: impl IntoArcStr, query: impl IntoArcStr) -> Self {
        Self {
            name: name.into(),
            query: query.into(),
        }
    }
}

/// Element Selector representation.
#[derive(Debug, Clone)]
pub enum BySelector {
    /// Select an element by id.
    Id(Arc<str>),
    /// Select an element by XPath.
    XPath(Arc<str>),
    /// Select an element by link text.
    LinkText(Arc<str>),
    /// Select an element by partial link text.
    PartialLinkText(Arc<str>),
    /// Select element by name.
    Name(Arc<str>),
    /// Select an element by tag.
    Tag(Arc<str>),
    /// Select an element by class.
    ClassName(Arc<str>),
    /// Select an element by CSS.
    Css(Arc<str>),
    /// Select an element by data-testid.
    Testid(Arc<str>),
}

/// Element Selector struct providing a convenient way to specify selectors.
///
/// # Scope when querying from a [`WebElement`]
///
/// When you call `find` / `find_all` / `query` on a [`WebElement`] (rather
/// than on a [`WebDriver`]), thirtyfour issues `Find Element From Element`
/// and the search is **scoped to the element's subtree** — except for
/// [`By::XPath`], see below.
///
/// All other variants (`Id`, `Name`, `Tag`, `ClassName`, `Css`, `Testid`,
/// `LinkText`, `PartialLinkText`) are forwarded as CSS selectors, which the
/// WebDriver spec runs against the element's descendants only.
///
/// # XPath gotcha
///
/// XPath `//foo` is **document-rooted**, even when called from a
/// [`WebElement`]. To search relative to the element you queried from, use
/// `.//foo`:
///
/// ```rust,no_run
/// # use thirtyfour::prelude::*;
/// # async fn _scope(parent: WebElement) -> WebDriverResult<()> {
/// // Wrong — searches the whole document, may match elements outside `parent`.
/// let _ = parent.find(By::XPath("//div[@class='child']")).await?;
/// // Right — searches only inside `parent`.
/// let _ = parent.find(By::XPath(".//div[@class='child']")).await?;
/// # Ok(()) }
/// ```
///
/// This is W3C WebDriver behaviour, not a thirtyfour quirk — it matches
/// every other Selenium-family client.
///
/// [`WebDriver`]: crate::WebDriver
/// [`WebElement`]: crate::WebElement
#[derive(Debug, Clone)]
pub struct By {
    selector: BySelector,
}

#[allow(non_snake_case)]
impl By {
    /// Select element by id.
    pub fn Id(id: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::Id(id.into()),
        }
    }

    /// Select element by link text.
    pub fn LinkText(text: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::LinkText(text.into()),
        }
    }

    /// Select element by partial link text.
    pub fn PartialLinkText(text: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::PartialLinkText(text.into()),
        }
    }

    /// Select element by CSS.
    pub fn Css(css: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::Css(css.into()),
        }
    }

    /// Select element by XPath.
    ///
    /// When called from a [`WebElement`], remember to prefix paths with
    /// `.//` to scope the search to the element's subtree — `//foo` is
    /// document-rooted regardless of which element you query from. See the
    /// [`By`] type-level docs for the full explanation.
    ///
    /// [`WebElement`]: crate::WebElement
    pub fn XPath(x: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::XPath(x.into()),
        }
    }

    /// Select element by name.
    pub fn Name(name: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::Css(format!(r#"[name="{}"]"#, name.into()).into()),
        }
    }

    /// Select element by tag.
    pub fn Tag(tag: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::Css(tag.into()),
        }
    }

    /// Select element by class.
    pub fn ClassName(name: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::Css(format!(".{}", name.into()).into()),
        }
    }

    /// Select element by testid.
    pub fn Testid(id: impl IntoArcStr) -> Self {
        Self {
            selector: BySelector::Css(format!("[data-testid=\"{}\"]", id.into()).into()),
        }
    }
}

impl fmt::Display for BySelector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BySelector::Id(id) => write!(f, "Id({})", id),
            BySelector::XPath(xpath) => write!(f, "XPath({})", xpath),
            BySelector::LinkText(text) => write!(f, "Link Text({})", text),
            BySelector::PartialLinkText(text) => write!(f, "Partial Link Text({})", text),
            BySelector::Name(name) => write!(f, "Name({})", name),
            BySelector::Tag(tag) => write!(f, "Tag({})", tag),
            BySelector::ClassName(cname) => write!(f, "Class({})", cname),
            BySelector::Css(css) => write!(f, "CSS({})", css),
            BySelector::Testid(id) => write!(f, "Testid({})", id),
        }
    }
}

impl fmt::Display for By {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.selector)
    }
}

impl From<BySelector> for Selector {
    fn from(by: BySelector) -> Self {
        match by {
            BySelector::Id(x) => Selector::new("css selector", format!("[id=\"{}\"]", x)),
            BySelector::XPath(x) => Selector::new("xpath", x),
            BySelector::LinkText(x) => Selector::new("link text", x),
            BySelector::PartialLinkText(x) => Selector::new("partial link text", x),
            BySelector::Name(x) => Selector::new("css selector", format!("[name=\"{}\"]", x)),
            BySelector::Tag(x) => Selector::new("css selector", x),
            BySelector::ClassName(x) => Selector::new("css selector", format!(".{}", x)),
            BySelector::Css(x) => Selector::new("css selector", x),
            BySelector::Testid(x) => {
                Selector::new("testid selector", format!("[data-testid=\"{}\"]", x))
            }
        }
    }
}

impl From<By> for Selector {
    fn from(by: By) -> Self {
        by.selector.into()
    }
}

/// Extension Command trait.
pub trait ExtensionCommand: Debug {
    /// Request Body
    fn parameters_json(&self) -> Option<Value>;

    /// HTTP method accepting by the webdriver
    fn method(&self) -> Method;

    /// Endpoint URL without `session/{sessionId}` prefix
    ///
    /// Example:- `/moz/addon/install`
    fn endpoint(&self) -> Arc<str>;
}

/// All the standard WebDriver commands.
#[allow(missing_docs)]
#[derive(Debug)]
pub enum Command {
    NewSession(Value),
    DeleteSession,
    Status,
    GetTimeouts,
    SetTimeouts(TimeoutConfiguration),
    NavigateTo(Arc<str>),
    GetCurrentUrl,
    Back,
    Forward,
    Refresh,
    GetTitle,
    GetWindowHandle,
    CloseWindow,
    SwitchToWindow(WindowHandle),
    GetWindowHandles,
    NewWindow,
    NewTab,
    SwitchToFrameDefault,
    SwitchToFrameNumber(u16),
    SwitchToFrameElement(ElementId),
    SwitchToParentFrame,
    GetWindowRect,
    SetWindowRect(OptionRect),
    MaximizeWindow,
    MinimizeWindow,
    FullscreenWindow,
    GetActiveElement,
    FindElement(Selector),
    FindElements(Selector),
    FindElementFromElement(ElementId, Selector),
    FindElementsFromElement(ElementId, Selector),
    IsElementSelected(ElementId),
    IsElementDisplayed(ElementId),
    GetElementAttribute(ElementId, Arc<str>),
    GetElementProperty(ElementId, Arc<str>),
    GetElementCssValue(ElementId, Arc<str>),
    GetElementText(ElementId),
    GetElementTagName(ElementId),
    GetElementRect(ElementId),
    IsElementEnabled(ElementId),
    ElementClick(ElementId),
    ElementClear(ElementId),
    ElementSendKeys(ElementId, TypingData),
    GetPageSource,
    ExecuteScript(Arc<str>, Arc<[Value]>),
    ExecuteAsyncScript(Arc<str>, Arc<[Value]>),
    GetAllCookies,
    GetNamedCookie(Arc<str>),
    AddCookie(Cookie),
    DeleteCookie(Arc<str>),
    DeleteAllCookies,
    PerformActions(Actions),
    ReleaseActions,
    DismissAlert,
    AcceptAlert,
    GetAlertText,
    SendAlertText(TypingData),
    PrintPage(PrintParameters),
    TakeScreenshot,
    TakeElementScreenshot(ElementId),
    /// Legacy Selenium endpoint: `GET /session/{id}/log/types`. Not part of
    /// W3C WebDriver, but still implemented by `chromedriver`. Returns a
    /// list of supported log type identifiers (e.g. `"browser"`,
    /// `"driver"`).
    GetLogTypes,
    /// Legacy Selenium endpoint: `POST /session/{id}/log` with a
    /// `{ "type": "<log_type>" }` body. Drains the named log buffer and
    /// returns its entries. Not part of W3C WebDriver, but still
    /// implemented by `chromedriver`. `geckodriver` does not support
    /// either endpoint.
    GetLog(Arc<str>),
    ExtensionCommand(Box<dyn ExtensionCommand + Send + Sync>),
}

/// Trait for formatting a WebDriver command into a `RequestData` struct.
pub trait FormatRequestData: Debug {
    /// Format the command into a `RequestData` struct.
    fn format_request(&self, session_id: &SessionId) -> RequestData;
}

impl FormatRequestData for Command {
    fn format_request(&self, session_id: &SessionId) -> RequestData {
        match self {
            Command::NewSession(caps) => {
                let w3c_caps = make_w3c_caps(caps);
                RequestData::new(Method::POST, "session").add_body(json!({
                    "capabilities": w3c_caps,
                    "desiredCapabilities": caps
                }))
            }
            Command::DeleteSession => {
                RequestData::new(Method::DELETE, format!("session/{}", session_id))
            }
            Command::Status => RequestData::new(Method::GET, "/status"),
            Command::GetTimeouts => {
                RequestData::new(Method::GET, format!("session/{}/timeouts", session_id))
            }
            Command::SetTimeouts(timeout_configuration) => {
                RequestData::new(Method::POST, format!("session/{}/timeouts", session_id))
                    .add_body(json!(timeout_configuration))
            }
            Command::NavigateTo(url) => {
                RequestData::new(Method::POST, format!("session/{}/url", session_id))
                    .add_body(json!({ "url": url }))
            }
            Command::GetCurrentUrl => {
                RequestData::new(Method::GET, format!("session/{}/url", session_id))
            }
            Command::Back => RequestData::new(Method::POST, format!("session/{}/back", session_id))
                .add_body(json!({})),
            Command::Forward => {
                RequestData::new(Method::POST, format!("session/{}/forward", session_id))
                    .add_body(json!({}))
            }
            Command::Refresh => {
                RequestData::new(Method::POST, format!("session/{}/refresh", session_id))
                    .add_body(json!({}))
            }
            Command::GetTitle => {
                RequestData::new(Method::GET, format!("session/{}/title", session_id))
            }
            Command::GetWindowHandle => {
                RequestData::new(Method::GET, format!("session/{}/window", session_id))
            }
            Command::CloseWindow => {
                RequestData::new(Method::DELETE, format!("session/{}/window", session_id))
            }
            Command::SwitchToWindow(window_handle) => {
                RequestData::new(Method::POST, format!("session/{}/window", session_id))
                    .add_body(json!({ "handle": window_handle.to_string() }))
            }
            Command::GetWindowHandles => {
                RequestData::new(Method::GET, format!("session/{}/window/handles", session_id))
            }
            Command::NewWindow => {
                RequestData::new(Method::POST, format!("session/{}/window/new", session_id))
                    .add_body(json!({"type": "window"}))
            }
            Command::NewTab => {
                RequestData::new(Method::POST, format!("session/{}/window/new", session_id))
                    .add_body(json!({"type": "tab"}))
            }
            Command::SwitchToFrameDefault => {
                RequestData::new(Method::POST, format!("session/{}/frame", session_id))
                    .add_body(json!({ "id": serde_json::Value::Null }))
            }
            Command::SwitchToFrameNumber(frame_number) => {
                RequestData::new(Method::POST, format!("session/{}/frame", session_id))
                    .add_body(json!({ "id": frame_number }))
            }
            Command::SwitchToFrameElement(element_id) => {
                RequestData::new(Method::POST, format!("session/{}/frame", session_id)).add_body(
                    json!({"id": {
                        "ELEMENT": element_id.to_string(),
                        MAGIC_ELEMENTID: element_id.to_string()
                    }}),
                )
            }
            Command::SwitchToParentFrame => {
                RequestData::new(Method::POST, format!("session/{}/frame/parent", session_id))
                    .add_body(json!({}))
            }
            Command::GetWindowRect => {
                RequestData::new(Method::GET, format!("session/{}/window/rect", session_id))
            }
            Command::SetWindowRect(option_rect) => {
                RequestData::new(Method::POST, format!("session/{}/window/rect", session_id))
                    .add_body(json!(option_rect))
            }
            Command::MaximizeWindow => {
                RequestData::new(Method::POST, format!("session/{}/window/maximize", session_id))
                    .add_body(json!({}))
            }
            Command::MinimizeWindow => {
                RequestData::new(Method::POST, format!("session/{}/window/minimize", session_id))
                    .add_body(json!({}))
            }
            Command::FullscreenWindow => {
                RequestData::new(Method::POST, format!("session/{}/window/fullscreen", session_id))
                    .add_body(json!({}))
            }
            Command::GetActiveElement => {
                RequestData::new(Method::GET, format!("session/{}/element/active", session_id))
            }
            Command::FindElement(selector) => {
                RequestData::new(Method::POST, format!("session/{}/element", session_id))
                    .add_body(json!({"using": selector.name, "value": selector.query}))
            }
            Command::FindElements(selector) => {
                RequestData::new(Method::POST, format!("session/{}/elements", session_id))
                    .add_body(json!({"using": selector.name, "value": selector.query}))
            }
            Command::FindElementFromElement(element_id, selector) => RequestData::new(
                Method::POST,
                format!("session/{}/element/{}/element", session_id, element_id),
            )
            .add_body(json!({"using": selector.name, "value": selector.query})),
            Command::FindElementsFromElement(element_id, selector) => RequestData::new(
                Method::POST,
                format!("session/{}/element/{}/elements", session_id, element_id),
            )
            .add_body(json!({"using": selector.name, "value": selector.query})),
            Command::IsElementSelected(element_id) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/selected", session_id, element_id),
            ),
            Command::IsElementDisplayed(element_id) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/displayed", session_id, element_id),
            ),
            Command::GetElementAttribute(element_id, attribute_name) => RequestData::new(
                Method::GET,
                format!(
                    "session/{}/element/{}/attribute/{}",
                    session_id, element_id, attribute_name
                ),
            ),
            Command::GetElementProperty(element_id, property_name) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/property/{}", session_id, element_id, property_name),
            ),
            Command::GetElementCssValue(element_id, property_name) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/css/{}", session_id, element_id, property_name),
            ),
            Command::GetElementText(element_id) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/text", session_id, element_id),
            ),
            Command::GetElementTagName(element_id) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/name", session_id, element_id),
            ),
            Command::GetElementRect(element_id) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/rect", session_id, element_id),
            ),
            Command::IsElementEnabled(element_id) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/enabled", session_id, element_id),
            ),
            Command::ElementClick(element_id) => RequestData::new(
                Method::POST,
                format!("session/{}/element/{}/click", session_id, element_id),
            )
            .add_body(json!({})),
            Command::ElementClear(element_id) => RequestData::new(
                Method::POST,
                format!("session/{}/element/{}/clear", session_id, element_id),
            )
            .add_body(json!({})),
            Command::ElementSendKeys(element_id, typing_data) => RequestData::new(
                Method::POST,
                format!("session/{}/element/{}/value", session_id, element_id),
            )
            .add_body(json!({"text": typing_data.to_string(), "value": typing_data.as_vec() })),
            Command::GetPageSource => {
                RequestData::new(Method::GET, format!("session/{}/source", session_id))
            }
            Command::ExecuteScript(script, args) => {
                RequestData::new(Method::POST, format!("session/{}/execute/sync", session_id))
                    .add_body(json!({"script": script, "args": args}))
            }
            Command::ExecuteAsyncScript(script, args) => {
                RequestData::new(Method::POST, format!("session/{}/execute/async", session_id))
                    .add_body(json!({"script": script, "args": args}))
            }
            Command::GetAllCookies => {
                RequestData::new(Method::GET, format!("session/{}/cookie", session_id))
            }
            Command::GetNamedCookie(cookie_name) => RequestData::new(
                Method::GET,
                format!("session/{}/cookie/{}", session_id, cookie_name),
            ),
            Command::AddCookie(cookie) => {
                RequestData::new(Method::POST, format!("session/{}/cookie", session_id))
                    .add_body(json!({ "cookie": cookie }))
            }
            Command::DeleteCookie(cookie_name) => RequestData::new(
                Method::DELETE,
                format!("session/{}/cookie/{}", session_id, cookie_name),
            ),
            Command::DeleteAllCookies => {
                RequestData::new(Method::DELETE, format!("session/{}/cookie", session_id))
            }
            Command::PerformActions(actions) => {
                RequestData::new(Method::POST, format!("session/{}/actions", session_id))
                    .add_body(json!({"actions": actions.0}))
            }
            Command::ReleaseActions => {
                RequestData::new(Method::DELETE, format!("session/{}/actions", session_id))
            }
            Command::DismissAlert => {
                RequestData::new(Method::POST, format!("session/{}/alert/dismiss", session_id))
                    .add_body(json!({}))
            }
            Command::AcceptAlert => {
                RequestData::new(Method::POST, format!("session/{}/alert/accept", session_id))
                    .add_body(json!({}))
            }
            Command::GetAlertText => {
                RequestData::new(Method::GET, format!("session/{}/alert/text", session_id))
            }
            Command::SendAlertText(typing_data) => {
                RequestData::new(Method::POST, format!("session/{}/alert/text", session_id))
                    .add_body(json!({
                        "value": typing_data.as_vec(), "text": typing_data.to_string()
                    }))
            }
            Command::PrintPage(params) => {
                RequestData::new(Method::POST, format!("/session/{}/print", session_id)).add_body(
                    serde_json::to_value(params)
                        .expect("Fail to parse Print Page Parameters to json"),
                )
            }
            Command::TakeScreenshot => {
                RequestData::new(Method::GET, format!("session/{}/screenshot", session_id))
            }
            Command::TakeElementScreenshot(element_id) => RequestData::new(
                Method::GET,
                format!("session/{}/element/{}/screenshot", session_id, element_id),
            ),
            Command::GetLogTypes => {
                RequestData::new(Method::GET, format!("session/{}/log/types", session_id))
            }
            Command::GetLog(log_type) => {
                RequestData::new(Method::POST, format!("session/{}/log", session_id))
                    .add_body(json!({ "type": log_type }))
            }
            Command::ExtensionCommand(command) => {
                let request_data = RequestData::new(
                    command.method(),
                    format!("session/{}{}", session_id, command.endpoint()),
                );
                match command.parameters_json() {
                    Some(param) => request_data.add_body(param),
                    None => request_data,
                }
            }
        }
    }
}