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
151    tokio::task::spawn_blocking(move || {
152        test.scope
153            .core_scope()?
154            .settled(timeout)
155            .map_err(not_settled)
156    })
157    .await
158    .map_err(|err| Error::internal(format!("waiting for the app to settle: {err}")))?
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            // The core's TLS, though this client speaks none: reqwest's own
545            // does not build on a Linux machine without CA certificates.
546            .tls_backend_preconfigured(encore_sdk_core::tls::http_client_config())
547            // This machine's own address: never through a proxy.
548            .no_proxy()
549            // Each test may run in a runtime of its own, and a connection
550            // kept from one test is not the next one's to use.
551            .pool_max_idle_per_host(0)
552            .timeout(STEP_TIMEOUT)
553            .build()
554            .unwrap_or_default()
555    })
556}
557
558impl Steps {
559    fn new(url: String) -> Self {
560        Steps {
561            url,
562            gone: AtomicBool::new(false),
563        }
564    }
565
566    fn silent(&self) -> bool {
567        self.url.is_empty() || self.gone.load(Ordering::Relaxed)
568    }
569
570    /// Sends a command, and returns its answer. `None` once the endpoint
571    /// has failed to answer one: not Encore's browser, or it has closed,
572    /// and the test goes on as it is.
573    async fn post(&self, command: &str, params: &serde_json::Value) -> Option<serde_json::Value> {
574        if self.silent() {
575            return None;
576        }
577        let sent = steps_client()
578            .post(format!("{}/{command}", self.url))
579            .json(params)
580            .send()
581            .await
582            .and_then(|response| response.error_for_status());
583        let answer = match sent {
584            Ok(response) => response.json().await.ok(),
585            Err(_) => None,
586        };
587        if answer.is_none() {
588            self.gone.store(true, Ordering::Relaxed);
589        }
590        answer
591    }
592
593    /// Says the step `name`, written at `at`, begins. Returns once the
594    /// endpoint has taken it, so that what the caller has the browser do
595    /// next comes after it.
596    async fn begin<'a>(&'a self, name: &str, at: &Location<'_>) -> OpenStep<'a> {
597        let params = serde_json::json!({"name": name, "file": at.file(), "line": at.line()});
598        let id = self
599            .post("stepBegin", &params)
600            .await
601            .and_then(|answer| answer["id"].as_str().map(str::to_string));
602        OpenStep { steps: self, id }
603    }
604}
605
606/// A step that has begun, and not ended. Dropped without [`end`](Self::end)
607/// — its statement panicked, or was dropped unfinished — it ends as failed.
608struct OpenStep<'a> {
609    steps: &'a Steps,
610    /// `None` where nothing took the step, and once it has ended.
611    id: Option<String>,
612}
613
614impl OpenStep<'_> {
615    /// Says the step ended, with `error` if it failed.
616    async fn end(&mut self, error: Option<String>) {
617        let Some(id) = self.id.take() else {
618            return;
619        };
620        let params = match error {
621            Some(error) => serde_json::json!({"id": id, "error": error}),
622            None => serde_json::json!({"id": id}),
623        };
624        self.steps.post("stepEnd", &params).await;
625    }
626}
627
628impl Drop for OpenStep<'_> {
629    fn drop(&mut self) {
630        let Some(id) = self.id.take() else {
631            return;
632        };
633        if self.steps.silent() {
634            return;
635        }
636        let error = match std::thread::panicking() {
637            true => "the statement panicked",
638            false => "the statement did not finish",
639        };
640        let body = serde_json::json!({"id": id, "error": error}).to_string();
641        // Nothing can be awaited here, and the runtime may be on its way
642        // out with the test: said on this thread, to this machine, briefly.
643        let _ = post_now(&format!("{}/stepEnd", self.steps.url), &body);
644    }
645}
646
647/// POSTs `body`, as JSON, to the `http://` address `url` of this machine,
648/// without a runtime, and does not wait for more than the answer's start.
649fn post_now(url: &str, body: &str) -> std::io::Result<()> {
650    use std::io::{Read as _, Write as _};
651    use std::net::{TcpStream, ToSocketAddrs as _};
652
653    let invalid = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "not an http:// URL");
654    let rest = url.strip_prefix("http://").ok_or_else(invalid)?;
655    let (authority, path) = match rest.find('/') {
656        Some(at) => rest.split_at(at),
657        None => (rest, "/"),
658    };
659    let addr = authority.to_socket_addrs()?.next().ok_or_else(invalid)?;
660    let mut stream = TcpStream::connect_timeout(&addr, STEP_LEFT_TIMEOUT)?;
661    stream.set_write_timeout(Some(STEP_LEFT_TIMEOUT))?;
662    stream.set_read_timeout(Some(STEP_LEFT_TIMEOUT))?;
663    write!(
664        stream,
665        "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/json\r\n\
666         Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
667        body.len()
668    )?;
669    stream.flush()?;
670    // Until the endpoint has taken it: its answer says nothing more.
671    let mut first = [0u8; 16];
672    let _ = stream.read(&mut first);
673    Ok(())
674}
675
676/// Says how a test run by `#[encore::test]` ended, and for a system test
677/// that failed, what it caused in the app: on standard error, under the
678/// failure the test harness prints.
679pub(super) struct Reported {
680    scope: Arc<super::Scope>,
681    ended: std::cell::Cell<bool>,
682}
683
684impl Reported {
685    pub(super) fn new(scope: Arc<super::Scope>) -> Self {
686        Reported {
687            scope,
688            ended: std::cell::Cell::new(false),
689        }
690    }
691
692    /// The test returned.
693    pub(super) fn ended(&self, failed: bool) {
694        self.ended.set(true);
695        self.report(failed);
696    }
697
698    fn report(&self, failed: bool) {
699        // A test that never reached Encore caused nothing in the app, and
700        // is not what starts the runtime.
701        let Some(test) = self.scope.core.get() else {
702            return;
703        };
704        if !crate::runtime::initialized().is_some_and(|core| core.system_test().is_some()) {
705            return;
706        }
707        test.set_outcome(match failed {
708            true => Outcome::Failed,
709            false => Outcome::Passed,
710        });
711        if !failed {
712            return;
713        }
714        // As it is now: a failed test may have left the app at work.
715        if let Ok(recorded) = test.telemetry(false, None) {
716            let tree = recorded.render();
717            if !tree.is_empty() {
718                eprintln!("\nWhat this test caused in the app:");
719                for line in tree.lines() {
720                    eprintln!("  {line}");
721                }
722            }
723        }
724    }
725}
726
727impl Drop for Reported {
728    fn drop(&mut self) {
729        // A test that never returned panicked.
730        if !self.ended.get() && std::thread::panicking() {
731            self.report(true);
732        }
733    }
734}
735
736#[cfg(test)]
737mod tests {
738    use super::*;
739    use std::io::{Read as _, Write as _};
740    use std::net::TcpListener;
741    use std::sync::Mutex;
742
743    /// What a test's statements and the endpoint they are reported to saw,
744    /// in order.
745    type Seen = Arc<Mutex<Vec<String>>>;
746
747    /// An endpoint that takes steps as a browser's does: its address, and
748    /// what it was sent, each as `<command> <body>`.
749    fn endpoint() -> (String, Seen) {
750        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
751        let url = format!("http://{}/encore/token", listener.local_addr().unwrap());
752        let seen = Seen::default();
753        let taken = seen.clone();
754        std::thread::spawn(move || {
755            for stream in listener.incoming() {
756                let Ok(mut stream) = stream else { return };
757                let mut request = Vec::new();
758                let mut buf = [0u8; 4096];
759                let (head, length) = loop {
760                    let Ok(n) = stream.read(&mut buf) else {
761                        break (0, 0);
762                    };
763                    if n == 0 {
764                        break (0, 0);
765                    }
766                    request.extend_from_slice(&buf[..n]);
767                    let Some(head) = request.windows(4).position(|w| w == b"\r\n\r\n") else {
768                        continue;
769                    };
770                    let length = String::from_utf8_lossy(&request[..head])
771                        .lines()
772                        .find_map(|line| {
773                            let (name, value) = line.split_once(':')?;
774                            name.eq_ignore_ascii_case("content-length")
775                                .then(|| value.trim().parse::<usize>().ok())?
776                        })
777                        .unwrap_or(0);
778                    break (head + 4, length);
779                };
780                while request.len() < head + length {
781                    let Ok(n) = stream.read(&mut buf) else { break };
782                    if n == 0 {
783                        break;
784                    }
785                    request.extend_from_slice(&buf[..n]);
786                }
787                let text = String::from_utf8_lossy(&request).into_owned();
788                let command = text
789                    .split_whitespace()
790                    .nth(1)
791                    .and_then(|path| path.rsplit('/').next())
792                    .unwrap_or_default()
793                    .to_string();
794                let body = text.get(head..).unwrap_or_default().to_string();
795                let answer = match command.as_str() {
796                    "stepBegin" => r#"{"id":"0123456789abcdef"}"#,
797                    _ => "{}",
798                };
799                taken.lock().unwrap().push(format!("{command} {body}"));
800                let _ = write!(
801                    stream,
802                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
803                     Content-Length: {}\r\nConnection: close\r\n\r\n{answer}",
804                    answer.len()
805                );
806            }
807        });
808        (url, seen)
809    }
810
811    fn browser_at(steps_url: &str) -> Browser {
812        Browser::at(
813            "ws://127.0.0.1:1/devtools/browser/token",
814            steps_url,
815            &[
816                ("api", "http://127.0.0.1:4001"),
817                ("proxy", "http://127.0.0.1:4000"),
818            ],
819        )
820    }
821
822    fn json(line: &str) -> serde_json::Value {
823        let (_, body) = line.split_once(' ').unwrap();
824        serde_json::from_str(body).unwrap()
825    }
826
827    #[tokio::test]
828    async fn a_step_has_begun_before_its_statement_runs() {
829        let (url, seen) = endpoint();
830        let browser = browser_at(&url);
831        let ran = seen.clone();
832        let line = line!() + 2;
833        let answer = browser
834            .step("pay", async move {
835                ran.lock().unwrap().push("ran".to_string());
836                42
837            })
838            .await;
839        assert_eq!(answer, 42);
840
841        let seen = seen.lock().unwrap().clone();
842        assert_eq!(seen.len(), 3, "{seen:?}");
843        assert!(seen[0].starts_with("stepBegin "), "{seen:?}");
844        assert_eq!(seen[1], "ran");
845        assert!(seen[2].starts_with("stepEnd "), "{seen:?}");
846        let begun = json(&seen[0]);
847        assert_eq!(begun["name"], "pay");
848        // Where the test said it, not where the SDK reports it from.
849        assert!(begun["file"].as_str().unwrap().ends_with("system.rs"));
850        assert_eq!(begun["line"], line);
851        let ended = json(&seen[2]);
852        assert_eq!(ended["id"], "0123456789abcdef");
853        assert!(ended.get("error").is_none());
854    }
855
856    #[tokio::test]
857    async fn a_statement_s_error_is_its_step_s() {
858        let (url, seen) = endpoint();
859        let browser = browser_at(&url);
860        let failed: Result<(), String> = browser
861            .try_step("pay", async { Err("no button#pay".to_string()) })
862            .await;
863        assert_eq!(failed.unwrap_err(), "no button#pay");
864        let said = seen.lock().unwrap().clone();
865        assert_eq!(json(&said[1])["error"], "no button#pay");
866
867        let fine: Result<u8, String> = browser.try_step("wait", async { Ok(1) }).await;
868        assert_eq!(fine, Ok(1));
869        let said = seen.lock().unwrap().clone();
870        assert!(json(&said[3]).get("error").is_none());
871    }
872
873    #[tokio::test]
874    async fn a_step_left_unfinished_ends_as_failed() {
875        let (url, seen) = endpoint();
876        let browser = browser_at(&url);
877        let waited = tokio::time::timeout(
878            Duration::from_millis(200),
879            browser.step("wait for thanks", std::future::pending::<()>()),
880        )
881        .await;
882        assert!(waited.is_err());
883        let seen = seen.lock().unwrap().clone();
884        assert_eq!(seen.len(), 2, "{seen:?}");
885        let ended = json(&seen[1]);
886        assert_eq!(ended["id"], "0123456789abcdef");
887        assert_eq!(ended["error"], "the statement did not finish");
888    }
889
890    #[tokio::test]
891    async fn with_nowhere_to_say_it_a_statement_runs_as_it_is() {
892        // No endpoint: a browser that takes no steps.
893        let browser = browser_at("");
894        assert_eq!(browser.step("pay", async { 1 }).await, 1);
895
896        // One that has gone: a port nothing listens on.
897        let closed = TcpListener::bind("127.0.0.1:0").unwrap();
898        let url = format!("http://{}/encore/token", closed.local_addr().unwrap());
899        drop(closed);
900        let browser = browser_at(&url);
901        assert_eq!(browser.step("pay", async { 2 }).await, 2);
902        // And is not asked again.
903        assert!(browser.inner.steps.silent());
904        let again: Result<u8, String> = browser.try_step("pay", async { Ok(3) }).await;
905        assert_eq!(again, Ok(3));
906    }
907
908    #[test]
909    fn a_name_the_app_has_none_of_says_what_it_has() {
910        let browser = browser_at("");
911        assert_eq!(browser.url("api").unwrap(), "http://127.0.0.1:4001");
912        let err = browser.url("web").unwrap_err();
913        assert_eq!(err.code, ErrCode::NotFound);
914        // The service proxy is no gateway or frontend to name.
915        assert!(err.message.ends_with("(it has: api)"), "{}", err.message);
916    }
917
918    #[test]
919    fn a_step_s_end_is_said_without_a_runtime() {
920        let (url, seen) = endpoint();
921        post_now(&format!("{url}/stepEnd"), r#"{"id":"ab"}"#).unwrap();
922        let seen = seen.lock().unwrap().clone();
923        assert_eq!(seen, vec![r#"stepEnd {"id":"ab"}"#.to_string()]);
924        assert!(post_now("https://example.com/x", "{}").is_err());
925    }
926}