viewpoint-core 0.4.3

High-level browser automation API for Viewpoint
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
#![cfg(feature = "integration")]

//! ARIA snapshot performance tests for viewpoint-core.
//!
//! These tests verify the performance optimizations for snapshot capture:
//! - Parallel node resolution
//! - Batch array element access
//! - Parallel frame capture
//! - SnapshotOptions configuration

use std::sync::Once;
use std::time::{Duration, Instant};

use viewpoint_core::{Browser, SnapshotOptions};

static TRACING_INIT: Once = Once::new();

/// Initialize tracing for tests.
fn init_tracing() {
    TRACING_INIT.call_once(|| {
        tracing_subscriber::fmt()
            .with_env_filter(
                tracing_subscriber::EnvFilter::from_default_env()
                    .add_directive(tracing::Level::INFO.into()),
            )
            .with_test_writer()
            .try_init()
            .ok();
    });
}

// =============================================================================
// Large DOM Performance Tests
// =============================================================================

/// Test snapshot capture on a page with 100+ elements completes in reasonable time.
#[tokio::test]
async fn test_large_dom_snapshot_performance() {
    init_tracing();

    let browser = Browser::launch()
        .headless(true)
        .launch()
        .await
        .expect("Failed to launch browser");

    let context = browser
        .new_context()
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    // Generate a page with 100+ interactive elements
    let mut html = String::from("<html><body><h1>Performance Test</h1>\n");
    for i in 0..100 {
        html.push_str(&format!("<button id=\"btn{i}\">Button {i}</button>\n"));
    }
    html.push_str("</body></html>");

    page.set_content(&html)
        .set()
        .await
        .expect("Failed to set content");

    // Time the snapshot capture
    let start = Instant::now();
    let snapshot = page.aria_snapshot().await.expect("Failed to get snapshot");
    let duration = start.elapsed();

    println!("Large DOM snapshot captured in {duration:?}");
    println!("Snapshot has {} children at root", snapshot.children.len());

    // Verify the snapshot contains our buttons (check for refs in new format)
    let yaml = snapshot.to_yaml();
    assert!(
        yaml.contains("[ref=c") && yaml.contains('p') && yaml.contains('e'),
        "Snapshot should contain element refs in format c{{ctx}}p{{page}}e{{counter}}"
    );

    // Performance expectation: should complete in under 5 seconds
    // (With sequential processing of 100+ elements at 1-5ms each, this could be 500ms+)
    // With parallel processing, should be much faster
    assert!(
        duration < Duration::from_secs(5),
        "Snapshot should complete in under 5 seconds, took {duration:?}"
    );

    // Clean up
    browser.close().await.expect("Failed to close browser");
}

/// Test snapshot with include_refs: false is faster.
#[tokio::test]
async fn test_snapshot_without_refs_performance() {
    init_tracing();

    let browser = Browser::launch()
        .headless(true)
        .launch()
        .await
        .expect("Failed to launch browser");

    let context = browser
        .new_context()
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    // Generate a page with 100 elements
    let mut html = String::from("<html><body>\n");
    for i in 0..100 {
        html.push_str(&format!("<button>Button {i}</button>\n"));
    }
    html.push_str("</body></html>");

    page.set_content(&html)
        .set()
        .await
        .expect("Failed to set content");

    // Time snapshot WITH refs
    let start_with_refs = Instant::now();
    let snapshot_with_refs = page.aria_snapshot().await.expect("Failed to get snapshot");
    let duration_with_refs = start_with_refs.elapsed();

    // Time snapshot WITHOUT refs
    let options = SnapshotOptions::default().include_refs(false);
    let start_without_refs = Instant::now();
    let snapshot_without_refs = page
        .aria_snapshot_with_options(options)
        .await
        .expect("Failed to get snapshot");
    let duration_without_refs = start_without_refs.elapsed();

    println!("Snapshot WITH refs: {duration_with_refs:?}");
    println!("Snapshot WITHOUT refs: {duration_without_refs:?}");

    // Verify refs are present/absent as expected
    let yaml_with = snapshot_with_refs.to_yaml();
    let _yaml_without = snapshot_without_refs.to_yaml();

    assert!(
        yaml_with.contains("[ref=c") && yaml_with.contains('p') && yaml_with.contains('e'),
        "Snapshot with refs should contain refs in format c{{ctx}}p{{page}}e{{counter}}"
    );
    // Without refs, the snapshot should not have refs
    // (The node_ref field will be None for all nodes)

    // Without refs should be faster (or at least not slower)
    // We don't assert this strictly since timing can be variable,
    // but we log for manual verification
    if duration_without_refs < duration_with_refs {
        println!(
            "Without refs was {:?} faster",
            duration_with_refs
                .checked_sub(duration_without_refs)
                .unwrap()
        );
    }

    // Clean up
    browser.close().await.expect("Failed to close browser");
}

// =============================================================================
// Multi-Frame Parallel Capture Tests
// =============================================================================

/// Test parallel frame capture with multiple iframes.
#[tokio::test]
async fn test_multi_frame_parallel_capture() {
    init_tracing();

    let browser = Browser::launch()
        .headless(true)
        .launch()
        .await
        .expect("Failed to launch browser");

    let context = browser
        .new_context()
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    // Create a page with 5 iframes, each with some content
    let html = r#"
        <html><body>
            <h1>Multi-Frame Test</h1>
            <iframe name="frame1" srcdoc="<html><body><button>Frame 1 Button</button></body></html>"></iframe>
            <iframe name="frame2" srcdoc="<html><body><button>Frame 2 Button</button></body></html>"></iframe>
            <iframe name="frame3" srcdoc="<html><body><button>Frame 3 Button</button></body></html>"></iframe>
            <iframe name="frame4" srcdoc="<html><body><button>Frame 4 Button</button></body></html>"></iframe>
            <iframe name="frame5" srcdoc="<html><body><button>Frame 5 Button</button></body></html>"></iframe>
        </body></html>
    "#;

    page.set_content(html)
        .set()
        .await
        .expect("Failed to set content");

    // Wait for iframes to load
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Time the multi-frame snapshot
    let start = Instant::now();
    let snapshot = page
        .aria_snapshot_with_frames()
        .await
        .expect("Failed to get multi-frame snapshot");
    let duration = start.elapsed();

    println!("Multi-frame snapshot captured in {duration:?}");

    let yaml = snapshot.to_yaml();
    println!("Multi-frame snapshot:\n{yaml}");

    // Verify all frames were captured (should see content from multiple frames)
    // With parallel capture, this should be faster than sequential

    // Performance expectation: should complete in under 5 seconds
    assert!(
        duration < Duration::from_secs(5),
        "Multi-frame snapshot should complete in under 5 seconds, took {duration:?}"
    );

    // Clean up
    browser.close().await.expect("Failed to close browser");
}

// =============================================================================
// SnapshotOptions Configuration Tests
// =============================================================================

/// Test SnapshotOptions::max_concurrency configuration.
#[tokio::test]
async fn test_snapshot_options_max_concurrency() {
    init_tracing();

    let browser = Browser::launch()
        .headless(true)
        .launch()
        .await
        .expect("Failed to launch browser");

    let context = browser
        .new_context()
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    // Generate a page with 50 elements
    let mut html = String::from("<html><body>\n");
    for i in 0..50 {
        html.push_str(&format!("<button>Button {i}</button>\n"));
    }
    html.push_str("</body></html>");

    page.set_content(&html)
        .set()
        .await
        .expect("Failed to set content");

    // Test with low concurrency
    let options_low = SnapshotOptions::default().max_concurrency(5);
    let start_low = Instant::now();
    let _ = page
        .aria_snapshot_with_options(options_low)
        .await
        .expect("Failed to get snapshot");
    let duration_low = start_low.elapsed();

    // Test with high concurrency
    let options_high = SnapshotOptions::default().max_concurrency(100);
    let start_high = Instant::now();
    let _ = page
        .aria_snapshot_with_options(options_high)
        .await
        .expect("Failed to get snapshot");
    let duration_high = start_high.elapsed();

    println!("Low concurrency (5): {duration_low:?}");
    println!("High concurrency (100): {duration_high:?}");

    // Both should complete successfully
    // Higher concurrency should generally be faster, but we don't assert
    // strictly due to timing variability

    // Clean up
    browser.close().await.expect("Failed to close browser");
}

/// Test SnapshotOptions::include_refs configuration.
#[tokio::test]
async fn test_snapshot_options_include_refs_false() {
    init_tracing();

    let browser = Browser::launch()
        .headless(true)
        .launch()
        .await
        .expect("Failed to launch browser");

    let context = browser
        .new_context()
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    page.set_content(
        r##"
        <html><body>
            <button id="btn1">Button 1</button>
            <button id="btn2">Button 2</button>
            <a href="#">Link</a>
        </body></html>
    "##,
    )
    .set()
    .await
    .expect("Failed to set content");

    // Capture without refs
    let options = SnapshotOptions::default().include_refs(false);
    let snapshot = page
        .aria_snapshot_with_options(options)
        .await
        .expect("Failed to get snapshot");

    // Verify structure is still captured
    let yaml = snapshot.to_yaml();
    println!("Snapshot without refs:\n{yaml}");

    // Should have the elements but no refs
    assert!(
        yaml.contains("button") || yaml.contains("link"),
        "Snapshot should still contain elements, got: {yaml}"
    );

    // Check that node_ref is None on root (since we skipped ref resolution)
    assert!(
        snapshot.node_ref.is_none(),
        "Root node_ref should be None when include_refs is false"
    );

    // Clean up
    browser.close().await.expect("Failed to close browser");
}

/// Test Frame::aria_snapshot_with_options.
#[tokio::test]
async fn test_frame_snapshot_with_options() {
    init_tracing();

    let browser = Browser::launch()
        .headless(true)
        .launch()
        .await
        .expect("Failed to launch browser");

    let context = browser
        .new_context()
        .await
        .expect("Failed to create context");
    let page = context.new_page().await.expect("Failed to create page");

    page.set_content(
        r#"
        <html><body>
            <h1>Main Page</h1>
            <iframe name="contentframe" srcdoc="<html><body><button>Frame Button</button></body></html>"></iframe>
        </body></html>
    "#,
    )
    .set()
    .await
    .expect("Failed to set content");

    // Wait for iframe to load
    tokio::time::sleep(Duration::from_millis(300)).await;

    // Get the content frame
    let frames = page.frames().await.expect("Failed to get frames");
    let content_frame = frames
        .iter()
        .find(|f| f.name() == "contentframe")
        .expect("Should find content frame");

    // Capture frame snapshot without refs
    let options = SnapshotOptions::default().include_refs(false);
    let snapshot = content_frame
        .aria_snapshot_with_options(options)
        .await
        .expect("Failed to get frame snapshot");

    let yaml = snapshot.to_yaml();
    println!("Frame snapshot without refs:\n{yaml}");

    // Should have structure but no refs
    assert!(
        yaml.contains("button"),
        "Frame snapshot should contain button"
    );

    // Clean up
    browser.close().await.expect("Failed to close browser");
}