encore-dev 2.0.0-beta.17

Rust SDK for Encore applications
Documentation
//! Driving a system test browser with [chromiumoxide].
//!
//! [`connect`] attaches chromiumoxide to the managed Chromium instance for the
//! current test (see [`system::browser`]). Pages connect to the app in the test
//! session with automatic test-context propagation, recording, and telemetry.
//! Browser actions (clicks, keystrokes, navigations) and the backend requests
//! they trigger appear together in recordings and telemetry:
//!
//! ```text
//! pay                                 tests/checkout.rs:14
//!   click button "Pay"
//!     POST http://localhost:4000/orders 500
//!       POST orders /orders 500
//! ```
//!
//! Use [`Browser::step`] or [`Browser::try_step`] to group actions under a
//! named test step.
//!
//! Re-exports this crate's `chromiumoxide` dependency (enabled via the
//! `chromiumoxide` feature) so test suites use a matching version. Encore
//! manages the Chromium process (`browser/chromium`) automatically.
//!
//! ```ignore
//! use encore::testing::chromiumoxide::{chromiumoxide::error::CdpError, connect};
//! use encore::testing::system;
//!
//! #[encore::test]
//! async fn pays_from_the_browser() -> Result<(), Box<dyn std::error::Error>> {
//!     let browser = connect().await?;
//!     let page = browser.new_page(browser.url("web")?).await?;
//!     browser
//!         .try_step("pay", async {
//!             page.find_element("button#pay").await?.click().await?;
//!             Ok::<_, CdpError>(())
//!         })
//!         .await?;
//!     page.find_element("#thanks").await?;
//!     system::settled().await?;
//!     Ok(())
//! }
//! ```
//!
//! [chromiumoxide]: https://docs.rs/chromiumoxide

use std::fmt::Display;
use std::future::{poll_fn, Future};
use std::ops::{Deref, DerefMut};
use std::path::Path;
use std::pin::Pin;

use futures_core::Stream as _;

use super::system::{self, BrowserOptions};
use crate::error::Error;

/// chromiumoxide, as this crate depends on it: the version [`Browser`] is of.
pub use ::chromiumoxide;

/// A [`chromiumoxide::Browser`](::chromiumoxide::Browser) connected to the
/// current test's managed browser (see [`connect`]).
///
/// Dereferences to [`::chromiumoxide::Browser`] while exposing Encore helpers
/// for URLs, recordings, and test steps. Dropping this value closes the
/// DevTools connection; Encore closes the browser process when the test ends.
pub struct Browser {
    browser: ::chromiumoxide::Browser,
    test: system::Browser,
    /// Drives the connection: chromiumoxide does nothing unless polled.
    handler: tokio::task::JoinHandle<()>,
}

/// Connects chromiumoxide to the current test's browser, launching it if it is
/// not already running.
///
/// Spawns a background task on the current Tokio runtime to drive the DevTools
/// connection; the task stops when [`Browser`] is dropped or when the test ends.
pub async fn connect() -> Result<Browser, Error> {
    connect_with(BrowserOptions::default()).await
}

/// Like [`connect`], with custom [`BrowserOptions`]. Options only take effect
/// on the first browser call in a test (see [`system::browser_with`]).
pub async fn connect_with(options: BrowserOptions) -> Result<Browser, Error> {
    attach(system::browser_with(options).await?).await
}

/// Connects chromiumoxide to `test`, a test's browser.
async fn attach(test: system::Browser) -> Result<Browser, Error> {
    // chromiumoxide is built against one version of the protocol, and the
    // browser is the version Encore pins: what the browser says that
    // chromiumoxide does not know, it is to pass over.
    let config = ::chromiumoxide::handler::HandlerConfig {
        ignore_invalid_messages: true,
        ..Default::default()
    };
    let (browser, mut handler) =
        ::chromiumoxide::Browser::connect_with_config(test.ws_endpoint(), config)
            .await
            .map_err(|err| {
                Error::unavailable(format!(
                    "could not connect chromiumoxide to the test's browser: {err}"
                ))
            })?;
    let handler = tokio::spawn(async move {
        // An error here is the connection's: the browser has gone.
        while let Some(Ok(())) = poll_fn(|cx| Pin::new(&mut handler).poll_next(cx)).await {}
    });
    Ok(Browser {
        browser,
        test,
        handler,
    })
}

impl Browser {
    /// Returns the URL for navigating to the named gateway or frontend inside
    /// the browser. Requests to this URL are routed to the test session.
    pub fn url(&self, name: &str) -> Result<String, Error> {
        self.test.url(name)
    }

    /// Returns the path where the HTML replay recording will be written when
    /// the test ends, if enabled. See [`system::Browser::recording`].
    pub fn recording(&self) -> Option<&Path> {
        self.test.recording()
    }

    /// Runs `statement` as a named step in the test recording and telemetry.
    /// See [`system::Browser::step`].
    #[track_caller]
    pub fn step<F: Future>(
        &self,
        name: impl Into<String>,
        statement: F,
    ) -> impl Future<Output = F::Output> {
        self.test.step(name, statement)
    }

    /// Like [`step`](Self::step) for fallible futures, recording any `Err`
    /// result as the step's error.
    #[track_caller]
    pub fn try_step<T, E: Display, F: Future<Output = Result<T, E>>>(
        &self,
        name: impl Into<String>,
        statement: F,
    ) -> impl Future<Output = Result<T, E>> {
        self.test.try_step(name, statement)
    }

    /// Returns the underlying [`system::Browser`] handle.
    pub fn session(&self) -> &system::Browser {
        &self.test
    }
}

impl Deref for Browser {
    type Target = ::chromiumoxide::Browser;

    fn deref(&self) -> &Self::Target {
        &self.browser
    }
}

impl DerefMut for Browser {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.browser
    }
}

impl Drop for Browser {
    fn drop(&mut self) {
        self.handler.abort();
    }
}

impl std::fmt::Debug for Browser {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Browser")
            .field("ws_endpoint", &self.test.ws_endpoint())
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read as _, Write as _};
    use std::net::{SocketAddr, TcpListener};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    /// Names a Chromium to run for this test, as it does for a test
    /// session: the `browser/chromium` component's `chrome-headless-shell`.
    const BROWSER_ENV: &str = "ENCORE_TEST_BROWSER";

    /// The ports the shop's page and its API are written against, which
    /// nothing listens on: where `encore run` would have them.
    const WEB: u16 = 45998;
    const API: u16 = 45999;

    const PAGE: &str = r#"<!doctype html><title>Shop</title>
<button id="pay">Pay</button><div id="out"></div>
<script>
  document.getElementById('pay').onclick = async () => {
    const res = await fetch('http://localhost:45999/pay', {method: 'POST'});
    document.getElementById('out').textContent = res.ok ? 'Thanks!' : 'Failed';
  };
</script>"#;

    /// The app: its page at `/`, and its API at `/pay`. Returns where it
    /// listens, and the head of each request it was sent.
    fn app() -> (SocketAddr, Arc<Mutex<Vec<String>>>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let requests = Arc::new(Mutex::new(Vec::new()));
        let seen = requests.clone();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { return };
                let seen = seen.clone();
                std::thread::spawn(move || {
                    let mut request = Vec::new();
                    let mut buf = [0u8; 4096];
                    while !request.windows(4).any(|w| w == b"\r\n\r\n") {
                        match stream.read(&mut buf) {
                            Ok(n) if n > 0 => request.extend_from_slice(&buf[..n]),
                            _ => return,
                        }
                    }
                    let head = String::from_utf8_lossy(&request).into_owned();
                    let (kind, body) = match head.starts_with("POST /pay") {
                        true => ("application/json", "{\"ok\":true}"),
                        false => ("text/html; charset=utf-8", PAGE),
                    };
                    seen.lock().unwrap().push(head);
                    let _ = write!(
                        stream,
                        "HTTP/1.1 200 OK\r\nContent-Type: {kind}\r\n\
                         Access-Control-Allow-Origin: *\r\nContent-Length: {}\r\n\
                         Connection: close\r\n\r\n{body}",
                        body.len()
                    );
                });
            }
        });
        (addr, requests)
    }

    /// chromiumoxide drives a browser run as a test session runs one, and
    /// what it does there is put down to the test's statements. Skipped
    /// without a Chromium (`ENCORE_TEST_BROWSER`).
    #[tokio::test(flavor = "multi_thread")]
    async fn chromiumoxide_drives_a_test_s_browser() {
        let Some(executable) = std::env::var_os(BROWSER_ENV).filter(|path| !path.is_empty()) else {
            eprintln!("skipping the chromiumoxide test: set {BROWSER_ENV} to a Chromium");
            return;
        };
        let (app, requests) = app();
        let route = |name: &str, port: u16, api: bool| encore_browser::Route {
            name: name.to_string(),
            port,
            to: app,
            api,
        };
        let session = encore_browser::Browser::launch(encore_browser::Config {
            executable: executable.into(),
            routes: vec![route("web", WEB, false), route("api", API, true)],
            tagging: encore_browser::Tagging {
                headers: vec![(
                    "x-encore-meta-ctx-encore-test".to_string(),
                    "0123456789abcdef".to_string(),
                )],
                trace_id: Some("0af7651916cd43dd8448eb211c80319c".to_string()),
            },
            ..Default::default()
        })
        .await
        .expect("the browser starts");

        // As the SDK core gives it to a test.
        let ws_endpoint = session.ws_url().to_string();
        let steps_url = ws_endpoint.replacen("ws://", "http://", 1).replacen(
            "/devtools/browser/",
            "/encore/",
            1,
        );
        let web = format!("http://localhost:{WEB}/");
        let browser = attach(system::Browser::at(
            &ws_endpoint,
            &steps_url,
            &[("web", &web)],
        ))
        .await
        .expect("chromiumoxide connects");

        let page = browser.new_page("about:blank").await.expect("a page");
        browser
            .try_step("open the shop", page.goto(browser.url("web").unwrap()))
            .await
            .expect("the shop opens");
        browser
            .try_step("pay", async {
                page.find_element("button#pay").await?.click().await?;
                Ok::<_, ::chromiumoxide::error::CdpError>(())
            })
            .await
            .expect("the button is clicked");
        let mut said = String::new();
        for _ in 0..100 {
            said = page
                .evaluate("document.getElementById('out').textContent")
                .await
                .expect("the page answers")
                .into_value()
                .unwrap_or_default();
            if !said.is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        assert_eq!(said, "Thanks!");
        drop(browser);

        let recorded = session.finish(true).await.expect("kept");
        let span = |name: &str| {
            recorded
                .spans
                .iter()
                .find(|span| span.name == name)
                .unwrap_or_else(|| {
                    let names: Vec<_> = recorded.spans.iter().map(|span| &span.name).collect();
                    panic!("no span {name:?} among {names:?}")
                })
        };
        // Each statement, with where the test made it.
        let opened = span("open the shop");
        let paid = span("pay");
        assert_eq!(paid.kind, encore_browser::Kind::Step);
        assert!(paid.attributes.iter().any(|(key, value)| {
            key == "code.file.path" && value.ends_with("chromiumoxide.rs")
        }));
        // What each had the browser do, read off the protocol, under it.
        assert_eq!(span(&format!("navigate {web}")).parent, Some(opened.id));
        let click = span("click button \"Pay\"");
        assert_eq!(click.parent, Some(paid.id));
        // And the request the click set off, under the click.
        let request = span(&format!("POST http://localhost:{API}/pay"));
        assert_eq!(request.kind, encore_browser::Kind::Request);
        assert_eq!(request.parent, Some(click.id));

        // The page's requests reached the app where the session has it,
        // each as the test's.
        let requests = requests.lock().unwrap().clone();
        let paying = requests
            .iter()
            .find(|head| head.starts_with("POST /pay"))
            .expect("the API was called")
            .to_ascii_lowercase();
        assert!(paying.contains("x-encore-meta-ctx-encore-test: 0123456789abcdef"));
        assert!(paying.contains("traceparent: 00-0af7651916cd43dd8448eb211c80319c-"));

        // And the page was recorded.
        let shop = recorded
            .pages
            .iter()
            .find(|page| page.url == web)
            .expect("the shop's page is in the recording");
        assert!(shop.events.len() > 4, "{} events", shop.events.len());
    }
}