Module network

Module network 

Source
Expand description

§Network Interception and Monitoring

This module provides comprehensive network capabilities including request interception, response mocking, event monitoring, and HAR recording/replay.

§Features

  • Request Interception: Intercept and modify outgoing requests
  • Response Mocking: Return custom responses without hitting the server
  • Request Blocking: Block requests matching specific patterns
  • Network Events: Monitor requests, responses, and failures
  • HAR Recording: Record network traffic for debugging
  • HAR Replay: Replay recorded traffic for testing
  • WebSocket Monitoring: Track WebSocket connections and messages

§Mock API Responses

Mock API endpoints to test UI without a backend:

use viewpoint_core::Browser;

// Mock a REST API endpoint with JSON response
page.route("**/api/users", |route| async move {
    route.fulfill()
        .status(200)
        .content_type("application/json")
        .body(r#"{"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}"#)
        .fulfill()
        .await
}).await?;

// Mock different responses based on request method
page.route("**/api/items", |route| async move {
    let method = route.request().method();
    match method.as_str() {
        "GET" => {
            route.fulfill()
                .status(200)
                .content_type("application/json")
                .body(r#"[{"id": 1, "name": "Item 1"}]"#)
                .fulfill()
                .await
        }
        "POST" => {
            route.fulfill()
                .status(201)
                .content_type("application/json")
                .body(r#"{"id": 2, "name": "New Item", "created": true}"#)
                .fulfill()
                .await
        }
        "DELETE" => {
            route.fulfill()
                .status(204)
                .fulfill()
                .await
        }
        _ => route.continue_route().continue_route().await
    }
}).await?;

// Mock error responses
page.route("**/api/error", |route| async move {
    route.fulfill()
        .status(500)
        .content_type("application/json")
        .body(r#"{"error": "Internal Server Error", "code": "SERVER_ERROR"}"#)
        .fulfill()
        .await
}).await?;

// Mock 404 Not Found
page.route("**/api/not-found", |route| async move {
    route.fulfill()
        .status(404)
        .content_type("application/json")
        .body(r#"{"error": "Resource not found"}"#)
        .fulfill()
        .await
}).await?;

// Mock delayed response for loading state testing
page.route("**/api/slow", |route| async move {
    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
    route.fulfill()
        .status(200)
        .content_type("application/json")
        .body(r#"{"data": "loaded"}"#)
        .fulfill()
        .await
}).await?;

§Request Interception

Use Route to intercept and handle network requests:

use viewpoint_core::Browser;

// Block images for faster tests
page.route("**/*.{png,jpg,jpeg,gif,webp}", |route| async move {
    route.abort().await
}).await?;

// Add authentication header to all API requests
page.route("**/api/**", |route| async move {
    route.continue_route()
        .header("Authorization", "Bearer test-token-123")
        .continue_route()
        .await
}).await?;

// Modify POST body
page.route("**/api/submit", |route| async move {
    route.continue_route()
        .post_data(r#"{"modified": true, "test": true}"#)
        .continue_route()
        .await
}).await?;

// Intercept and inspect request before continuing
page.route("**/api/log", |route| async move {
    let request = route.request();
    println!("Request URL: {}", request.url());
    println!("Request method: {}", request.method());
    if let Some(body) = request.post_data() {
        println!("Request body: {}", body);
    }
    route.continue_route().continue_route().await
}).await?;

§URL Patterns

Routes support glob patterns for matching URLs:

  • ** - Match any path segments
  • * - Match any characters except /
  • ? - Match a single character
use viewpoint_core::{Browser, Route};
// Match all API endpoints
page.route("**/api/**", |route| async move {
    route.continue_route().continue_route().await
}).await?;

// Match specific file types
page.route("**/*.{js,css}", |route| async move {
    route.continue_route().continue_route().await
}).await?;

// Match exact URL
page.route("https://example.com/login", |route| async move {
    route.continue_route().continue_route().await
}).await?;

§Network Events

Monitor network activity with event listeners:

use viewpoint_core::Browser;

// Wait for a specific request
let request = page.wait_for_request("**/api/data")
    .wait()
    .await?;
println!("Request URL: {}", request.url());

// Wait for a specific response
let response = page.wait_for_response("**/api/data")
    .wait()
    .await?;
println!("Response status: {}", response.status());

§HAR Recording

Record network traffic for debugging or test fixtures:

use viewpoint_core::Browser;

// Start HAR recording
context.route_from_har()
    .record_path("recording.har")
    .build()
    .await?;

// ... navigate and interact ...

// HAR is automatically saved when context closes

§HAR Replay

Replay recorded traffic for deterministic tests:

use viewpoint_core::Browser;

// Replay from HAR file
context.route_from_har()
    .path("recording.har")
    .build()
    .await?;

// Now requests will be served from the HAR file
let page = context.new_page().await?;
page.goto("https://example.com").goto().await?;

§WebSocket Monitoring

Monitor WebSocket connections:

use viewpoint_core::Browser;

// Listen for WebSocket connections
page.on_websocket(|ws| async move {
    println!("WebSocket connected: {}", ws.url());
     
    // Listen for messages
    ws.on_frame(|frame| async move {
        println!("Frame: {:?}", frame.payload());
        Ok(())
    }).await;
     
    Ok(())
}).await;

Re-exports§

pub use events::NetworkEvent;
pub use events::NetworkEventListener;
pub use events::RequestEvent;
pub use events::RequestFailedEvent;
pub use events::RequestFinishedEvent;
pub use events::ResponseEvent;
pub use events::WaitForRequestBuilder;
pub use events::WaitForResponseBuilder;
pub use har::Har;
pub use har::HarEntry;
pub use har::HarPage;
pub use har::HarRequest;
pub use har::HarResponse;
pub use har::HarTimings;
pub use har_recorder::HarRecorder;
pub use har_recorder::HarRecordingBuilder;
pub use har_recorder::HarRecordingOptions;
pub use har_replay::HarReplayHandler;
pub use har_replay::HarReplayOptions;
pub use har_replay::HarResponseData;
pub use har_replay::TimingMode;
pub use har_replay::UpdateContentMode;
pub use websocket::WebSocket;
pub use websocket::WebSocketFrame;
pub use websocket::WebSocketManager;

Modules§

auth
HTTP and proxy authentication handling.
events
Network event handling.
har
HAR (HTTP Archive) format support.
har_recorder
HAR (HTTP Archive) recording.
har_replay
HAR replay functionality.
websocket
WebSocket monitoring and testing.

Structs§

ContinueBuilder
Builder for continuing a request with optional modifications.
FetchBuilder
Builder for fetching the actual response with optional request modifications.
FetchedResponse
A response fetched via route.fetch().
FulfillBuilder
Builder for fulfilling a request with a custom response.
HeaderEntry
Response HTTP header entry.
RemoteAddress
Remote server address.
Request
A network request.
RequestSizes
Request size information.
RequestTiming
Request timing information.
Response
A network response.
Route
An intercepted network request that can be fulfilled, continued, or aborted.
RouteHandlerRegistry
Route handler registry for a page or context.
SecurityDetails
Security details for HTTPS responses.

Enums§

AbortError
Error code for aborting requests.
ResourceType
Resource type as it was perceived by the rendering engine.
RouteAction
The result of a route handler action.
UrlPattern
URL pattern for matching requests.

Traits§

UrlMatcher
Trait for types that can match URLs.

Type Aliases§

RouteHandler
A route handler function.