Skip to main content

encore/testing/
system.rs

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