encore-dev 2.0.0-beta.15

Rust SDK for Encore applications
Documentation
//! A system test's browser, driven with [chromiumoxide].
//!
//! [`connect`] connects chromiumoxide to the browser Encore runs for the
//! current test (see [`system::browser`]): a page reaches the app where
//! `encore run` has it, in the test session; its requests are the test's;
//! and what it shows is recorded. What the test has the browser do — a
//! click, a key, a navigation — is read off the protocol and is in the
//! recording and in the test's telemetry, with the requests that came of it
//! and what the app did for each:
//!
//! ```text
//! pay                                 tests/checkout.rs:14
//!   click button "Pay"
//!     POST http://localhost:4000/orders 500
//!       POST orders /orders 500
//! ```
//!
//! [`Browser::step`] says which statement of the test that was.
//!
//! chromiumoxide is this crate's own, behind the `chromiumoxide` feature and
//! re-exported here, so a suite names one version of it. It launches no
//! browser: Encore runs its own, the `browser/chromium` component.
//!
//! ```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;

/// chromiumoxide's browser, connected to the current test's: see
/// [`connect`]. It is chromiumoxide's [`Browser`](::chromiumoxide::Browser)
/// to use (it dereferences to it), with what Encore knows of the browser
/// beside it.
///
/// Dropped, it lets go of the connection. The browser itself is the test
/// session's, and ends with the test: there is nothing to close.
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, starting it if the
/// test has none yet.
///
/// The connection is driven by a task on the runtime this is awaited in,
/// which ends when the [`Browser`] is dropped, or when the test ends and
/// its browser with it.
pub async fn connect() -> Result<Browser, Error> {
    connect_with(BrowserOptions::default()).await
}

/// [`connect`], with the browser as `options` say: they are the first ask's
/// to say, as [`system::browser_with`]'s are.
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 {
    /// The URL a page reaches the gateway or frontend `name` at: the one
    /// `encore run` has it at, which the frontend is written against. The
    /// browser's requests there go to the test session.
    pub fn url(&self, name: &str) -> Result<String, Error> {
        self.test.url(name)
    }

    /// The file the recording is written to when the test ends, if it is
    /// kept: see [`system::Browser::recording`].
    pub fn recording(&self) -> Option<&Path> {
        self.test.recording()
    }

    /// Runs `statement` as the step `name` of the test, so that what it has
    /// the browser do is put down to it: 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)
    }

    /// [`step`](Self::step), for a statement that can fail: its error is
    /// the step's.
    #[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)
    }

    /// The test's browser as Encore has it, whichever tool drives it.
    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());
    }
}