Skip to main content

encore/testing/
system.rs

1//! End-to-end system tests that run against the full application.
2//!
3//! While unit tests run inside a single service in isolation (service-to-service
4//! calls are not served and Pub/Sub subscriptions do not run), tests in a
5//! system test suite—a crate whose directory contains `encore.systest.json`—run
6//! against the whole app in a dedicated test session. Services start on demand
7//! just like `encore run`, using test secrets, test configs, and isolated test
8//! data.
9//!
10//! ```ignore
11//! use encore::testing::system;
12//!
13//! static BILLING: Database = Database::named("billing");
14//!
15//! #[encore::test]
16//! async fn placing_an_order_charges_the_card() -> Result<(), Box<dyn std::error::Error>> {
17//!     let order = orders::place(&PlaceParams { sku: "tee".into(), qty: 2 }).await?;
18//!     // The order's event has been handled by billing's subscription.
19//!     system::settled().await?;
20//!
21//!     let row = BILLING
22//!         .query_one("SELECT amount FROM charges WHERE order_id = $1", &[&order.id])
23//!         .await?;
24//!     assert_eq!(row.get::<_, i64>(0), 4000);
25//!     Ok(())
26//! }
27//! ```
28//!
29//! A system test can call any service and access any resource declared by the
30//! app (either via `::named(...)` or through a service's own declaration).
31//!
32//! Each test gets isolated data across every Postgres database, ClickHouse
33//! database, Redis database, and object bucket (with migrations applied). All
34//! services handling requests for that test operate on the test's isolated
35//! data, so tests can run in parallel without interfering with one another.
36//!
37//! System tests can also load a [`Fixture`](super::Fixture). When the fixture's
38//! setup runs against the app and settles, the resulting state across all
39//! databases, buckets, and Redis instances is snapshotted and copied for each
40//! test that loads it.
41//!
42//! Background work that is not triggered by a test request (such as a worker
43//! loop or polling job) runs against the session's shared data. To test such
44//! background work, set `"data": "shared"` in `encore.systest.json`; tests in
45//! that suite share data with background workers and with each other.
46//!
47//! Published Pub/Sub messages are delivered automatically to subscriptions in
48//! their declaring services. Call [`settled`] to wait for delivery rather than
49//! calling [`deliver`](super::deliver).
50//!
51//! Each test has an ID that propagates automatically across all outgoing
52//! requests and messages so Encore can attribute work and route data correctly.
53//! Making a service call or publishing a message from an unassociated thread
54//! panics.
55//!
56//! To test frontends in a real browser, call [`browser`] to launch a managed
57//! headless Chromium instance connected to the test session with automatic
58//! recording and telemetry.
59//!
60//! Run system tests with `encore test`, or with `cargo test` inside the suite's
61//! directory.
62
63use std::collections::HashMap;
64use std::fmt::Display;
65use std::future::Future;
66use std::panic::Location;
67use std::path::{Path, PathBuf};
68use std::sync::atomic::{AtomicBool, Ordering};
69use std::sync::{Arc, OnceLock};
70use std::time::Duration;
71
72use encore_sdk_core::system_test::{NotSettled, Outcome, SystemTest};
73
74pub use encore_sdk_core::system_test::telemetry::{
75    Deliveries, Event, Kind, Link, Log, LostContext, Publishes, Queries, Requests, Span, Status,
76    Telemetry, What,
77};
78
79use crate::error::{ErrCode, Error};
80use crate::runtime::core;
81
82/// The test session the process's tests run against.
83fn session() -> Result<&'static std::sync::Arc<SystemTest>, Error> {
84    core().system_test().ok_or_else(|| {
85        Error::new(
86            ErrCode::FailedPrecondition,
87            "not a system test: only tests in a system test suite (a directory with \
88             `encore.systest.json`) run against the full app",
89        )
90    })
91}
92
93/// Waits up to 30 seconds for all asynchronous work triggered by the current
94/// test to finish (no in-flight service or gateway requests, and no queued,
95/// active, or retrying Pub/Sub deliveries). See [`settled_with`] to customize
96/// the timeout.
97///
98/// Only work carrying the current test's ID is tracked, so parallel tests do
99/// not wait on each other and unrelated background work is ignored. If a
100/// service drops request context propagation, that downstream work loses the
101/// test ID, runs against shared data, and is not awaited (inspect
102/// [`telemetry`] to find lost context).
103///
104/// In suites configured with `"data": "shared"`, `settled` waits for all
105/// in-flight work across the entire app. Detached tasks spawned by a service
106/// after responding to a request are not tracked.
107///
108/// ```ignore
109/// orders::place(&params).await?;   // publishes `order-placed`
110/// system::settled().await?;        // billing has handled it
111/// ```
112pub async fn settled() -> Result<(), Error> {
113    settled_with(SettleOptions::new()).await
114}
115
116/// Like [`settled`], with custom [`SettleOptions`]. If the app does not settle
117/// in time, the returned error lists what work is still in progress.
118///
119/// ```ignore
120/// system::settled_with(SettleOptions::new().timeout(Duration::from_secs(5))).await?;
121/// ```
122pub async fn settled_with(options: SettleOptions) -> Result<(), Error> {
123    wait(options.timeout).await
124}
125
126/// The options of [`settled_with`].
127#[derive(Debug, Clone, Default)]
128pub struct SettleOptions {
129    timeout: Option<Duration>,
130}
131
132impl SettleOptions {
133    /// The options [`settled`] waits with.
134    pub fn new() -> Self {
135        Self::default()
136    }
137
138    /// Waits for at most `timeout`, rather than 30 seconds.
139    pub fn timeout(mut self, timeout: Duration) -> Self {
140        self.timeout = Some(timeout);
141        self
142    }
143}
144
145async fn wait(timeout: Option<Duration>) -> Result<(), Error> {
146    session()?;
147    let test = super::current()?;
148    // The session is asked over the process's connection to the daemon,
149    // which answers when it has settled: off the async workers.
150    let waited = tokio::task::spawn_blocking(move || {
151        test.scope
152            .core_scope()?
153            .settled(timeout)
154            .map_err(not_settled)
155    })
156    .await
157    .map_err(|err| Error::internal(format!("waiting for the app to settle: {err}")))?;
158    waited
159}
160
161fn not_settled(err: anyhow::Error) -> Error {
162    let code = match err.downcast_ref::<NotSettled>() {
163        Some(_) => ErrCode::DeadlineExceeded,
164        None => ErrCode::Unavailable,
165    };
166    Error::new(code, format!("{err:#}"))
167}
168
169/// Returns the URL of the named gateway or frontend in the current test
170/// session, for use with custom clients (such as a WebSocket client).
171/// Frontends start on demand on the first connection.
172///
173/// SDK and generated clients propagate test context automatically; for custom
174/// clients, attach the headers returned by [`headers`].
175pub fn url(name: &str) -> Result<String, Error> {
176    let session = session()?;
177    session.url(name).map(str::to_owned).ok_or_else(|| {
178        let mut known: Vec<&str> = session.gateway_urls().keys().map(String::as_str).collect();
179        known.sort_unstable();
180        Error::not_found(format!(
181            "the app has no gateway or frontend {name:?} (its gateways: {})",
182            match known.is_empty() {
183                true => "none".to_string(),
184                false => known.join(", "),
185            }
186        ))
187    })
188}
189
190/// Returns HTTP headers that associate a custom client's request with the
191/// current test (carrying the test ID in Request Context and the active trace
192/// context).
193///
194/// ```ignore
195/// let mut request = http::Request::get(format!("{}/health", system::url("api")?));
196/// for (name, value) in system::headers()? {
197///     request = request.header(name, value);
198/// }
199/// ```
200pub fn headers() -> Result<Vec<(String, String)>, Error> {
201    session()?;
202    let test = super::current()?;
203    Ok(test
204        .scope
205        .core_scope()?
206        .carry()
207        .map(|carried| carried.headers())
208        .unwrap_or_default())
209}
210
211/// Waits for the app to settle and returns the [`Telemetry`] recorded for the
212/// current test, including all service spans, inter-service requests, Pub/Sub
213/// deliveries, queries, and log lines.
214///
215/// Inspect spans via [`Span::what`] and the helper filters on [`Telemetry`]:
216///
217/// ```ignore
218/// let recorded = system::telemetry().await?;
219/// assert_eq!(recorded.requests().service("catalog").count(), 1);
220/// assert!(recorded.deliveries().all(|d| matches!(d.what, What::Delivery { handled: true, .. })));
221/// assert_eq!(recorded.errors(), Vec::<String>::new());
222/// ```
223///
224/// [`Telemetry::render`] formats the same trace tree printed on test failure,
225/// and [`Telemetry::shape`] strips run-specific values for snapshot testing.
226pub async fn telemetry() -> Result<Telemetry, Error> {
227    telemetry_with(TelemetryOptions::new()).await
228}
229
230/// Like [`telemetry`], with custom [`TelemetryOptions`] (for example, to
231/// inspect telemetry immediately without waiting for the app to settle).
232///
233/// ```ignore
234/// let now = system::telemetry_with(TelemetryOptions::new().settle(false)).await?;
235/// ```
236pub async fn telemetry_with(options: TelemetryOptions) -> Result<Telemetry, Error> {
237    session()?;
238    let test = super::current()?;
239    let TelemetryOptions { settle, timeout } = options;
240    tokio::task::spawn_blocking(move || {
241        test.scope
242            .core_scope()?
243            .telemetry(settle, timeout)
244            .map_err(not_settled)
245    })
246    .await
247    .map_err(|err| Error::internal(format!("reading the test's telemetry: {err}")))?
248}
249
250/// The options of [`telemetry_with`].
251#[derive(Debug, Clone)]
252pub struct TelemetryOptions {
253    settle: bool,
254    timeout: Option<Duration>,
255}
256
257impl Default for TelemetryOptions {
258    fn default() -> Self {
259        TelemetryOptions {
260            settle: true,
261            timeout: None,
262        }
263    }
264}
265
266impl TelemetryOptions {
267    /// The options [`telemetry`] reads with: once the app has settled,
268    /// waiting for at most 30 seconds.
269    pub fn new() -> Self {
270        Self::default()
271    }
272
273    /// Whether to wait for the app to [settle](settled) first, which is when
274    /// all of what the test caused is recorded. `false` reads what has been
275    /// recorded by now. `true` by default.
276    pub fn settle(mut self, settle: bool) -> Self {
277        self.settle = settle;
278        self
279    }
280
281    /// Waits for the app to settle for at most `timeout`, rather than 30
282    /// seconds.
283    pub fn timeout(mut self, timeout: Duration) -> Self {
284        self.timeout = Some(timeout);
285        self
286    }
287}
288
289/// Controls when [`browser`] recordings are saved.
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub enum Record {
292    /// For a test that failed, or whose runner does not say how it ended.
293    Failed,
294    /// For every test.
295    All,
296    /// Never: nothing is recorded.
297    Off,
298}
299
300/// Options for launching a test browser with [`browser_with`].
301#[derive(Debug, Clone, Default)]
302pub struct BrowserOptions {
303    record: Option<Record>,
304    args: Vec<String>,
305    window: Option<(u32, u32)>,
306}
307
308impl BrowserOptions {
309    pub fn new() -> Self {
310        Self::default()
311    }
312
313    /// When what the browser recorded is kept. Without it, what
314    /// `ENCORE_TEST_RECORD` says (`failed`, `all` or `off`), else
315    /// [`Record::Failed`].
316    pub fn record(mut self, record: Record) -> Self {
317        self.record = Some(record);
318        self
319    }
320
321    /// More command-line arguments for the browser, after Encore's own.
322    pub fn args<I, A>(mut self, args: I) -> Self
323    where
324        I: IntoIterator<Item = A>,
325        A: Into<String>,
326    {
327        self.args.extend(args.into_iter().map(Into::into));
328        self
329    }
330
331    /// The size of the browser's window, in CSS pixels: 1280×800 without it.
332    pub fn window(mut self, width: u32, height: u32) -> Self {
333        self.window = Some((width, height));
334        self
335    }
336}
337
338/// The current test's browser: see [`browser`]. Cheap to clone, and every
339/// clone is the same browser.
340#[derive(Debug, Clone)]
341pub struct Browser {
342    inner: Arc<BrowserInner>,
343}
344
345#[derive(Debug)]
346struct BrowserInner {
347    ws_endpoint: String,
348    urls: HashMap<String, String>,
349    recording: Option<PathBuf>,
350    steps: Steps,
351}
352
353/// Returns a managed headless Chromium [`Browser`] for the current test,
354/// launching it on first call and closing it when the test ends.
355///
356/// The browser integrates directly with the test session:
357///
358/// - Pages reach gateways and frontends at their normal `encore run` addresses
359///   (such as `http://localhost:4000`), automatically routed to the test
360///   session.
361/// - Every request from the browser carries the test's ID, so backend work
362///   runs against the test's isolated data and is awaited by [`settled`].
363/// - Browser actions, page requests, console errors, uncaught exceptions, and
364///   failed requests appear in [`telemetry`] alongside the backend spans they
365///   triggered.
366/// - Page activity is recorded; on failure, an HTML replay file is saved
367///   ([`Browser::recording`]).
368///
369/// Enable the `chromiumoxide` feature to use `testing::chromiumoxide::connect`,
370/// or connect any other Chrome DevTools Protocol client to
371/// [`Browser::ws_endpoint`]. Encore downloads the `browser/chromium` component
372/// automatically on first use.
373///
374/// ```ignore
375/// let browser = system::browser().await?;
376/// let (chromium, handler) = chromiumoxide::Browser::connect(browser.ws_endpoint()).await?;
377/// let page = chromium.new_page(browser.url("web")?).await?;
378/// ```
379pub async fn browser() -> Result<Browser, Error> {
380    browser_with(BrowserOptions::default()).await
381}
382
383/// Like [`browser`], with custom [`BrowserOptions`]. Options only take effect
384/// on the first call in a test; subsequent calls return the same browser.
385pub async fn browser_with(options: BrowserOptions) -> Result<Browser, Error> {
386    use encore_sdk_core::system_test::BrowserOptions as CoreOptions;
387    session()?;
388    let test = super::current()?;
389    let options = CoreOptions {
390        record: options.record.map(|record| {
391            match record {
392                Record::Failed => "failed",
393                Record::All => "all",
394                Record::Off => "off",
395            }
396            .to_string()
397        }),
398        args: options.args,
399        width: options.window.map(|(width, _)| width).unwrap_or_default(),
400        height: options.window.map(|(_, height)| height).unwrap_or_default(),
401    };
402    // The session answers once the browser has started, which the first
403    // time on a machine is once it is downloaded: off the async workers.
404    let started = tokio::task::spawn_blocking(move || {
405        test.scope
406            .core_scope()?
407            .browser(&options)
408            .map_err(|err| Error::unavailable(format!("{err:#}")))
409    })
410    .await
411    .map_err(|err| Error::internal(format!("starting the test's browser: {err}")))??;
412    Ok(Browser {
413        inner: Arc::new(BrowserInner {
414            ws_endpoint: started.ws_endpoint,
415            urls: started.urls,
416            recording: Some(started.recording)
417                .filter(|path| !path.is_empty())
418                .map(PathBuf::from),
419            steps: Steps::new(started.steps_url),
420        }),
421    })
422}
423
424impl Browser {
425    /// A browser at `ws_endpoint` that takes its steps at `steps_url`,
426    /// with `urls` for the app's: for tests of what is built on one.
427    #[cfg(test)]
428    pub(super) fn at(ws_endpoint: &str, steps_url: &str, urls: &[(&str, &str)]) -> Browser {
429        Browser {
430            inner: Arc::new(BrowserInner {
431                ws_endpoint: ws_endpoint.to_string(),
432                urls: urls
433                    .iter()
434                    .map(|(name, url)| (name.to_string(), url.to_string()))
435                    .collect(),
436                recording: None,
437                steps: Steps::new(steps_url.to_string()),
438            }),
439        }
440    }
441
442    /// Returns the Chrome DevTools Protocol WebSocket endpoint
443    /// (for example, `ws://127.0.0.1:53211/devtools/browser/…`).
444    pub fn ws_endpoint(&self) -> &str {
445        &self.inner.ws_endpoint
446    }
447
448    /// Returns the path where the HTML replay recording will be written when
449    /// the test ends, or `None` if recording is disabled.
450    pub fn recording(&self) -> Option<&Path> {
451        self.inner.recording.as_deref()
452    }
453
454    /// Returns the URL for navigating to the named gateway or frontend inside
455    /// the browser. Requests to this URL are routed to the test session.
456    pub fn url(&self, name: &str) -> Result<String, Error> {
457        self.inner.urls.get(name).cloned().ok_or_else(|| {
458            let mut known: Vec<&str> = self
459                .inner
460                .urls
461                .keys()
462                .map(String::as_str)
463                .filter(|known| *known != "proxy")
464                .collect();
465            known.sort_unstable();
466            Error::not_found(format!(
467                "the app has no gateway or frontend {name:?} (it has: {})",
468                match known.is_empty() {
469                    true => "none".to_string(),
470                    false => known.join(", "),
471                }
472            ))
473        })
474    }
475
476    /// Runs `statement` as a named step in the test recording and
477    /// [`telemetry`], tagged with the caller's source location.
478    ///
479    /// Browser actions (clicks, keystrokes, navigations) and the backend
480    /// requests they trigger while `statement` runs are grouped under this
481    /// step. If `statement` panics or is dropped before completing, the step is
482    /// recorded as failed. Step-reporting failures never fail the test.
483    ///
484    /// ```ignore
485    /// browser.step("pay", page.find_element("button#pay").await?.click()).await?;
486    /// ```
487    #[track_caller]
488    pub fn step<F: Future>(
489        &self,
490        name: impl Into<String>,
491        statement: F,
492    ) -> impl Future<Output = F::Output> {
493        let (browser, name, at) = (self.inner.clone(), name.into(), Location::caller());
494        async move {
495            let mut open = browser.steps.begin(&name, at).await;
496            let output = statement.await;
497            open.end(None).await;
498            output
499        }
500    }
501
502    /// Like [`step`](Self::step) for fallible futures, recording any `Err`
503    /// result as the step's error.
504    #[track_caller]
505    pub fn try_step<T, E: Display, F: Future<Output = Result<T, E>>>(
506        &self,
507        name: impl Into<String>,
508        statement: F,
509    ) -> impl Future<Output = Result<T, E>> {
510        let (browser, name, at) = (self.inner.clone(), name.into(), Location::caller());
511        async move {
512            let mut open = browser.steps.begin(&name, at).await;
513            let output = statement.await;
514            open.end(output.as_ref().err().map(|err| err.to_string()))
515                .await;
516            output
517        }
518    }
519}
520
521/// How long saying a step began or ended may take: the browser's endpoint
522/// is on this machine.
523const STEP_TIMEOUT: Duration = Duration::from_secs(5);
524
525/// How long saying that a step was left unfinished may take: said while a
526/// thread unwinds or a future is dropped, which must not be held up.
527const STEP_LEFT_TIMEOUT: Duration = Duration::from_millis(300);
528
529/// Says which statement of a test is running, to the endpoint of the test's
530/// browser, over HTTP: `POST <url>/stepBegin` and `POST <url>/stepEnd`.
531#[derive(Debug)]
532struct Steps {
533    /// `http://127.0.0.1:<port>/encore/<token>`. Empty where there is
534    /// nowhere to say it.
535    url: String,
536    /// Set once the endpoint has not answered: nothing more is said.
537    gone: AtomicBool,
538}
539
540fn steps_client() -> &'static reqwest::Client {
541    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
542    CLIENT.get_or_init(|| {
543        reqwest::Client::builder()
544            // This machine's own address: never through a proxy.
545            .no_proxy()
546            // Each test may run in a runtime of its own, and a connection
547            // kept from one test is not the next one's to use.
548            .pool_max_idle_per_host(0)
549            .timeout(STEP_TIMEOUT)
550            .build()
551            .unwrap_or_default()
552    })
553}
554
555impl Steps {
556    fn new(url: String) -> Self {
557        Steps {
558            url,
559            gone: AtomicBool::new(false),
560        }
561    }
562
563    fn silent(&self) -> bool {
564        self.url.is_empty() || self.gone.load(Ordering::Relaxed)
565    }
566
567    /// Sends a command, and returns its answer. `None` once the endpoint
568    /// has failed to answer one: not Encore's browser, or it has closed,
569    /// and the test goes on as it is.
570    async fn post(&self, command: &str, params: &serde_json::Value) -> Option<serde_json::Value> {
571        if self.silent() {
572            return None;
573        }
574        let sent = steps_client()
575            .post(format!("{}/{command}", self.url))
576            .json(params)
577            .send()
578            .await
579            .and_then(|response| response.error_for_status());
580        let answer = match sent {
581            Ok(response) => response.json().await.ok(),
582            Err(_) => None,
583        };
584        if answer.is_none() {
585            self.gone.store(true, Ordering::Relaxed);
586        }
587        answer
588    }
589
590    /// Says the step `name`, written at `at`, begins. Returns once the
591    /// endpoint has taken it, so that what the caller has the browser do
592    /// next comes after it.
593    async fn begin<'a>(&'a self, name: &str, at: &Location<'_>) -> OpenStep<'a> {
594        let params = serde_json::json!({"name": name, "file": at.file(), "line": at.line()});
595        let id = self
596            .post("stepBegin", &params)
597            .await
598            .and_then(|answer| answer["id"].as_str().map(str::to_string));
599        OpenStep { steps: self, id }
600    }
601}
602
603/// A step that has begun, and not ended. Dropped without [`end`](Self::end)
604/// — its statement panicked, or was dropped unfinished — it ends as failed.
605struct OpenStep<'a> {
606    steps: &'a Steps,
607    /// `None` where nothing took the step, and once it has ended.
608    id: Option<String>,
609}
610
611impl OpenStep<'_> {
612    /// Says the step ended, with `error` if it failed.
613    async fn end(&mut self, error: Option<String>) {
614        let Some(id) = self.id.take() else {
615            return;
616        };
617        let params = match error {
618            Some(error) => serde_json::json!({"id": id, "error": error}),
619            None => serde_json::json!({"id": id}),
620        };
621        self.steps.post("stepEnd", &params).await;
622    }
623}
624
625impl Drop for OpenStep<'_> {
626    fn drop(&mut self) {
627        let Some(id) = self.id.take() else {
628            return;
629        };
630        if self.steps.silent() {
631            return;
632        }
633        let error = match std::thread::panicking() {
634            true => "the statement panicked",
635            false => "the statement did not finish",
636        };
637        let body = serde_json::json!({"id": id, "error": error}).to_string();
638        // Nothing can be awaited here, and the runtime may be on its way
639        // out with the test: said on this thread, to this machine, briefly.
640        let _ = post_now(&format!("{}/stepEnd", self.steps.url), &body);
641    }
642}
643
644/// POSTs `body`, as JSON, to the `http://` address `url` of this machine,
645/// without a runtime, and does not wait for more than the answer's start.
646fn post_now(url: &str, body: &str) -> std::io::Result<()> {
647    use std::io::{Read as _, Write as _};
648    use std::net::{TcpStream, ToSocketAddrs as _};
649
650    let invalid = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "not an http:// URL");
651    let rest = url.strip_prefix("http://").ok_or_else(invalid)?;
652    let (authority, path) = match rest.find('/') {
653        Some(at) => rest.split_at(at),
654        None => (rest, "/"),
655    };
656    let addr = authority.to_socket_addrs()?.next().ok_or_else(invalid)?;
657    let mut stream = TcpStream::connect_timeout(&addr, STEP_LEFT_TIMEOUT)?;
658    stream.set_write_timeout(Some(STEP_LEFT_TIMEOUT))?;
659    stream.set_read_timeout(Some(STEP_LEFT_TIMEOUT))?;
660    write!(
661        stream,
662        "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/json\r\n\
663         Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
664        body.len()
665    )?;
666    stream.flush()?;
667    // Until the endpoint has taken it: its answer says nothing more.
668    let mut first = [0u8; 16];
669    let _ = stream.read(&mut first);
670    Ok(())
671}
672
673/// Says how a test run by `#[encore::test]` ended, and for a system test
674/// that failed, what it caused in the app: on standard error, under the
675/// failure the test harness prints.
676pub(super) struct Reported {
677    scope: Arc<super::Scope>,
678    ended: std::cell::Cell<bool>,
679}
680
681impl Reported {
682    pub(super) fn new(scope: Arc<super::Scope>) -> Self {
683        Reported {
684            scope,
685            ended: std::cell::Cell::new(false),
686        }
687    }
688
689    /// The test returned.
690    pub(super) fn ended(&self, failed: bool) {
691        self.ended.set(true);
692        self.report(failed);
693    }
694
695    fn report(&self, failed: bool) {
696        // A test that never reached Encore caused nothing in the app, and
697        // is not what starts the runtime.
698        let Some(test) = self.scope.core.get() else {
699            return;
700        };
701        if !crate::runtime::initialized().is_some_and(|core| core.system_test().is_some()) {
702            return;
703        }
704        test.set_outcome(match failed {
705            true => Outcome::Failed,
706            false => Outcome::Passed,
707        });
708        if !failed {
709            return;
710        }
711        // As it is now: a failed test may have left the app at work.
712        if let Ok(recorded) = test.telemetry(false, None) {
713            let tree = recorded.render();
714            if !tree.is_empty() {
715                eprintln!("\nWhat this test caused in the app:");
716                for line in tree.lines() {
717                    eprintln!("  {line}");
718                }
719            }
720        }
721    }
722}
723
724impl Drop for Reported {
725    fn drop(&mut self) {
726        // A test that never returned panicked.
727        if !self.ended.get() && std::thread::panicking() {
728            self.report(true);
729        }
730    }
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736    use std::io::{Read as _, Write as _};
737    use std::net::TcpListener;
738    use std::sync::Mutex;
739
740    /// What a test's statements and the endpoint they are reported to saw,
741    /// in order.
742    type Seen = Arc<Mutex<Vec<String>>>;
743
744    /// An endpoint that takes steps as a browser's does: its address, and
745    /// what it was sent, each as `<command> <body>`.
746    fn endpoint() -> (String, Seen) {
747        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
748        let url = format!("http://{}/encore/token", listener.local_addr().unwrap());
749        let seen = Seen::default();
750        let taken = seen.clone();
751        std::thread::spawn(move || {
752            for stream in listener.incoming() {
753                let Ok(mut stream) = stream else { return };
754                let mut request = Vec::new();
755                let mut buf = [0u8; 4096];
756                let (head, length) = loop {
757                    let Ok(n) = stream.read(&mut buf) else {
758                        break (0, 0);
759                    };
760                    if n == 0 {
761                        break (0, 0);
762                    }
763                    request.extend_from_slice(&buf[..n]);
764                    let Some(head) = request.windows(4).position(|w| w == b"\r\n\r\n") else {
765                        continue;
766                    };
767                    let length = String::from_utf8_lossy(&request[..head])
768                        .lines()
769                        .find_map(|line| {
770                            let (name, value) = line.split_once(':')?;
771                            name.eq_ignore_ascii_case("content-length")
772                                .then(|| value.trim().parse::<usize>().ok())?
773                        })
774                        .unwrap_or(0);
775                    break (head + 4, length);
776                };
777                while request.len() < head + length {
778                    let Ok(n) = stream.read(&mut buf) else { break };
779                    if n == 0 {
780                        break;
781                    }
782                    request.extend_from_slice(&buf[..n]);
783                }
784                let text = String::from_utf8_lossy(&request).into_owned();
785                let command = text
786                    .split_whitespace()
787                    .nth(1)
788                    .and_then(|path| path.rsplit('/').next())
789                    .unwrap_or_default()
790                    .to_string();
791                let body = text.get(head..).unwrap_or_default().to_string();
792                let answer = match command.as_str() {
793                    "stepBegin" => r#"{"id":"0123456789abcdef"}"#,
794                    _ => "{}",
795                };
796                taken.lock().unwrap().push(format!("{command} {body}"));
797                let _ = write!(
798                    stream,
799                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
800                     Content-Length: {}\r\nConnection: close\r\n\r\n{answer}",
801                    answer.len()
802                );
803            }
804        });
805        (url, seen)
806    }
807
808    fn browser_at(steps_url: &str) -> Browser {
809        Browser::at(
810            "ws://127.0.0.1:1/devtools/browser/token",
811            steps_url,
812            &[
813                ("api", "http://127.0.0.1:4001"),
814                ("proxy", "http://127.0.0.1:4000"),
815            ],
816        )
817    }
818
819    fn json(line: &str) -> serde_json::Value {
820        let (_, body) = line.split_once(' ').unwrap();
821        serde_json::from_str(body).unwrap()
822    }
823
824    #[tokio::test]
825    async fn a_step_has_begun_before_its_statement_runs() {
826        let (url, seen) = endpoint();
827        let browser = browser_at(&url);
828        let ran = seen.clone();
829        let line = line!() + 2;
830        let answer = browser
831            .step("pay", async move {
832                ran.lock().unwrap().push("ran".to_string());
833                42
834            })
835            .await;
836        assert_eq!(answer, 42);
837
838        let seen = seen.lock().unwrap().clone();
839        assert_eq!(seen.len(), 3, "{seen:?}");
840        assert!(seen[0].starts_with("stepBegin "), "{seen:?}");
841        assert_eq!(seen[1], "ran");
842        assert!(seen[2].starts_with("stepEnd "), "{seen:?}");
843        let begun = json(&seen[0]);
844        assert_eq!(begun["name"], "pay");
845        // Where the test said it, not where the SDK reports it from.
846        assert!(begun["file"].as_str().unwrap().ends_with("system.rs"));
847        assert_eq!(begun["line"], line);
848        let ended = json(&seen[2]);
849        assert_eq!(ended["id"], "0123456789abcdef");
850        assert!(ended.get("error").is_none());
851    }
852
853    #[tokio::test]
854    async fn a_statement_s_error_is_its_step_s() {
855        let (url, seen) = endpoint();
856        let browser = browser_at(&url);
857        let failed: Result<(), String> = browser
858            .try_step("pay", async { Err("no button#pay".to_string()) })
859            .await;
860        assert_eq!(failed.unwrap_err(), "no button#pay");
861        let said = seen.lock().unwrap().clone();
862        assert_eq!(json(&said[1])["error"], "no button#pay");
863
864        let fine: Result<u8, String> = browser.try_step("wait", async { Ok(1) }).await;
865        assert_eq!(fine, Ok(1));
866        let said = seen.lock().unwrap().clone();
867        assert!(json(&said[3]).get("error").is_none());
868    }
869
870    #[tokio::test]
871    async fn a_step_left_unfinished_ends_as_failed() {
872        let (url, seen) = endpoint();
873        let browser = browser_at(&url);
874        let waited = tokio::time::timeout(
875            Duration::from_millis(200),
876            browser.step("wait for thanks", std::future::pending::<()>()),
877        )
878        .await;
879        assert!(waited.is_err());
880        let seen = seen.lock().unwrap().clone();
881        assert_eq!(seen.len(), 2, "{seen:?}");
882        let ended = json(&seen[1]);
883        assert_eq!(ended["id"], "0123456789abcdef");
884        assert_eq!(ended["error"], "the statement did not finish");
885    }
886
887    #[tokio::test]
888    async fn with_nowhere_to_say_it_a_statement_runs_as_it_is() {
889        // No endpoint: a browser that takes no steps.
890        let browser = browser_at("");
891        assert_eq!(browser.step("pay", async { 1 }).await, 1);
892
893        // One that has gone: a port nothing listens on.
894        let closed = TcpListener::bind("127.0.0.1:0").unwrap();
895        let url = format!("http://{}/encore/token", closed.local_addr().unwrap());
896        drop(closed);
897        let browser = browser_at(&url);
898        assert_eq!(browser.step("pay", async { 2 }).await, 2);
899        // And is not asked again.
900        assert!(browser.inner.steps.silent());
901        let again: Result<u8, String> = browser.try_step("pay", async { Ok(3) }).await;
902        assert_eq!(again, Ok(3));
903    }
904
905    #[test]
906    fn a_name_the_app_has_none_of_says_what_it_has() {
907        let browser = browser_at("");
908        assert_eq!(browser.url("api").unwrap(), "http://127.0.0.1:4001");
909        let err = browser.url("web").unwrap_err();
910        assert_eq!(err.code, ErrCode::NotFound);
911        // The service proxy is no gateway or frontend to name.
912        assert!(err.message.ends_with("(it has: api)"), "{}", err.message);
913    }
914
915    #[test]
916    fn a_step_s_end_is_said_without_a_runtime() {
917        let (url, seen) = endpoint();
918        post_now(&format!("{url}/stepEnd"), r#"{"id":"ab"}"#).unwrap();
919        let seen = seen.lock().unwrap().clone();
920        assert_eq!(seen, vec![r#"stepEnd {"id":"ab"}"#.to_string()]);
921        assert!(post_now("https://example.com/x", "{}").is_err());
922    }
923}