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
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
use serde::Serialize;
use serde_repr::Serialize_repr;
use std::time::Duration;

use crate::common::{keys::TypingData, types::ElementId};

/// Trait for all Actions.
pub trait Action {
    /// Get a pause action.
    fn get_pause(duration_ms: u64) -> Self;
}

/// Null Action.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum NullAction {
    /// Pause action.
    Pause {
        /// Duration of the pause in milliseconds.
        duration: u64,
    },
}

impl Action for NullAction {
    fn get_pause(duration_ms: u64) -> Self {
        NullAction::Pause {
            duration: duration_ms,
        }
    }
}

/// Key Action.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum KeyAction {
    /// Pause action.
    Pause {
        /// Duration of the pause in milliseconds.
        duration: u64,
    },
    /// Key Up action.
    KeyUp {
        /// The key to press.
        value: char,
    },
    /// Key Down action.
    KeyDown {
        /// The key to release.
        value: char,
    },
}

impl Action for KeyAction {
    fn get_pause(duration_ms: u64) -> Self {
        KeyAction::Pause {
            duration: duration_ms,
        }
    }
}

/// Mouse Button.
#[derive(Debug, Clone, Serialize_repr)]
#[repr(u8)]
pub enum MouseButton {
    /// Left mouse button.
    Left = 0,
    /// Middle mouse button.
    Middle = 1,
    /// Right mouse button.
    Right = 2,
}

/// Pointer Origin.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PointerOrigin {
    /// Pointer origin is the viewport.
    Viewport,
    /// Pointer origin is the pointer itself.
    Pointer,
    /// Pointer origin is a WebElement.
    #[serde(rename = "element-6066-11e4-a52e-4f735466cecf")]
    WebElement(ElementId),
}

/// Pointer Action.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum PointerAction {
    /// Pause action.
    Pause {
        /// Duration of the pause in milliseconds.
        duration: u64,
    },
    /// Pointer down action.
    PointerDown {
        /// The mouse button to press.
        button: MouseButton,
        /// Duration of the action in milliseconds.
        duration: u64,
    },
    /// Pointer up action.
    PointerUp {
        /// The mouse button to release.
        button: MouseButton,
        /// Duration of the action in milliseconds.
        duration: u64,
    },
    /// Pointer move action.
    PointerMove {
        /// Duration of the action in milliseconds.
        duration: u64,
        /// The pointer origin.
        origin: PointerOrigin,
        /// The x coordinate to move to.
        x: i64,
        /// The y coordinate to move to.
        y: i64,
    },
    /// Pointer cancel action.
    PointerCancel,
}

impl Action for PointerAction {
    fn get_pause(duration_ms: u64) -> Self {
        PointerAction::Pause {
            duration: duration_ms,
        }
    }
}

/// Parameters for Pointer Actions.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PointerParameters {
    /// The type of pointer.
    pointer_type: String,
}

/// Action Source.
#[derive(Debug, Clone, Serialize)]
pub struct ActionSource<T: Action + Clone> {
    /// The ID of the action source.
    id: String,
    /// The type of action source.
    #[serde(rename(serialize = "type"))]
    action_type: String,
    /// Parameters for the action source.
    #[serde(skip_serializing_if = "Option::is_none")]
    parameters: Option<PointerParameters>,
    /// The actions to perform.
    actions: Vec<T>,
    /// The duration of the action source in milliseconds.
    #[serde(skip_serializing)]
    duration: u64,
}

impl<T> ActionSource<T>
where
    T: Action + Clone,
{
    /// Add the specified action to this action source.
    pub fn add_action(&mut self, action: T) {
        self.actions.push(action);
    }

    /// Add a pause action so this action source.
    pub fn pause(&mut self) {
        self.actions.push(T::get_pause(0));
    }

    /// Add a pause action with the specified duration to this action source.
    pub fn pause_for(&mut self, duration_ms: u64) {
        self.actions.push(T::get_pause(duration_ms));
    }

    /// Get the ID of this action source.
    pub fn id(&self) -> &str {
        &self.id
    }
}

impl ActionSource<KeyAction> {
    /// Create a new Key action source.
    ///
    /// Duration represents the time before an action is executed.
    /// Defaults to 0ms
    pub fn new(name: &str, duration: Option<Duration>) -> Self {
        let duration = match duration {
            Some(duration) => {
                let millis = duration.as_millis();
                u64::try_from(millis).ok().unwrap_or(u64::MAX)
            }
            None => 0,
        };

        ActionSource {
            id: name.to_owned(),
            action_type: String::from("key"),
            parameters: None,
            actions: Vec::new(),
            duration,
        }
    }

    /// Add a Key Down action.
    pub fn key_down(&mut self, value: char) {
        self.add_action(KeyAction::KeyDown {
            value,
        });
    }

    /// Add a Key Up action.
    pub fn key_up(&mut self, value: char) {
        self.add_action(KeyAction::KeyUp {
            value,
        });
    }

    /// Send multiple keys as a string of Key Up and Key Down actions.
    pub fn send_keys(&mut self, text: TypingData) {
        for c in text.as_vec() {
            self.key_down(c);
            self.key_up(c);
        }
    }
}

/// Enum representing the type of pointer action.
#[derive(Debug)]
pub enum PointerActionType {
    /// Mouse pointer.
    Mouse,
    /// Pen pointer.
    Pen,
    /// Touch pointer.
    Touch,
}

impl ActionSource<PointerAction> {
    /// Create a new Pointer action source.
    ///
    /// Duration represents the time before an action is executed.
    /// Defaults to 250ms
    pub fn new(name: &str, action_type: PointerActionType, duration: Option<Duration>) -> Self {
        let duration = match duration {
            Some(duration) => {
                let millis = duration.as_millis();
                u64::try_from(millis).ok().unwrap_or(u64::MAX)
            }
            None => 250,
        };

        ActionSource {
            id: name.to_owned(),
            action_type: String::from("pointer"),
            parameters: Some(PointerParameters {
                pointer_type: String::from(match action_type {
                    PointerActionType::Mouse => "mouse",
                    PointerActionType::Pen => "pen",
                    PointerActionType::Touch => "touch",
                }),
            }),
            actions: Vec::new(),
            duration,
        }
    }

    /// Add a move action to the specified coordinates.
    pub fn move_to(&mut self, x: i64, y: i64) {
        self.add_action(PointerAction::PointerMove {
            duration: self.duration,
            origin: PointerOrigin::Viewport,
            x,
            y,
        });
    }

    /// Add a move action by the specified coordinates.
    pub fn move_by(&mut self, x: i64, y: i64) {
        self.add_action(PointerAction::PointerMove {
            duration: self.duration,
            origin: PointerOrigin::Pointer,
            x,
            y,
        });
    }

    /// Add a move action to the specified coordinates relative to the element.
    pub fn move_to_element(&mut self, element_id: ElementId, x: i64, y: i64) {
        self.add_action(PointerAction::PointerMove {
            duration: self.duration,
            origin: PointerOrigin::WebElement(element_id),
            x,
            y,
        });
    }

    /// Add a move action to the center of the specified element.
    pub fn move_to_element_center(&mut self, element_id: ElementId) {
        self.add_action(PointerAction::PointerMove {
            duration: self.duration,
            origin: PointerOrigin::WebElement(element_id),
            x: 0,
            y: 0,
        });
    }

    /// Add a click action.
    pub fn click(&mut self) {
        self.add_action(PointerAction::PointerDown {
            button: MouseButton::Left,
            duration: 0,
        });
        self.add_action(PointerAction::PointerUp {
            button: MouseButton::Left,
            duration: 0,
        });
    }

    /// Add a right-click action.
    pub fn context_click(&mut self) {
        self.add_action(PointerAction::PointerDown {
            button: MouseButton::Right,
            duration: 0,
        });
        self.add_action(PointerAction::PointerUp {
            button: MouseButton::Right,
            duration: 0,
        });
    }

    /// Add a click-and-hold action.
    pub fn click_and_hold(&mut self) {
        self.add_action(PointerAction::PointerDown {
            button: MouseButton::Left,
            duration: 0,
        });
    }

    /// Add a click-and-hold action on the specified element.
    pub fn click_element_and_hold(&mut self, element_id: ElementId) {
        self.move_to_element_center(element_id);
        self.click_and_hold();
    }

    /// Add a release action.
    pub fn release(&mut self) {
        self.add_action(PointerAction::PointerUp {
            button: MouseButton::Left,
            duration: 0,
        });
    }

    /// Add a double-click action.
    pub fn double_click(&mut self) {
        self.click();
        self.click();
    }

    /// Add a double-click action on the specified element.
    pub fn double_click_element(&mut self, element_id: ElementId) {
        self.move_to_element_center(element_id);
        self.double_click();
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn compare_null_action(action: NullAction, value: serde_json::Value) {
        let actions: Vec<NullAction> = vec![action];
        let source = ActionSource {
            action_type: String::from("none"),
            id: String::from("null"),
            parameters: None,
            actions,
            duration: 0,
        };

        let value_got = serde_json::to_value(source);
        assert!(value_got.is_ok());
        assert_eq!(
            value_got.unwrap(),
            json!({
                "id": "null",
                "type": "none",
                "actions": [ value ]
            })
        );
    }

    #[test]
    fn test_null_action() {
        compare_null_action(
            NullAction::Pause {
                duration: 0,
            },
            json!({"type": "pause", "duration": 0}),
        );

        compare_null_action(
            NullAction::Pause {
                duration: 4,
            },
            json!({"type": "pause", "duration": 4}),
        );
    }

    fn compare_key_action(action: KeyAction, value: serde_json::Value) {
        let mut source = ActionSource::<KeyAction>::new("key", None);
        source.add_action(action);

        let value_got = serde_json::to_value(source);
        assert!(value_got.is_ok());
        assert_eq!(
            value_got.unwrap(),
            json!({
                "id": "key",
                "type": "key",
                "actions": [ value ]
            })
        );
    }

    #[test]
    fn test_key_action_pause() {
        compare_key_action(
            KeyAction::Pause {
                duration: 0,
            },
            json!({"type": "pause", "duration": 0}),
        );

        compare_key_action(
            KeyAction::Pause {
                duration: 3,
            },
            json!({"type": "pause", "duration": 3}),
        );
    }

    #[test]
    fn test_key_action_updown() {
        compare_key_action(
            KeyAction::KeyDown {
                value: 'a',
            },
            json!({"type": "keyDown", "value": 'a'}),
        );

        compare_key_action(
            KeyAction::KeyDown {
                value: '\u{e004}',
            },
            json!({
            "type": "keyDown", "value": '\u{e004}'
            }),
        );

        compare_key_action(
            KeyAction::KeyUp {
                value: 'a',
            },
            json!({"type": "keyUp", "value": 'a'}),
        );

        compare_key_action(
            KeyAction::KeyUp {
                value: '\u{e004}',
            },
            json!({
            "type": "keyUp", "value": '\u{e004}'
            }),
        );
    }

    fn compare_pointer_action(action: PointerAction, value: serde_json::Value) {
        let mut source =
            ActionSource::<PointerAction>::new("mouse", PointerActionType::Mouse, None);
        source.add_action(action);

        let value_got = serde_json::to_value(source);
        assert!(value_got.is_ok());
        assert_eq!(
            value_got.unwrap(),
            json!({
                "id": "mouse",
                "type": "pointer",
                "parameters": {
                    "pointerType": "mouse"
                },
                "actions": [ value ]
            })
        );
    }

    #[test]
    fn test_pointer_action_pause() {
        compare_pointer_action(
            PointerAction::Pause {
                duration: 0,
            },
            json!({"type": "pause", "duration": 0}),
        );

        compare_pointer_action(
            PointerAction::Pause {
                duration: 2,
            },
            json!({"type": "pause", "duration": 2}),
        );
    }

    #[test]
    fn test_pointer_action_button() {
        compare_pointer_action(
            PointerAction::PointerDown {
                button: MouseButton::Left,
                duration: 0,
            },
            json!({"type": "pointerDown", "button": 0, "duration": 0}),
        );

        compare_pointer_action(
            PointerAction::PointerDown {
                button: MouseButton::Middle,
                duration: 0,
            },
            json!({"type": "pointerDown", "button": 1, "duration": 0}),
        );

        compare_pointer_action(
            PointerAction::PointerDown {
                button: MouseButton::Right,
                duration: 0,
            },
            json!({"type": "pointerDown", "button": 2, "duration": 0}),
        );

        compare_pointer_action(
            PointerAction::PointerUp {
                button: MouseButton::Left,
                duration: 0,
            },
            json!({"type": "pointerUp", "button": 0, "duration": 0}),
        );

        compare_pointer_action(
            PointerAction::PointerUp {
                button: MouseButton::Middle,
                duration: 0,
            },
            json!({"type": "pointerUp", "button": 1, "duration": 0}),
        );

        compare_pointer_action(
            PointerAction::PointerUp {
                button: MouseButton::Right,
                duration: 0,
            },
            json!({"type": "pointerUp", "button": 2, "duration": 0}),
        );
    }

    #[test]
    fn test_pointer_action_pointermove() {
        compare_pointer_action(
            PointerAction::PointerMove {
                duration: 0,
                x: 0,
                y: 0,
                origin: PointerOrigin::Viewport,
            },
            json!({
            "type": "pointerMove", "origin": "viewport", "x": 0, "y": 0, "duration": 0
            }),
        );

        compare_pointer_action(
            PointerAction::PointerMove {
                duration: 0,
                x: 0,
                y: 0,
                origin: PointerOrigin::Pointer,
            },
            json!({
            "type": "pointerMove", "origin": "pointer", "x": 0, "y": 0, "duration": 0
            }),
        );

        compare_pointer_action(
            PointerAction::PointerMove {
                duration: 0,
                x: 0,
                y: 0,
                origin: PointerOrigin::WebElement(ElementId::from("id1234")),
            },
            json!({
            "type": "pointerMove", "origin": {"element-6066-11e4-a52e-4f735466cecf": "id1234"}, "x": 0, "y": 0, "duration": 0
            }),
        );

        compare_pointer_action(
            PointerAction::PointerMove {
                duration: 1,
                x: 100,
                y: 200,
                origin: PointerOrigin::Viewport,
            },
            json!({
                "type": "pointerMove",
                "x": 100,
                "y": 200,
                "duration": 1,
                "origin": "viewport"
            }),
        );

        compare_pointer_action(
            PointerAction::PointerMove {
                duration: 1,
                x: 100,
                y: 200,
                origin: PointerOrigin::Pointer,
            },
            json!({
                "type": "pointerMove",
                "x": 100,
                "y": 200,
                "duration": 1,
                "origin": "pointer"
            }),
        );

        compare_pointer_action(
            PointerAction::PointerMove {
                duration: 1,
                x: 100,
                y: 200,
                origin: PointerOrigin::WebElement(ElementId::from("someid")),
            },
            json!({
                "type": "pointerMove",
                "x": 100,
                "y": 200,
                "duration": 1,
                "origin": {"element-6066-11e4-a52e-4f735466cecf": "someid"}
            }),
        );
    }

    #[test]
    fn test_pointer_action_cancel() {
        compare_pointer_action(PointerAction::PointerCancel, json!({"type": "pointerCancel"}));
    }
}