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
//! `Network` domain — network observation, headers, cookies, throttling.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::cdp::Cdp;
use crate::cdp::command::{CdpCommand, CdpEvent, Empty};
use crate::cdp::ids::{LoaderId, RequestId};
use crate::common::protocol::string_enum;
use crate::error::WebDriverResult;

string_enum! {
    /// Connection type for network throttling
    /// (`Network.ConnectionType`).
    pub enum ConnectionType {
        /// No connection.
        None = "none",
        /// 2G cellular.
        Cellular2G = "cellular2g",
        /// 3G cellular.
        Cellular3G = "cellular3g",
        /// 4G cellular.
        Cellular4G = "cellular4g",
        /// Bluetooth.
        Bluetooth = "bluetooth",
        /// Ethernet.
        Ethernet = "ethernet",
        /// WiFi.
        Wifi = "wifi",
        /// WiMAX.
        Wimax = "wimax",
        /// Other.
        Other = "other",
    }
}

string_enum! {
    /// Reason a network request failed (`Network.ErrorReason`). Used by
    /// [`crate::cdp::domains::fetch::FailRequest`] and seen on
    /// [`LoadingFailed`] / [`crate::cdp::domains::fetch::RequestPaused`]
    /// events.
    pub enum ErrorReason {
        /// Generic failure.
        Failed = "Failed",
        /// Request was aborted (e.g. user navigation).
        Aborted = "Aborted",
        /// Request timed out.
        TimedOut = "TimedOut",
        /// Access was denied (e.g. CORS).
        AccessDenied = "AccessDenied",
        /// Connection was closed.
        ConnectionClosed = "ConnectionClosed",
        /// Connection was reset.
        ConnectionReset = "ConnectionReset",
        /// Connection was refused.
        ConnectionRefused = "ConnectionRefused",
        /// Connection was aborted.
        ConnectionAborted = "ConnectionAborted",
        /// Connection failed for another reason.
        ConnectionFailed = "ConnectionFailed",
        /// DNS resolution failed.
        NameNotResolved = "NameNotResolved",
        /// Browser is offline.
        InternetDisconnected = "InternetDisconnected",
        /// Address could not be reached.
        AddressUnreachable = "AddressUnreachable",
        /// Blocked by client (e.g. extension).
        BlockedByClient = "BlockedByClient",
        /// Blocked by server response (e.g. CSP).
        BlockedByResponse = "BlockedByResponse",
    }
}

string_enum! {
    /// Resource type classification used by `Network` and `Fetch` events
    /// (`Network.ResourceType`).
    pub enum ResourceType {
        /// HTML document.
        Document = "Document",
        /// CSS stylesheet.
        Stylesheet = "Stylesheet",
        /// Image (raster or SVG).
        Image = "Image",
        /// Audio or video.
        Media = "Media",
        /// Web font.
        Font = "Font",
        /// JavaScript script.
        Script = "Script",
        /// `<track>` text track.
        TextTrack = "TextTrack",
        /// `XMLHttpRequest`.
        Xhr = "XHR",
        /// `fetch()` API.
        Fetch = "Fetch",
        /// `<link rel="prefetch">`.
        Prefetch = "Prefetch",
        /// Server-Sent Events.
        EventSource = "EventSource",
        /// WebSocket.
        WebSocket = "WebSocket",
        /// Web app manifest.
        Manifest = "Manifest",
        /// Signed Exchange.
        SignedExchange = "SignedExchange",
        /// `navigator.sendBeacon` ping.
        Ping = "Ping",
        /// CSP violation report.
        CspViolationReport = "CSPViolationReport",
        /// CORS preflight.
        Preflight = "Preflight",
        /// Anything else.
        Other = "Other",
    }
}

/// Simulated network conditions for `Network.emulateNetworkConditions`.
///
/// See <https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-emulateNetworkConditions>.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkConditions {
    /// True to emulate the network being offline.
    pub offline: bool,
    /// Latency to add (milliseconds).
    pub latency: u32,
    /// Download throughput, bytes/second. `-1` disables download throttling.
    pub download_throughput: i32,
    /// Upload throughput, bytes/second. `-1` disables upload throttling.
    pub upload_throughput: i32,
    /// Connection type, if known.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_type: Option<ConnectionType>,
}

impl Default for NetworkConditions {
    fn default() -> Self {
        Self {
            offline: false,
            latency: 0,
            download_throughput: -1,
            upload_throughput: -1,
            connection_type: None,
        }
    }
}

impl NetworkConditions {
    /// Construct an instance with throttling disabled.
    pub fn new() -> Self {
        Self::default()
    }
}

/// `Network.enable`.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Enable {
    /// Buffer size in bytes for resource bodies (default 0 — disabled).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_total_buffer_size: Option<i64>,
    /// Per-resource max buffer size in bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_resource_buffer_size: Option<i64>,
}
impl CdpCommand for Enable {
    const METHOD: &'static str = "Network.enable";
    type Returns = Empty;
}

/// `Network.disable`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Disable;
impl CdpCommand for Disable {
    const METHOD: &'static str = "Network.disable";
    type Returns = Empty;
}

/// `Network.clearBrowserCache`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ClearBrowserCache;
impl CdpCommand for ClearBrowserCache {
    const METHOD: &'static str = "Network.clearBrowserCache";
    type Returns = Empty;
}

/// `Network.clearBrowserCookies`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ClearBrowserCookies;
impl CdpCommand for ClearBrowserCookies {
    const METHOD: &'static str = "Network.clearBrowserCookies";
    type Returns = Empty;
}

/// `Network.setExtraHTTPHeaders`.
#[derive(Debug, Clone, Serialize)]
pub struct SetExtraHttpHeaders {
    /// Map of header name to value. Wire field is `headers`.
    pub headers: HashMap<String, String>,
}
impl CdpCommand for SetExtraHttpHeaders {
    const METHOD: &'static str = "Network.setExtraHTTPHeaders";
    type Returns = Empty;
}

/// `Network.setUserAgentOverride`.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetUserAgentOverride {
    /// User agent string to use.
    pub user_agent: String,
    /// Browser language.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accept_language: Option<String>,
    /// Platform string (e.g. `"Linux x86_64"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub platform: Option<String>,
}
impl CdpCommand for SetUserAgentOverride {
    const METHOD: &'static str = "Network.setUserAgentOverride";
    type Returns = Empty;
}

/// `Network.emulateNetworkConditions`.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EmulateNetworkConditions {
    /// True to emulate the network being offline.
    pub offline: bool,
    /// Latency to add (milliseconds).
    pub latency: u32,
    /// Download throughput, bytes/second. `-1` disables.
    pub download_throughput: i32,
    /// Upload throughput, bytes/second. `-1` disables.
    pub upload_throughput: i32,
    /// Connection type if known.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_type: Option<ConnectionType>,
}

impl From<NetworkConditions> for EmulateNetworkConditions {
    fn from(c: NetworkConditions) -> Self {
        Self {
            offline: c.offline,
            latency: c.latency,
            download_throughput: c.download_throughput,
            upload_throughput: c.upload_throughput,
            connection_type: c.connection_type,
        }
    }
}

impl CdpCommand for EmulateNetworkConditions {
    const METHOD: &'static str = "Network.emulateNetworkConditions";
    type Returns = Empty;
}

/// `Network.getResponseBody`.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetResponseBody {
    /// Identifier of the network request.
    pub request_id: RequestId,
}

/// Response for [`GetResponseBody`].
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseBody {
    /// Response body.
    pub body: String,
    /// True if `body` is base64-encoded.
    pub base64_encoded: bool,
}

impl CdpCommand for GetResponseBody {
    const METHOD: &'static str = "Network.getResponseBody";
    type Returns = ResponseBody;
}

/// `Network.requestWillBeSent` event.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestWillBeSent {
    /// Request identifier.
    pub request_id: RequestId,
    /// Loader identifier.
    pub loader_id: LoaderId,
    /// URL of the document this request is loaded for. CDP spells this
    /// `documentURL` (capital `URL`), not the camelCase you'd expect.
    #[serde(rename = "documentURL")]
    pub document_url: String,
    /// Request data — full structure documented at
    /// <https://chromedevtools.github.io/devtools-protocol/tot/Network/#type-Request>.
    pub request: serde_json::Value,
    /// Timestamp of the event.
    pub timestamp: f64,
    /// Wall-clock time of the event.
    pub wall_time: f64,
    /// Initiator info.
    pub initiator: serde_json::Value,
}
impl CdpEvent for RequestWillBeSent {
    const METHOD: &'static str = "Network.requestWillBeSent";
    const ENABLE: Option<&'static str> = Some("Network.enable");
}

/// `Network.responseReceived` event.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseReceived {
    /// Request identifier.
    pub request_id: RequestId,
    /// Loader identifier.
    pub loader_id: LoaderId,
    /// Timestamp.
    pub timestamp: f64,
    /// Resource type (e.g. `Document`, `Xhr`, `Image`).
    pub r#type: ResourceType,
    /// Full response details (status, headers, mime type, etc.).
    pub response: serde_json::Value,
}
impl CdpEvent for ResponseReceived {
    const METHOD: &'static str = "Network.responseReceived";
    const ENABLE: Option<&'static str> = Some("Network.enable");
}

/// `Network.loadingFinished` event.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoadingFinished {
    /// Request identifier.
    pub request_id: RequestId,
    /// Timestamp.
    pub timestamp: f64,
    /// Total number of bytes received.
    pub encoded_data_length: f64,
}
impl CdpEvent for LoadingFinished {
    const METHOD: &'static str = "Network.loadingFinished";
    const ENABLE: Option<&'static str> = Some("Network.enable");
}

/// `Network.loadingFailed` event.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoadingFailed {
    /// Request identifier.
    pub request_id: RequestId,
    /// Timestamp.
    pub timestamp: f64,
    /// Resource type.
    pub r#type: ResourceType,
    /// User-friendly error message.
    pub error_text: String,
    /// Whether the loading was canceled.
    pub canceled: Option<bool>,
}
impl CdpEvent for LoadingFailed {
    const METHOD: &'static str = "Network.loadingFailed";
    const ENABLE: Option<&'static str> = Some("Network.enable");
}

/// Domain facade returned by [`Cdp::network`].
#[derive(Debug)]
pub struct NetworkDomain<'a> {
    cdp: &'a Cdp,
}

impl<'a> NetworkDomain<'a> {
    pub(crate) fn new(cdp: &'a Cdp) -> Self {
        Self {
            cdp,
        }
    }

    /// `Network.enable` (default buffer sizes).
    pub async fn enable(&self) -> WebDriverResult<()> {
        self.cdp.send(Enable::default()).await?;
        Ok(())
    }

    /// `Network.disable`.
    pub async fn disable(&self) -> WebDriverResult<()> {
        self.cdp.send(Disable).await?;
        Ok(())
    }

    /// `Network.clearBrowserCache`.
    pub async fn clear_browser_cache(&self) -> WebDriverResult<()> {
        self.cdp.send(ClearBrowserCache).await?;
        Ok(())
    }

    /// `Network.clearBrowserCookies`.
    pub async fn clear_browser_cookies(&self) -> WebDriverResult<()> {
        self.cdp.send(ClearBrowserCookies).await?;
        Ok(())
    }

    /// `Network.setExtraHTTPHeaders`.
    pub async fn set_extra_http_headers(
        &self,
        headers: HashMap<String, String>,
    ) -> WebDriverResult<()> {
        self.cdp
            .send(SetExtraHttpHeaders {
                headers,
            })
            .await?;
        Ok(())
    }

    /// `Network.setUserAgentOverride`.
    pub async fn set_user_agent_override(
        &self,
        user_agent: impl Into<String>,
    ) -> WebDriverResult<()> {
        self.cdp
            .send(SetUserAgentOverride {
                user_agent: user_agent.into(),
                accept_language: None,
                platform: None,
            })
            .await?;
        Ok(())
    }

    /// `Network.emulateNetworkConditions` from a [`NetworkConditions`].
    pub async fn emulate_network_conditions(
        &self,
        conditions: NetworkConditions,
    ) -> WebDriverResult<()> {
        self.cdp.send(EmulateNetworkConditions::from(conditions)).await?;
        Ok(())
    }

    /// `Network.getResponseBody`.
    pub async fn get_response_body(
        &self,
        request_id: impl Into<RequestId>,
    ) -> WebDriverResult<ResponseBody> {
        self.cdp
            .send(GetResponseBody {
                request_id: request_id.into(),
            })
            .await
    }
}