browsing 0.1.3

Lightweight MCP/API for browser automation: navigate, get content (text), screenshot. Parallelism via RwLock.
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Comprehensive tests for tools handlers
//!
//! These tests cover:
//! - NavigationHandler (search, navigate)
//! - InteractionHandler (click, input, send_keys)
//! - ContentHandler (scroll, find_text, dropdown_options, select_dropdown)
//! - TabsHandler (create_tab, switch_tab, close_tab)
//! - AdvancedHandler (extract_content, extract_links, etc.)

use browsing::error::BrowsingError;

// ============================================================================
// NavigationHandler Tests
// ============================================================================

#[test]
fn test_navigation_handler_search_action_type() {
    let action_type = "search";
    assert_eq!(action_type, "search");
}

#[test]
fn test_navigation_handler_navigate_action_type() {
    let action_type = "navigate";
    assert_eq!(action_type, "navigate");
}

#[test]
fn test_search_engine_duckduckgo() {
    let engine = "duckduckgo";
    let query = "test query";
    let encoded_query = urlencoding::encode(query);
    let search_url = format!("https://duckduckgo.com/?q={encoded_query}");

    assert_eq!(search_url, "https://duckduckgo.com/?q=test%20query");
    assert!(search_url.contains("duckduckgo.com"));
}

#[test]
fn test_search_engine_google() {
    let engine = "google";
    let query = "rust programming";
    let encoded_query = urlencoding::encode(query);
    let search_url = format!("https://www.google.com/search?q={encoded_query}&udm=14");

    assert!(search_url.contains("google.com/search"));
    assert!(search_url.contains("q=rust%20programming"));
}

#[test]
fn test_search_engine_bing() {
    let engine = "bing";
    let query = "browser automation";
    let encoded_query = urlencoding::encode(query);
    let search_url = format!("https://www.bing.com/search?q={encoded_query}");

    assert!(search_url.contains("bing.com/search"));
    assert!(search_url.contains("q=browser%20automation"));
}

#[test]
fn test_url_encoding() {
    let query = "hello world & test";
    let encoded = urlencoding::encode(query);
    let encoded_str = encoded.to_string();

    assert_eq!(encoded_str, "hello%20world%20%26%20test");
    assert!(!encoded_str.contains(" "));
    assert!(!encoded_str.contains("&"));
}

#[test]
fn test_navigate_url_validation() {
    let valid_urls = vec![
        "https://example.com",
        "http://localhost:8080",
        "https://www.google.com/search?q=test",
    ];

    for url in valid_urls {
        assert!(url.starts_with("http://") || url.starts_with("https://"));
        assert!(url.len() > 10);
    }
}

#[test]
fn test_navigate_new_tab_flag() {
    let new_tab = true;
    assert!(new_tab, "Should create new tab");

    let new_tab = false;
    assert!(!new_tab, "Should navigate in current tab");
}

// ============================================================================
// InteractionHandler Tests
// ============================================================================

#[test]
fn test_interaction_handler_click_action_type() {
    let action_type = "click";
    assert_eq!(action_type, "click");
}

#[test]
fn test_interaction_handler_input_action_type() {
    let action_type = "input";
    assert_eq!(action_type, "input");
}

#[test]
fn test_interaction_handler_send_keys_action_type() {
    let action_type = "send_keys";
    assert_eq!(action_type, "send_keys");
}

#[test]
fn test_element_index_validation() {
    let valid_indices = vec![0u32, 1, 10, 100, 999999];

    for index in valid_indices {
        assert!(index < u32::MAX, "Index should be valid");
    }
}

#[test]
fn test_input_text_validation() {
    let valid_texts = vec![
        "Hello, World!",
        "test@example.com",
        "12345",
        "Special chars: !@#$%^&*()",
        "Unicode: 你好世界 🌍",
    ];

    for text in valid_texts {
        assert!(!text.is_empty(), "Input text should not be empty");
    }
}

#[test]
fn test_key_sequence_parsing() {
    let key_sequences = vec![
        "Enter",
        "Escape",
        "Control+A",
        "Shift+End",
        "Control+C Control+V",
    ];

    for sequence in key_sequences {
        let keys: Vec<&str> = sequence.split_whitespace().collect();
        assert!(!keys.is_empty(), "Key sequence should not be empty");
    }
}

#[test]
fn test_backend_node_id_validation() {
    let valid_ids = vec![1u32, 100, 1000, 999999];

    for id in valid_ids {
        assert!(id > 0, "Backend node ID should be positive");
    }
}

// ============================================================================
// ContentHandler Tests
// ============================================================================

#[test]
fn test_content_handler_scroll_action_type() {
    let action_type = "scroll";
    assert_eq!(action_type, "scroll");
}

#[test]
fn test_content_handler_find_text_action_type() {
    let action_type = "find_text";
    assert_eq!(action_type, "find_text");
}

#[test]
fn test_content_handler_dropdown_options_action_type() {
    let action_type = "dropdown_options";
    assert_eq!(action_type, "dropdown_options");
}

#[test]
fn test_content_handler_select_dropdown_action_type() {
    let action_type = "select_dropdown";
    assert_eq!(action_type, "select_dropdown");
}

#[test]
fn test_scroll_direction_validation() {
    let down = true;
    assert!(down, "Should scroll down");

    let down = false;
    assert!(!down, "Should scroll up");
}

#[test]
fn test_scroll_pages_validation() {
    let valid_pages = vec![0.5f64, 1.0, 2.0, 3.5, 10.0];

    for pages in valid_pages {
        assert!(pages > 0.0, "Scroll pages should be positive");
        assert!(pages <= 100.0, "Scroll pages should be reasonable");
    }
}

#[test]
fn test_scroll_delta_calculation() {
    let viewport_height = 1000.0f64;
    let pages = 2.0f64;

    let delta_down = pages * viewport_height; // 2000.0
    let delta_up = -pages * viewport_height; // -2000.0

    assert_eq!(delta_down, 2000.0);
    assert_eq!(delta_up, -2000.0);
}

#[test]
fn test_find_text_validation() {
    let valid_texts = vec![
        "Search term",
        "123",
        "Special & chars",
        "Unicode text",
        "Single word",
    ];

    for text in valid_texts {
        assert!(!text.is_empty(), "Search text should not be empty");
    }
}

#[test]
fn test_dropdown_option_format() {
    let option_value = "option1";
    let option_text = "Option 1";
    let option_selected = true;

    assert_eq!(option_value, "option1");
    assert_eq!(option_text, "Option 1");
    assert!(option_selected);
}

#[test]
fn test_select_dropdown_validation() {
    let valid_selections = vec!["Option 1", "option1", "First option", "value", "Any text"];

    for selection in valid_selections {
        assert!(
            !selection.is_empty(),
            "Dropdown selection should not be empty"
        );
    }
}

// ============================================================================
// TabsHandler Tests
// ============================================================================

#[test]
fn test_tabs_handler_create_tab_action_type() {
    let action_type = "create_tab";
    assert_eq!(action_type, "create_tab");
}

#[test]
fn test_tabs_handler_switch_tab_action_type() {
    let action_type = "switch_tab";
    assert_eq!(action_type, "switch_tab");
}

#[test]
fn test_tabs_handler_close_tab_action_type() {
    let action_type = "close_tab";
    assert_eq!(action_type, "close_tab");
}

#[test]
fn test_tab_creation_with_url() {
    let url = "https://example.com";
    assert!(url.starts_with("https://"));
}

#[test]
fn test_tab_creation_blank_url() {
    let url = "about:blank";
    assert_eq!(url, "about:blank");
}

#[test]
fn test_target_id_format() {
    let target_id = "E12BA567-8A90-1234-5678-9ABCDEF01234";
    assert_eq!(target_id.len(), 36);
    assert!(target_id.contains('-'));
}

// ============================================================================
// AdvancedHandler Tests
// ============================================================================

#[test]
fn test_extract_content_action_type() {
    let action_type = "extract_content";
    assert_eq!(action_type, "extract_content");
}

#[test]
fn test_extract_links_action_type() {
    let action_type = "extract_links";
    assert_eq!(action_type, "extract_links");
}

#[test]
fn test_extract_images_action_type() {
    let action_type = "extract_images";
    assert_eq!(action_type, "extract_images");
}

#[test]
fn test_wait_action_type() {
    let action_type = "wait";
    assert_eq!(action_type, "wait");
}

#[test]
fn test_wait_duration_validation() {
    let valid_durations = vec![100u64, 500, 1000, 5000, 10000];

    for duration in valid_durations {
        assert!(duration >= 100, "Wait duration should be at least 100ms");
        assert!(
            duration <= 60000,
            "Wait duration should not exceed 60 seconds"
        );
    }
}

// ============================================================================
// ActionResult Tests
// ============================================================================

#[test]
fn test_action_result_default() {
    use browsing::agent::views::ActionResult;

    let result = ActionResult::default();

    assert!(result.extracted_content.is_none_or(|s| s.is_empty()));
    assert!(result.long_term_memory.is_none_or(|s| s.is_empty()));
}

#[test]
fn test_action_result_with_content() {
    use browsing::agent::views::ActionResult;

    let result = ActionResult {
        extracted_content: Some("Test content".to_string()),
        long_term_memory: Some("Test memory".to_string()),
        ..Default::default()
    };

    assert_eq!(result.extracted_content, Some("Test content".to_string()));
    assert_eq!(result.long_term_memory, Some("Test memory".to_string()));
}

#[test]
fn test_action_result_memory_format() {
    let memories = vec![
        "Navigated to https://example.com",
        "Clicked element 1 (backend_node_id: 123)",
        "Input text into element 5 (backend_node_id: 456)",
        "Scrolled down 1 pages",
        "Searched duckduckgo for 'test query'",
    ];

    for memory in memories {
        assert!(!memory.is_empty(), "Memory should not be empty");
        assert!(memory.len() <= 512, "Memory should be reasonable length");
    }
}

// ============================================================================
// ActionParams Tests
// ============================================================================

#[test]
fn test_action_params_get_required_str() {
    let test_data = vec![
        ("url", "https://example.com"),
        ("query", "test query"),
        ("text", "input text"),
        ("engine", "google"),
    ];

    for (key, value) in test_data {
        assert!(!key.is_empty(), "Parameter key should not be empty");
        assert!(!value.is_empty(), "Parameter value should not be empty");
    }
}

#[test]
fn test_action_params_get_required_u32() {
    let test_data = vec![("index", 1u32), ("count", 5u32), ("timeout", 10000u32)];

    for (key, value) in test_data {
        assert!(!key.is_empty(), "Parameter key should not be empty");
        assert!(value > 0, "Parameter value should be positive");
    }
}

#[test]
fn test_action_params_get_optional_bool() {
    let test_cases = vec![
        ("new_tab", Some(true)),
        ("down", Some(false)),
        ("full_page", Some(true)),
        ("optional", None),
    ];

    for (key, value) in test_cases {
        assert!(!key.is_empty(), "Parameter key should not be empty");
        assert!(
            value.is_some() || value.is_none(),
            "Parameter should be optional"
        );
    }
}

#[test]
fn test_action_params_get_optional_f64() {
    let test_cases = vec![
        ("pages", Some(1.0f64)),
        ("quality", Some(85.0)),
        ("delay", Some(500.0)),
        ("optional", None),
    ];

    for (key, value) in test_cases {
        assert!(!key.is_empty(), "Parameter key should not be empty");
        if let Some(v) = value {
            assert!(v >= 0.0, "Optional f64 should be non-negative");
        }
    }
}

// ============================================================================
// SelectorMap Tests
// ============================================================================

#[test]
fn test_selector_map_structure() {
    use browsing::dom::views::DOMInteractedElement;
    use std::collections::HashMap;

    let entry = DOMInteractedElement {
        index: 1,
        backend_node_id: Some(123),
        tag: "button".to_string(),
        text: Some("Click me".to_string()),
        attributes: HashMap::new(),
        selector: None,
    };

    assert_eq!(entry.index, 1);
    assert_eq!(entry.backend_node_id, Some(123));
    assert_eq!(entry.tag, "button");
    assert_eq!(entry.text, Some("Click me".to_string()));
}

#[test]
fn test_selector_map_validation() {
    use browsing::dom::views::DOMInteractedElement;
    use std::collections::HashMap;

    let entries = vec![
        DOMInteractedElement {
            index: 0,
            backend_node_id: Some(100),
            tag: "input".to_string(),
            text: Some("text".to_string()),
            attributes: HashMap::new(),
            selector: None,
        },
        DOMInteractedElement {
            index: 1,
            backend_node_id: Some(101),
            tag: "button".to_string(),
            text: Some("Submit".to_string()),
            attributes: HashMap::new(),
            selector: None,
        },
    ];

    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0].index, 0);
    assert_eq!(entries[1].index, 1);
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[test]
fn test_tool_error_creation() {
    let error = BrowsingError::Tool("Test tool error".to_string());

    assert!(matches!(error, BrowsingError::Tool(_)));
}

#[test]
fn test_element_not_found_error() {
    let index = 999u32;
    let error = BrowsingError::Tool(format!("Element index {} not found", index));

    assert!(matches!(error, BrowsingError::Tool(_)));
    if let BrowsingError::Tool(msg) = error {
        assert!(msg.contains("not found"));
        assert!(msg.contains("999"));
    }
}

#[test]
fn test_unsupported_search_engine_error() {
    let engine = "unknown_engine";
    let error = BrowsingError::Tool(format!(
        "Unsupported search engine: {}. Options: duckduckgo, google, bing",
        engine
    ));

    assert!(matches!(error, BrowsingError::Tool(_)));
    if let BrowsingError::Tool(msg) = error {
        assert!(msg.contains("Unsupported"));
        assert!(msg.contains("unknown_engine"));
    }
}

// ============================================================================
// Integration Test Markers
// ============================================================================

#[test]
fn test_navigation_handler_search() {
    // Test navigation handler search parameter validation
    let engines = vec!["duckduckgo", "google", "bing"];
    let query = "test query";

    for engine in engines {
        assert!(!engine.is_empty());
        assert!(!query.is_empty());

        let encoded_query = urlencoding::encode(query);
        let search_url = match engine {
            "duckduckgo" => format!("https://duckduckgo.com/?q={encoded_query}"),
            "google" => format!("https://www.google.com/search?q={encoded_query}&udm=14"),
            "bing" => format!("https://www.bing.com/search?q={encoded_query}"),
            _ => panic!("Unknown engine"),
        };

        assert!(search_url.contains(engine));
        assert!(search_url.contains("q="));
    }
}

#[test]
fn test_navigation_handler_navigate() {
    // Test navigation handler URL validation
    let test_urls = vec![
        ("https://example.com", true),
        ("http://localhost:8080", true),
        ("ftp://example.com", false),
        ("not-a-url", false),
        ("", false),
    ];

    for (url, should_be_valid) in test_urls {
        let is_valid = url.starts_with("http://") || url.starts_with("https://");
        assert_eq!(
            is_valid, should_be_valid,
            "URL {} validity check failed",
            url
        );
    }
}

#[test]
fn test_interaction_handler_click() {
    // Test interaction handler click parameter validation
    let element_indices = vec![0u32, 1, 5, 10, 100];

    for index in element_indices {
        assert!(index >= 0, "Element index must be non-negative");
    }

    // Test click action parameters
    let click_params = vec![(0, Some("left")), (5, Some("right")), (10, Some("middle"))];

    for (index, button) in click_params {
        assert!(index >= 0);
        assert!(button.is_some());
    }
}

#[test]
fn test_interaction_handler_input() {
    // Test interaction handler input parameter validation
    let test_inputs = vec![
        ("test text", true),
        ("", false),
        ("Hello, world!", true),
        ("special chars: @#$%", true),
    ];

    for (input, should_be_valid) in test_inputs {
        let is_valid = !input.is_empty();
        assert_eq!(
            is_valid, should_be_valid,
            "Input '{}' validation failed",
            input
        );
    }

    // Test input action structure
    let element_index = 5u32;
    let text = "sample text";

    assert!(element_index >= 0);
    assert!(!text.is_empty());
}

#[test]
fn test_content_handler_scroll() {
    // Test content handler scroll parameter validation
    let scroll_directions = vec!["up", "down", "left", "right"];

    for direction in scroll_directions {
        assert!(!direction.is_empty());
        assert!(direction.len() <= 10);
    }

    // Test scroll amounts
    let scroll_amounts = vec![0, 100, 500, 1000];

    for amount in scroll_amounts {
        assert!(amount >= 0);
        assert!(amount <= 10000);
    }
}

#[test]
fn test_content_handler_find_text() {
    // Test content handler find_text parameter validation
    let search_queries = vec!["example text", "search term", "multiple words"];

    for query in search_queries {
        assert!(!query.is_empty());
        assert!(query.len() > 3);
    }

    // Test text search patterns
    let text = "This is a sample text for testing find functionality";
    assert!(text.contains("sample"));
    assert!(text.contains("text"));
}

#[test]
fn test_content_handler_dropdown() {
    // Test content handler dropdown parameter validation
    let dropdown_indices = vec![0u32, 1, 2, 5, 10];

    for index in dropdown_indices {
        assert!(index >= 0);
    }

    // Test dropdown selection
    let dropdown_options = vec!["Option 1", "Option 2", "Option 3"];

    for option in dropdown_options {
        assert!(!option.is_empty());
    }
}

#[test]
fn test_tabs_handler_lifecycle() {
    // Test tabs handler lifecycle operations
    let tab_operations = vec!["create", "switch", "close"];

    for operation in tab_operations {
        assert!(!operation.is_empty());
    }

    // Test tab ID format
    let tab_ids = vec!["CDEB6E0D5C0F4D1A8B9E5C0F4D1A8B9E", "1234567890abcdef"];

    for tab_id in tab_ids {
        assert!(!tab_id.is_empty());
        assert!(tab_id.len() >= 16);
    }
}