eoka 0.16.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! A fake Chrome for unit tests: one loopback WebSocket peer.

use std::time::Duration;

use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
use tokio::net::TcpStream;
use tokio::task::JoinHandle;
use tokio_tungstenite::{tungstenite::Message, WebSocketStream};

use super::Transport;

pub(crate) type Peer = WebSocketStream<TcpStream>;

/// Listen on a loopback port. The task yields the first client as a WebSocket peer.
pub(crate) async fn listen() -> (String, JoinHandle<Peer>) {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("ws://{}", listener.local_addr().unwrap());
    let peer = tokio::spawn(async move {
        let (socket, _) = listener.accept().await.unwrap();
        tokio_tungstenite::accept_async(socket).await.unwrap()
    });
    (url, peer)
}

/// A transport connected to a fresh peer.
pub(crate) async fn connect(
    proxy_auth: Option<(String, String)>,
    timeout: Duration,
    filter_cdp: bool,
) -> (Transport, Peer) {
    let (url, peer) = listen().await;
    let transport = Transport::connect_with_proxy_auth(&url, proxy_auth, timeout, filter_cdp)
        .await
        .unwrap();
    (transport, peer.await.unwrap())
}

/// The next frame the transport sent, parsed as a CDP command.
pub(crate) async fn next_command(peer: &mut Peer) -> Value {
    let message = tokio::time::timeout(Duration::from_secs(2), peer.next())
        .await
        .expect("command must reach the peer")
        .unwrap()
        .unwrap();
    serde_json::from_str(message.to_text().unwrap()).unwrap()
}

/// Send one JSON message to the transport.
pub(crate) async fn send_json(peer: &mut Peer, message: Value) {
    peer.send(Message::Text(message.to_string().into()))
        .await
        .unwrap();
}