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