### Example Searches Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/enum.TestError_search= Demonstrates example search queries that can be performed. ```APIDOC ## GET /examples/searches ### Description Provides example search queries for demonstration purposes. ### Method GET ### Endpoint /examples/searches ### Parameters #### No parameters required. ### Request Example ```json { "request": "No body needed for this request" } ``` ### Response #### Success Response (200) - **search_examples** (array) - A list of example search queries. #### Response Example ```json { "search_examples": [ "std::vec", "u32 -> bool", "Option, (T -> U) -> Option" ] } ``` ``` -------------------------------- ### Example Searches (Text) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/expect/struct.LocatorAssertions_search= Common patterns for example searches within the system. These examples demonstrate how users can query for specific types, type conversions, and functional transformations. ```text * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Basic TestHarness Usage Example (Rust) Source: https://docs.rs/viewpoint-test/latest/src/viewpoint_test/harness/mod.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A minimal example demonstrating the basic usage of TestHarness. It launches a browser, navigates to a URL, and asserts the outcome. The harness automatically handles cleanup upon completion. ```Rust use viewpoint_test::TestHarness; #[tokio::test] async fn my_test() -> Result<(), Box> { let harness = TestHarness::new().await?; let page = harness.page(); page.goto("https://example.com").goto().await?; Ok(()) } ``` -------------------------------- ### Basic TestHarness Usage Example Source: https://docs.rs/viewpoint-test/latest/src/viewpoint_test/harness/mod.rs A simple example demonstrating the core functionality of `TestHarness`. It initializes a new harness, gets a page object, navigates to a URL, and relies on the harness's `Drop` implementation for automatic cleanup. ```rust use viewpoint_test::TestHarness; #[tokio::test] async fn my_test() -> Result<(), Box> { let harness = TestHarness::new().await?; let page = harness.page(); page.goto("https://example.com").goto().await?; Ok(()) // harness drops and cleans up } ``` -------------------------------- ### Start Tracing with Options (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=u32+-%3E+bool Initiates the recording of test execution traces, including optional screenshots and DOM snapshots, for debugging purposes. Tracing requires at least one page to exist in the context before it can be started. The tracing state is shared across multiple `tracing()` calls within the same context. ```rust use viewpoint_core::context::TracingOptions; // Create a page first (required before starting tracing) let page = context.new_page().await.unwrap(); // Start tracing with screenshots and snapshots context.tracing().start( TracingOptions::new() .screenshots(true) .snapshots(true) ).await.unwrap(); // Perform test actions page.goto("https://example.com").await.unwrap(); ``` -------------------------------- ### Example: HAR Routing with Options Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=u32+-%3E+bool Shows how to use `route_from_har_with_options` to route requests from 'recordings/api.har' with specific options, such as filtering by URL pattern. ```Rust use viewpoint_core::{Browser, network::HarReplayOptions}; let browser = Browser::launch().headless(true).launch().await?; let context = browser.new_context().await?; // With options context.route_from_har_with_options( "recordings/api.har", HarReplayOptions::new() .url("**/api/**") .strict(true) ).await?; ``` -------------------------------- ### Example: Using aria_snapshot_with_frames Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page Demonstrates how to use the `aria_snapshot_with_frames` method to capture an ARIA snapshot and then interact with an element inside an iframe using its reference. It shows how to print the snapshot and provides a commented-out example of clicking an element by its reference. ```rust use viewpoint_core::Page; let snapshot = page.aria_snapshot_with_frames().await?; // The snapshot YAML output will show frame content inline: // - document "Main Page" // - heading "Title" // - iframe "Widget Frame" [frame-boundary] // - document "Widget" // - button "Click me" [ref=c0p0f1e1] println!("{}", snapshot); // You can interact with elements inside iframes using their refs: // page.locator_from_ref("c0p0f1e1").click().await?; ``` -------------------------------- ### Get Page Count in Browser Context (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=std%3A%3Avec This Rust example provides a concise way to get the number of pages currently open within a browser context. It's a performance optimization over fetching all pages just to count them. ```rust use viewpoint_core::BrowserContext; let count = context.page_count().await?; println!("Number of pages: {}", count); ``` -------------------------------- ### Rust Search Examples Source: https://docs.rs/viewpoint-test/latest/src/viewpoint_test/expect/soft_locator.rs_search= Provides examples of common search queries for Rust, focusing on standard library types and type transformations. These examples are useful for understanding generic type manipulation and function signatures. ```text std::vec u32 -> bool Option, (T -> U) -> Option ``` -------------------------------- ### Download Event Handler Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=u32+-%3E+bool Set up a handler to be notified when a file download starts. This allows for programmatic interaction with downloads. ```APIDOC ## POST /page/download/handler ### Description Sets a handler for file download events. This function is called whenever a download process is initiated. ### Method POST ### Endpoint /page/download/handler ### Parameters #### Query Parameters - **handler** (Function) - Required - A function that takes a `Download` object and returns a `Future`. ### Request Body ```json { "handler": "async (download) => { console.log('Download started:', download.url()); }" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates the handler was set successfully. #### Response Example ```json { "message": "Download handler set." } ``` --- ## DELETE /page/download/handler ### Description Removes the currently set download event handler. No further notifications for download events will be sent. ### Method DELETE ### Endpoint /page/download/handler ### Response #### Success Response (200) - **message** (string) - Indicates the handler was removed successfully. #### Response Example ```json { "message": "Download handler removed." } ``` ``` -------------------------------- ### Rust: Example Usage of Expect API Source: https://docs.rs/viewpoint-test/latest/src/viewpoint_test/expect/mod.rs_search= Demonstrates how to use the `expect` and `expect_page` functions for asserting element visibility, text content, and page URL/title in browser automation tests. This example requires the `integration` feature to be enabled. ```rust # #[cfg(feature = "integration")] # tokio_test::block_on(async { # use viewpoint_core::Browser; use viewpoint_test::{expect, expect_page}; # let browser = Browser::launch().headless(true).launch().await.unwrap(); # let context = browser.new_context().await.unwrap(); # let page = context.new_page().await.unwrap(); # page.goto("https://example.com").goto().await.unwrap(); // Assert element is visible let locator = page.locator("h1"); expect(&locator).to_be_visible().await.unwrap(); // Assert text content expect(&locator).to_have_text("Example Domain").await.unwrap(); // Assert page URL expect_page(&page).to_have_url("https://example.com/").await.unwrap(); # }); ``` -------------------------------- ### Example: Simple HAR Routing Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search= Demonstrates basic network request routing from a HAR file using `route_from_har` in Rust. All requests matching entries in 'recordings/api.har' will be replayed. ```rust use viewpoint_core::{Browser, network::HarReplayOptions}; let browser = Browser::launch().headless(true).launch().await?; let context = browser.new_context().await?; // Simple HAR routing for all pages context.route_from_har("recordings/api.har").await?; ``` -------------------------------- ### Get All Context-Level Initialization Scripts (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves a list of all initialization scripts that are currently set to be applied to all new pages within the browser context. These are the scripts that will execute before any page-specific scripts. ```rust let scripts = context.init_scripts().await?; ``` -------------------------------- ### Example: Using aria_snapshot_with_frames_and_options Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page Illustrates how to use `aria_snapshot_with_frames_and_options` with custom settings. This example shows disabling reference inclusion in the snapshot by creating a `SnapshotOptions` object with `include_refs(false)` for potentially faster capture. ```rust use viewpoint_core::{Page, SnapshotOptions}; // Skip ref resolution for faster capture let options = SnapshotOptions::default().include_refs(false); let snapshot = page.aria_snapshot_with_frames_and_options(options).await?; ``` -------------------------------- ### Example: HAR Routing with Options (URL Filter) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search= Shows how to use `route_from_har_with_options` in Rust to replay requests from a HAR file, but only for URLs matching a specific pattern ('**/api/**'). ```rust use viewpoint_core::{Browser, network::HarReplayOptions}; let browser = Browser::launch().headless(true).launch().await?; let context = browser.new_context().await?; // URL filter: only match specific URLs context.route_from_har_with_options( "api.har", HarReplayOptions::new().url("**/api/**") ).await?; ``` -------------------------------- ### Get Context-Level Initialization Scripts (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search= Retrieves a list of all context-level initialization scripts that are configured to be applied to all new pages. This function returns the registered scripts as strings. ```rust pub async fn init_scripts(&self) -> Vec ``` -------------------------------- ### Example: HAR Routing with Options (Original Timing) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search= Illustrates using `route_from_har_with_options` in Rust to replay HAR entries while preserving their original timing using `use_original_timing(true)`. ```rust use viewpoint_core::{Browser, network::HarReplayOptions}; let browser = Browser::launch().headless(true).launch().await?; let context = browser.new_context().await?; // Simulate original timing context.route_from_har_with_options( "api.har", HarReplayOptions::new().use_original_timing(true) ).await?; ``` -------------------------------- ### Handle Download Events in Rust Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=u32+-%3E+bool Sets up a handler for file download events. This handler is invoked when a download is initiated, allowing for actions to be taken upon download start. ```rust use viewpoint_core::Page; page.on_download(|download| async move { // Handler logic here, e.g., getting the download path }).await; ``` -------------------------------- ### Example: Block Analytics Requests Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search= Demonstrates blocking all requests matching the pattern '**/analytics/**' using the `route` function in Rust. It utilizes `route.abort().await` to prevent the requests from being sent. ```rust use viewpoint_core::{Browser, network::Route}; let browser = Browser::launch().headless(true).launch().await?; let context = browser.new_context().await?; // Block all analytics requests for all pages context.route("**/analytics/**", |route: Route| async move { route.abort().await }).await?; ``` -------------------------------- ### Quick Start: Basic Test with TestHarness Source: https://docs.rs/viewpoint-test/latest/viewpoint_test Demonstrates how to set up a basic test using the TestHarness, navigate to a URL, and perform element assertions. Requires `tokio` for async execution. ```rust use viewpoint_test::{TestHarness, expect}; #[tokio::test] async fn my_test() -> Result<(), Box> { let harness = TestHarness::new().await?; let page = harness.page(); page.goto("https://example.com").goto().await?; // Assert element is visible expect(page.locator("h1")).to_be_visible().await?; // Assert element has text expect(page.locator("h1")).to_have_text("Example Domain").await?; Ok(()) // harness drops and cleans up automatically } ``` -------------------------------- ### Get Frame by Name with Page.frame Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page This example shows how to get a specific frame by its name attribute. If a frame with the given name exists, it returns `Some(Frame)`; otherwise, it returns `None`. This is useful for targeting frames with known names, like 'payment-frame'. ```rust use viewpoint_core::Page; if let Some(frame) = page.frame("payment-frame").await? { frame.goto("https://payment.example.com").await?; } ``` -------------------------------- ### Get Browser Context Tracing Controller (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search= Provides access to a tracing controller for recording test execution traces, including screenshots, DOM snapshots, and network activity. These traces are compatible with Playwright's Trace Viewer and are essential for debugging test failures. Note that at least one page must exist before starting tracing. ```rust pub fn tracing(&self) -> Tracing ``` -------------------------------- ### Quick Start: Basic Test Harness Usage Source: https://docs.rs/viewpoint-test/latest/index Demonstrates the fundamental usage of the TestHarness for setting up a browser, navigating to a page, and performing basic locator assertions like visibility and text content. ```rust use viewpoint_test::{TestHarness, expect}; #[tokio::test] async fn my_test() -> Result<(), Box> { let harness = TestHarness::new().await?; let page = harness.page(); page.goto("https://example.com").goto().await?; // Assert element is visible expect(page.locator("h1")).to_be_visible().await?; // Assert element has text expect(page.locator("h1")).to_have_text("Example Domain").await?; Ok(()) } ``` -------------------------------- ### Browser Launch and Connection Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Browser Methods for launching a new browser instance or connecting to an existing one. ```APIDOC ## POST /Browser/launch ### Description Launches a new browser instance using a builder pattern. Allows configuring headless mode and other launch options before the actual launch. ### Method POST ### Endpoint /Browser/launch ### Parameters #### Query Parameters - **headless** (boolean) - Optional - Whether to run the browser in headless mode. #### Request Body (Not applicable for launch builder initiation) ### Request Example ```rust use viewpoint_core::Browser; let browser = Browser::launch() .headless(true) .launch() .await?; ``` ### Response #### Success Response (200) - **Browser** (object) - An instance of the launched browser. #### Response Example ```json { "browser_instance_id": "some_browser_id" } ``` ## POST /Browser/connect ### Description Connects to an already running browser instance via its WebSocket URL. ### Method POST ### Endpoint /Browser/connect ### Parameters #### Query Parameters - **ws_url** (string) - Required - The WebSocket URL of the running browser. #### Request Body (Not applicable) ### Request Example ```rust use viewpoint_core::Browser; let browser = Browser::connect("ws://localhost:9222/devtools/browser/...").await?; ``` ### Response #### Success Response (200) - **Browser** (object) - An instance representing the connected browser. #### Response Example ```json { "browser_instance_id": "connected_browser_id" } ``` ## POST /Browser/connect_over_cdp ### Description Connects to an already running browser via an HTTP endpoint or WebSocket URL. Auto-discovers the WebSocket URL if an HTTP endpoint is provided. ### Method POST ### Endpoint /Browser/connect_over_cdp ### Parameters #### Query Parameters - **endpoint_url** (string) - Required - The HTTP endpoint or WebSocket URL of the browser. - **timeout** (Duration) - Optional - Custom connection timeout. - **headers** (map) - Optional - Custom headers to include in the connection request. #### Request Body (Not applicable for builder initiation) ### Request Example ```rust use viewpoint_core::Browser; use std::time::Duration; // Connect via HTTP endpoint let browser = Browser::connect_over_cdp("http://localhost:9222") .connect() .await?; // With custom timeout and headers let browser = Browser::connect_over_cdp("http://localhost:9222") .timeout(Duration::from_secs(10)) .header("Authorization", "Bearer token") .connect() .await?; ``` ### Response #### Success Response (200) - **Browser** (object) - An instance representing the connected browser. #### Response Example ```json { "browser_instance_id": "cdp_connected_browser_id" } ``` ``` -------------------------------- ### Expect and Handle Downloads with Page.expect_download Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page This example shows how to wait for and retrieve a `Download` object triggered by a specific action. The `action` closure should perform the necessary steps to initiate a download. The downloaded file can then be saved using methods on the `Download` object. ```rust use viewpoint_core::Page; let mut download = page.expect_download(|| async { page.locator("a.download").click().await?; Ok(()) }).await?; download.save_as("./my-file.pdf").await?; ``` -------------------------------- ### Example: Using SoftAssertions with a Page in Rust Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/expect/struct.SoftAssertions_search= Illustrates how to use `SoftAssertions` to perform assertions on a `Page`. This example checks the page's URL and then asserts all collected failures. ```Rust use viewpoint_test::SoftAssertions; let soft = SoftAssertions::new(); soft.expect_page(&page).to_have_url("https://example.com/").await; soft.assert_all().unwrap(); ``` -------------------------------- ### Get Context ID (via context_id method) (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=std%3A%3Avec Retrieves the context ID using the `context_id` method. This is an alternative way to get the context's identifier. ```rust let context_id_str = context.context_id(); ``` -------------------------------- ### Browser Launching and Connecting Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Browser_search=u32+-%3E+bool Methods for launching new browser instances or connecting to existing ones. ```APIDOC ## Browser Struct A browser instance connected via CDP. The `Browser` struct represents a connection to a Chromium-based browser. It can be obtained by: * `Browser::launch()` - Spawn and connect to a new browser process * `Browser::connect()` - Connect to an existing browser via WebSocket URL * `Browser::connect_over_cdp()` - Connect via HTTP endpoint (auto-discovers WebSocket) ### Method: Browser::launch #### Description Create a browser builder for launching a new browser. #### Method `pub fn launch() -> BrowserBuilder` #### Example ```rust use viewpoint_core::Browser; let browser = Browser::launch() .headless(true) .launch() .await?; ``` ### Method: Browser::connect #### Description Connect to an already-running browser via WebSocket URL. #### Method `pub async fn connect(ws_url: &str) -> Result` #### Parameters ##### Query Parameters - **ws_url** (string) - Required - The WebSocket URL of the running browser. #### Example ```rust use viewpoint_core::Browser; let browser = Browser::connect("ws://localhost:9222/devtools/browser/...").await?; ``` #### Errors Returns an error if the connection fails. ### Method: Browser::connect_over_cdp #### Description Connect to an already-running browser via HTTP endpoint or WebSocket URL. This method supports both HTTP endpoint URLs (e.g., `http://localhost:9222`) and WebSocket URLs (e.g., `ws://localhost:9222/devtools/browser/...`). For HTTP endpoints, it auto-discovers the WebSocket URL. #### Method `pub fn connect_over_cdp( endpoint_url: impl Into, ) -> ConnectOverCdpBuilder` #### Parameters ##### Path Parameters - **endpoint_url** (string) - Required - The HTTP or WebSocket endpoint URL of the browser. #### Example ```rust use viewpoint_core::Browser; use std::time::Duration; // Connect via HTTP endpoint let browser = Browser::connect_over_cdp("http://localhost:9222") .connect() .await?; // With custom timeout and headers let browser = Browser::connect_over_cdp("http://localhost:9222") .timeout(Duration::from_secs(10)) .header("Authorization", "Bearer token") .connect() .await?; // Access existing browser contexts and pages let contexts = browser.contexts().await?; for context in contexts { let pages = context.pages().await?; for page in &pages { println!("Found page: {}", page.target_id()); } } ``` ``` -------------------------------- ### Add Initialization Script from Path Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=u32+-%3E+bool Adds an initialization script from a specified file path. Errors if the file cannot be read or the script added. ```APIDOC ## POST /websites/rs_viewpoint-test/add_init_script_path ### Description Adds an initialization script from a given file path. This script will be evaluated before every page load. ### Method POST ### Endpoint /websites/rs_viewpoint-test/add_init_script_path ### Parameters #### Request Body - **path** (string) - Required - The file path to the JavaScript script. ### Request Example ```javascript page.add_init_script_path("/path/to/your/script.js").await; ``` ### Response #### Success Response (200) - **script_id** (string) - The unique identifier for the added script. #### Response Example ```json { "script_id": "init_script_456" } ``` #### Error Handling Returns an error if the file cannot be read or the script cannot be added. ``` -------------------------------- ### Browser Launch API Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Browser_search= Provides methods to launch and connect to a browser instance. This includes spawning a new browser process or connecting to an existing one. ```APIDOC ## POST /Browser/launch ### Description Spawns and connects to a new browser process. Returns a `BrowserBuilder` to configure launch options. ### Method GET ### Endpoint N/A (Method Call) ### Parameters None ### Request Example ```rust use viewpoint_core::Browser; let browser = Browser::launch() .headless(true) .launch() .await?; ``` ### Response #### Success Response (200) - **Browser** (object) - An instance of the connected browser. #### Response Example ```json { "browser_instance": "" } ``` ``` ```APIDOC ## POST /Browser/connect ### Description Connects to an already-running browser via a WebSocket URL. ### Method GET ### Endpoint N/A (Method Call) ### Parameters #### Query Parameters - **ws_url** (string) - Required - The WebSocket URL of the running browser. ### Request Example ```rust use viewpoint_core::Browser; let browser = Browser::connect("ws://localhost:9222/devtools/browser/...").await?; ``` ### Response #### Success Response (200) - **Browser** (object) - An instance of the connected browser. #### Response Example ```json { "browser_instance": "" } ``` #### Errors - **BrowserError** - Returned if the connection fails. ``` ```APIDOC ## POST /Browser/connect_over_cdp ### Description Connects to an already-running browser via an HTTP endpoint or WebSocket URL. Auto-discovers WebSocket URL for HTTP endpoints. ### Method GET ### Endpoint N/A (Method Call) ### Parameters #### Path Parameters - **endpoint_url** (string) - Required - The HTTP or WebSocket URL of the browser endpoint. #### Query Parameters - **timeout** (Duration) - Optional - Custom connection timeout. - **header** (string, string) - Optional - Custom headers to include in the connection request. ### Request Example ```rust use viewpoint_core::Browser; use std::time::Duration; // Connect via HTTP endpoint let browser = Browser::connect_over_cdp("http://localhost:9222") .connect() .await?; // With custom timeout and headers let browser = Browser::connect_over_cdp("http://localhost:9222") .timeout(Duration::from_secs(10)) .header("Authorization", "Bearer token") .connect() .await?; ``` ### Response #### Success Response (200) - **Browser** (object) - An instance of the connected browser. #### Response Example ```json { "browser_instance": "" } ``` ``` -------------------------------- ### Get Selected Values by Backend ID (JavaScript) Source: https://docs.rs/viewpoint-test/latest/src/viewpoint_test/expect/locator_helpers.rs_search=std%3A%3Avec Calls a JavaScript function on a specific element identified by its backend node ID to get its selected values. This is useful when the element is already known and referenced directly, especially in scenarios involving CDP. ```Rust let js_fn = js! { (function() { const el = this; if (el.tagName.toLowerCase() !== "select") { return { values: [el.value || ""] }; } const values = []; for (const opt of el.selectedOptions) { values.push(opt.value); } return { values: values }; }) }; // Strip outer parentheses for CDP functionDeclaration let js_fn = js_fn.trim_start_matches('(').trim_end_matches(')'); let result = call_function_on_backend_id(page, backend_node_id, js_fn).await?; Ok(result .get("values") .and_then(|v| v.as_array()) .map(|arr| { arr.iter() .filter_map(|v| v.as_str()) .map(std::string::ToString::to_string) .collect() }) .unwrap_or_default()) ``` -------------------------------- ### Rust Example: Using expect_page assertions Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/expect/fn.expect_page_search=std%3A%3Avec Demonstrates how to use the `expect_page` function to create assertions for a page's URL and title. Requires the `viewpoint_test` crate and uses `await` and `unwrap` for asynchronous operations. ```rust use viewpoint_test::expect_page; expect_page(&page).to_have_url("https://example.com/").await.unwrap(); expect_page(&page).to_have_title("Example Domain").await.unwrap(); ``` -------------------------------- ### Get Selected Values by Backend ID (Rust) Source: https://docs.rs/viewpoint-test/latest/src/viewpoint_test/expect/locator_helpers.rs Retrieves the selected values from a select element or the value of a non-select element using its backend node ID. It executes JavaScript to get the values and handles potential errors. Dependencies include `viewpoint_core::Page` and `AssertionError`. ```rust async fn get_selected_values_by_backend_id( page: &viewpoint_core::Page, backend_node_id: BackendNodeId, ) -> Result, AssertionError> { let js_fn = js! { (function() { const el = this; if (el.tagName.toLowerCase() !== "select") { return { values: [el.value || ""] }; } const values = []; for (const opt of el.selectedOptions) { values.push(opt.value); } return { values: values }; }) }; // Strip outer parentheses for CDP functionDeclaration let js_fn = js_fn.trim_start_matches('(').trim_end_matches(')'); let result = call_function_on_backend_id(page, backend_node_id, js_fn).await?; Ok(result .get("values") .and_then(|v| v.as_array()) .map(|arr| { arr.iter() .filter_map(|v| v.as_str()) .map(std::string::ToString::to_string) .collect() }) .unwrap_or_default()) } ``` -------------------------------- ### CloneToUninit API Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/enum.DocumentLoadState_search=std%3A%3Avec Documentation for the `clone_to_uninit` method, which performs copy-assignment from self to a destination pointer. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method `unsafe fn` ### Endpoint N/A (This is a trait method, not a web endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) N/A #### Response Example None ``` -------------------------------- ### Get Input Value by Backend ID - Rust Source: https://docs.rs/viewpoint-test/latest/src/viewpoint_test/expect/locator_helpers.rs_search= An internal helper function to get the value of an input element using its BackendNodeId. It executes JavaScript to retrieve the 'value' property of the element. This is typically used after resolving a reference or a backend node ID to a specific element. ```Rust /// Get input value by backend node ID. async fn get_input_value_by_backend_id( page: &viewpoint_core::Page, backend_node_id: BackendNodeId, ) -> Result { let js_fn = js! { (function() { return { value: this.value || "" }; }) }; // Strip outer parentheses for CDP functionDeclaration let js_fn = js_fn.trim_start_matches('(').trim_end_matches(')'); let result = call_function_on_backend_id(page, backend_node_id, js_fn).await?; Ok(result .get("value") .and_then(|v| v.as_str()) .unwrap_or("") .to_string()) } ``` -------------------------------- ### Element Interaction from Reference Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=std%3A%3Avec Methods to get an ElementHandle or a Locator from a snapshot reference string. ```APIDOC ## POST /websites/rs_viewpoint-test/element_from_ref ### Description Get an element handle from a snapshot ref. This resolves the ref (format: `c{contextIndex}p{pageIndex}f{frameIndex}e{counter}`) to an `ElementHandle` that can be used for low-level DOM operations. ### Method POST ### Endpoint `/websites/rs_viewpoint-test/element_from_ref` ### Parameters #### Path Parameters - **ref_str** (string) - Required - The element ref from an ARIA snapshot (e.g., `c0p0f0e1`) ### Request Example ```json { "ref_str": "c0p0f0e1" } ``` ### Response #### Success Response (200) - **ElementHandle** - A handle to the DOM element. #### Response Example ```json { "handle": "" } ``` ## POST /websites/rs_viewpoint-test/locator_from_ref ### Description Create a locator from a snapshot ref. This creates a `Locator` that targets the element identified by the ref. Unlike `element_from_ref`, the locator provides auto-waiting behavior and is the preferred way to interact with elements. ### Method POST ### Endpoint `/websites/rs_viewpoint-test/locator_from_ref` ### Parameters #### Path Parameters - **ref_str** (string) - Required - The element ref from an ARIA snapshot (e.g., `c0p0f0e1`) ### Request Example ```json { "ref_str": "c0p0f0e1" } ``` ### Response #### Success Response (200) - **Locator** - A locator targeting the specified element. #### Response Example ```json { "locator": "" } ``` ## POST /websites/rs_viewpoint-test/get_backend_node_id_for_ref ### Description Get the backend node ID for a ref from the ref map. This is used by `element_from_ref` and `locator_from_ref` to lookup the backendNodeId for a ref captured during `aria_snapshot()`. ### Method POST ### Endpoint `/websites/rs_viewpoint-test/get_backend_node_id_for_ref` ### Parameters #### Path Parameters - **ref_str** (string) - Required - The element ref from an ARIA snapshot (e.g., `c0p0f0e1`) ### Request Example ```json { "ref_str": "c0p0f0e1" } ``` ### Response #### Success Response (200) - **backend_node_id** (integer) - The backend node ID for the ref. #### Response Example ```json { "backend_node_id": 12345 } ``` ``` -------------------------------- ### Download Handling Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=std%3A%3Avec Set up a handler that is invoked whenever a file download process begins on the page. ```APIDOC ## POST /page/on_download ### Description Sets a handler for file downloads. The handler will be called whenever a download starts. ### Method POST ### Endpoint /page/on_download ### Parameters #### Request Body - **handler** (function) - Required - A callback function that accepts a `Download` object and returns a `Future`. ### Request Example ```json { "handler": "download => async move { println!(\"Download started: {}\", download.url()); }" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates success. ``` -------------------------------- ### Get BrowserContext ID Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the unique identifier string for the browser context. ```Rust let context_id = context.id(); ``` -------------------------------- ### Add Initialization Script from File Path (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Adds an initialization script to all pages within the context by reading its content from a specified file path. The script is registered to run before any page scripts and persists across all pages created in the context. ```rust use viewpoint_core::Browser; let browser = Browser::launch().headless(true).launch().await?; let context = browser.new_context().await?; context.add_init_script_path("./scripts/mock-auth.js").await?; ``` -------------------------------- ### Navigate to URL with Viewpoint Core Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page Demonstrates navigating to a URL using the `goto` method, with options for waiting for specific document load states and setting timeouts. This method is part of the `Page` object in `viewpoint_core` and requires the `viewpoint_core` crate. ```rust use viewpoint_core::Page; use viewpoint_core::DocumentLoadState; use std::time::Duration; // Simple navigation page.goto("https://example.com").goto().await?; // Navigation with options page.goto("https://example.com") .wait_until(DocumentLoadState::DomContentLoaded) .timeout(Duration::from_secs(10)) .goto() .await?; ``` -------------------------------- ### Get Video Controller Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=u32+-%3E+bool Retrieves the video recording controller if video recording is enabled for the page. ```APIDOC ## GET /websites/rs_viewpoint-test/video ### Description Gets the video recording controller if video recording was enabled when the page was created. Returns `None` if video recording was not configured. ### Method GET ### Endpoint /websites/rs_viewpoint-test/video ### Response #### Success Response (200) - **video** (object | null) - The video recording controller object, or `null` if not enabled. #### Response Example ```json { "video": { "path": "/videos/video.mp4" } } ``` ``` -------------------------------- ### Get the Count of Failed Soft Assertions in Rust Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/expect/struct.SoftAssertions_search= Returns the total number of soft assertions that have failed. ```Rust pub fn failure_count(&self) -> usize ``` -------------------------------- ### Init Scripts Management Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext Manage initialization scripts that run before page loads. Scripts can be added directly or from file paths. ```APIDOC ## POST /context/init_script ### Description Add a script to be evaluated before every new page load. The script will run before any scripts on the page, and will persist for all pages created in this context (including popups). Unlike `page.add_init_script()`, this applies to all pages in the context, not just a single page. ### Method POST ### Endpoint `/context/init_script` ### Parameters #### Request Body - **script** (string) - Required - The JavaScript code to be executed. ### Request Example ```json { "script": "Object.defineProperty(navigator, 'webdriver', { get: () => false })" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "Init script added successfully" } ``` ## POST /context/init_script_path ### Description Add an init script from a file path. The file contents will be read and registered as an init script for all pages in this context. ### Method POST ### Endpoint `/context/init_script_path` ### Parameters #### Request Body - **path** (string) - Required - The path to the JavaScript file. ### Request Example ```json { "path": "./scripts/mock-auth.js" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "Init script from path added successfully" } ``` ## GET /context/init_scripts ### Description Get all context-level init scripts. This returns the scripts that will be applied to all new pages. ### Method GET ### Endpoint `/context/init_scripts` ### Response #### Success Response (200) - **scripts** (array of strings) - A list of all init script contents. #### Response Example ```json { "scripts": [ "Object.defineProperty(navigator, 'webdriver', { get: () => false })", "// Content of mock-auth.js" ] } ``` ``` -------------------------------- ### HAR Recording Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext APIs for initiating, starting, saving, and stopping network traffic recording to HAR files. ```APIDOC ## POST /context/har/record ### Description Starts recording network traffic to a HAR file at the specified path. The recording continues until the context is closed or `save_har` is called. ### Method POST ### Endpoint `/context/har/record` ### Parameters #### Request Body - **path** (PathBuf) - Required - The file path where the HAR data will be saved. ### Request Example ```json { "path": "/path/to/output.har" } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation that HAR recording has started. #### Response Example ```json { "message": "HAR recording started successfully." } ``` ## POST /context/har/start ### Description Starts HAR recording with specific options, allowing for filtering and content omission. ### Method POST ### Endpoint `/context/har/start` ### Parameters #### Request Body - **options** (HarRecordingOptions) - Required - Options for HAR recording. - **path** (String) - Required - The file path for the HAR file. - **url_filter** (String) - Optional - A glob pattern to filter URLs for recording. - **omit_content** (Boolean) - Optional - If true, response content will not be recorded. ### Request Example ```json { "options": { "path": "api_requests.har", "url_filter": "**/api/**", "omit_content": true } } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation that HAR recording has started with the provided options. #### Response Example ```json { "message": "HAR recording started with specified options." } ``` ## POST /context/har/save ### Description Saves the current HAR recording to its designated file path. This is useful if you want to save the HAR before the context is closed. ### Method POST ### Endpoint `/context/har/save` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **path** (PathBuf) - The file path where the HAR was saved. #### Response Example ```json { "path": "/path/to/saved/output.har" } ``` ## POST /context/har/stop ### Description Stops the HAR recording. Optionally saves the recording to a file before stopping. ### Method POST ### Endpoint `/context/har/stop` ### Parameters #### Request Body - **save** (boolean) - Required - If `true`, the HAR recording will be saved to file before stopping. ### Request Example ```json { "save": true } ``` ### Response #### Success Response (200) - **saved_path** (Option) - The path where the HAR file was saved, if `save` was true and successful. Returns `null` otherwise. #### Response Example ```json { "saved_path": "/path/to/stopped/recording.har" } ``` ``` -------------------------------- ### Get CDP Connection Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Browser_search= Retrieves a reference to the Chrome DevTools Protocol (CDP) connection associated with the browser instance. ```APIDOC ## GET /browser/connection ### Description Retrieves a reference to the Chrome DevTools Protocol (CDP) connection associated with the browser instance. ### Method GET ### Endpoint /browser/connection ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **connection** (object) - A reference to the CDP connection object. #### Response Example ```json { "connection": "" } ``` ``` -------------------------------- ### Handle Downloads with Page.on_download Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page This snippet demonstrates how to set up a handler for download events. The closure receives a `Download` object, allowing access to the downloaded file's path. It's crucial to have the `viewpoint_core` crate imported. ```rust use viewpoint_core::Page; page.on_download(|mut download| async move { let path = download.path().await.unwrap(); println!("Downloaded: {}", path.display()); }).await; ``` -------------------------------- ### Add Initialization Script Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=u32+-%3E+bool Adds a script to be evaluated before every page load. The script persists across navigations. ```APIDOC ## POST /websites/rs_viewpoint-test/add_init_script ### Description Adds a script to be evaluated before every page load. This script runs before any other scripts on the page and persists across navigations. ### Method POST ### Endpoint /websites/rs_viewpoint-test/add_init_script ### Parameters #### Request Body - **script** (string) - Required - The JavaScript code to be evaluated. ### Request Example ```javascript page.add_init_script("Object.defineProperty(navigator, 'webdriver', { get: () => false })").await; ``` ### Response #### Success Response (200) - **script_id** (string) - The unique identifier for the added script. #### Response Example ```json { "script_id": "init_script_123" } ``` ``` -------------------------------- ### Download Event Handling Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search= Set a handler for file download events. The handler is called when a download starts. ```APIDOC ## POST /page/on_download ### Description Sets a handler for file download events. The handler receives a `Download` object when a download begins. ### Method POST ### Endpoint /page/on_download ### Parameters #### Request Body - **handler** (function) - Required - A function that accepts a `Download` object and returns a `Future`. ### Request Example ```json { "handler": "async (download) => { console.log(`Download started: ${download.url()}`); }" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Download handler set successfully." } ``` ``` -------------------------------- ### Get BrowserContext CDP ID Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.BrowserContext_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the browser context's ID as recognized by the Chrome DevTools Protocol. ```Rust let cdp_context_id = context.context_id(); ``` -------------------------------- ### Get Viewport Size API Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieve the current dimensions (width and height in pixels) of the page's viewport. ```APIDOC ## GET /page/viewport_size ### Description Get the current viewport size. Returns the width and height in pixels. ### Method GET ### Endpoint /page/viewport_size ### Response #### Success Response (200) - **viewportSize** (object | null) - An object containing 'width' and 'height', or null if not available. #### Response Example ```json { "viewportSize": { "width": 1280, "height": 720 } } ``` ``` -------------------------------- ### Get Page Content API Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieve the entire HTML content of the current page, including the doctype declaration. ```APIDOC ## GET /page/content ### Description Get the full HTML content of the page including the doctype. ### Method GET ### Endpoint /page/content ### Response #### Success Response (200) - **html** (string) - The complete HTML content of the page. #### Response Example ```json { "html": "......" } ``` ### Errors - The page is closed - Evaluation fails ``` -------------------------------- ### Convenience: Using the Test Macro Source: https://docs.rs/viewpoint-test/latest/index Illustrates how to use the `#[viewpoint::test]` attribute macro for simplified test function signatures, automatically handling the setup and teardown of the page object. ```rust use viewpoint_test::test; use viewpoint_core::Page; #[viewpoint_test::test] async fn my_test(page: &Page) -> Result<(), Box> { page.goto("https://example.com").goto().await?; // page is automatically set up and cleaned up Ok(()) } ``` -------------------------------- ### Get Type ID (Rust) Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/expect/struct.LocatorAssertions Retrieves the `TypeId` of a given object. This is a fundamental operation for runtime type identification in Rust. It is part of the `Any` trait implementation. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Navigate to URL Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page_search=u32+-%3E+bool Navigates the page to a specified URL and returns a builder for configuring navigation options. ```APIDOC ## POST /websites/rs_viewpoint-test/goto ### Description Navigates the page to the specified URL. Returns a builder that allows for the configuration of navigation options such as timeouts and wait conditions. ### Method POST ### Endpoint /websites/rs_viewpoint-test/goto ### Parameters #### Request Body - **url** (string) - Required - The URL to navigate to. - **options** (object) - Optional - Navigation options like timeout, wait until. ### Request Example ```javascript page.goto("https://example.com", { waitUntil: 'networkidle0' }).await; ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful navigation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Control Keyboard Input with Page.keyboard Source: https://docs.rs/viewpoint-test/latest/viewpoint_test/struct.Page This example demonstrates interacting with the keyboard controller to simulate key presses, typing text, and using key combinations. It covers basic key presses, typing strings, and managing modifier keys like Shift. ```rust use viewpoint_core::Page; // Press a key page.keyboard().press("Enter").await?; // Type text page.keyboard().type_text("Hello, World!").await?; // Use key combinations page.keyboard().press("Control+a").await?; // Hold and release modifiers page.keyboard().down("Shift").await?; page.keyboard().press("a").await?; // Types 'A' page.keyboard().up("Shift").await?; ```