Skip to main content

ocre/
testing.rs

1//! Test helpers for Ocre apps, like Rails' `ActionDispatch::IntegrationTest`
2//! and `ActiveSupport::Testing`: a request client for the running app, the
3//! test database, the server log, time travel and assertions.
4//!
5//! Feature `testing`, native builds only: a generated app lists
6//! `ocre = { ..., features = ["testing"] }` under `[dev-dependencies]`, so the
7//! module is in `cargo test` and never in the WebAssembly build.
8//!
9//! # How request tests run
10//!
11//! Handlers need workerd (D1, KV, Queues... exist only there), so request
12//! tests talk HTTP to the real runtime. `ocre test --e2e`:
13//!
14//! 1. creates a fresh local D1 database in `.wrangler/test-state` (the
15//!    development data in `.wrangler/state` is untouched), applies the
16//!    migrations and loads the fixtures of `tests/fixtures/`,
17//! 2. starts one `cf dev` on that state for the whole run, logging to
18//!    `.wrangler/test-state/dev.log`,
19//! 3. runs `cargo test -- --ignored` with [`TEST_URL`], [`TEST_STATE`] and
20//!    [`TEST_LOG`] set. In an Ocre app, `#[ignore]` marks the tests that need
21//!    the runtime: plain `cargo test` (and `ocre test`) skips them.
22//!
23//! ```no_run
24//! // tests/posts.rs
25//! use ocre::testing::Client;
26//!
27//! #[test]
28//! #[ignore = "request test: run with `ocre test --e2e`"]
29//! fn creates_a_post() {
30//!     let mut client = Client::new();
31//!     let created = client.post("/posts", &[("title", "Hello"), ("body", "First post")]);
32//!     created.assert_redirect_to("/posts/1");
33//!     assert_eq!(client.flash("notice").as_deref(), Some("Post was successfully created."));
34//!     client.follow_redirect(&created).assert_status(200).assert_contains("Hello");
35//! }
36//! ```
37//!
38//! There are no per-test transactions (Rails' transactional tests): the
39//! database belongs to the `cf dev` process, which the test process reaches
40//! only over HTTP or through wrangler. The database is fresh for each run;
41//! tests running in parallel share it, so they create their own records
42//! (factories give unique values) and assert on them rather than on global
43//! counts, or run with `-- --test-threads=1`.
44
45use std::{
46    collections::BTreeMap,
47    fmt::Debug,
48    path::{Path, PathBuf},
49    process::Command,
50    time::{Duration, Instant},
51};
52
53use cookie::{Cookie, CookieJar, Key};
54use serde::{Serialize, de::DeserializeOwned};
55use serde_json::{Map, Value};
56
57use crate::{SESSION_COOKIE, mail::Email};
58
59mod fake;
60
61pub use fake::{FakeServer, ReceivedRequest};
62
63/// Environment variable holding the base URL of the server `ocre test --e2e` started.
64///
65/// # Examples
66///
67/// ```
68/// assert_eq!(ocre::testing::TEST_URL, "OCRE_TEST_URL");
69/// ```
70pub const TEST_URL: &str = "OCRE_TEST_URL";
71
72/// Environment variable holding the local state directory of the test run (`.wrangler/test-state`).
73///
74/// # Examples
75///
76/// ```
77/// assert_eq!(ocre::testing::TEST_STATE, "OCRE_TEST_STATE");
78/// ```
79pub const TEST_STATE: &str = "OCRE_TEST_STATE";
80
81/// Environment variable holding the path of the test server's log.
82///
83/// # Examples
84///
85/// ```
86/// assert_eq!(ocre::testing::TEST_LOG, "OCRE_TEST_LOG");
87/// ```
88pub const TEST_LOG: &str = "OCRE_TEST_LOG";
89
90/// How long [`eventually`] and [`Log::wait_for`] wait.
91const WAIT: Duration = Duration::from_secs(30);
92
93/// An HTTP client for request tests, with a cookie jar, like a browser tab
94/// (Rails' integration session).
95///
96/// Every request carries `Sec-Fetch-Site: same-origin`, as a browser's
97/// same-site form does, so Ocre's cross-site request check passes; use
98/// [`Client::cross_site`] to test the check. Cookies from `Set-Cookie`
99/// are sent back on the next requests, so a sign-in, the session and flash
100/// messages carry over. Redirects are not followed automatically: assert on
101/// them, then call [`Client::follow_redirect`]. Two clients are two
102/// independent visitors (Rails' `open_session`).
103///
104/// # Examples
105///
106/// ```no_run
107/// use ocre::testing::Client;
108///
109/// let mut client = Client::new();
110/// client.get("/up").assert_status(200).assert_contains("OK");
111/// ```
112#[derive(Debug)]
113pub struct Client {
114    agent: ureq::Agent,
115    base: String,
116    headers: Vec<(String, String)>,
117    /// `name` -> value as the server sent it (percent-encoded).
118    cookies: BTreeMap<String, String>,
119}
120
121impl Client {
122    /// A client for the server `ocre test --e2e` started ([`TEST_URL`]).
123    ///
124    /// # Panics
125    ///
126    /// When [`TEST_URL`] is not set: the test was run with plain `cargo test -- --ignored`.
127    ///
128    /// # Examples
129    ///
130    /// ```no_run
131    /// let mut client = ocre::testing::Client::new();
132    /// client.get("/").assert_success();
133    /// ```
134    #[allow(clippy::new_without_default)]
135    pub fn new() -> Self {
136        let base = std::env::var(TEST_URL).unwrap_or_else(|_| {
137            panic!("{TEST_URL} is not set. Fix: run request tests with `ocre test --e2e`, which starts the server")
138        });
139        Self::with_base_url(&base)
140    }
141
142    /// A client for the app at `base` (`http://localhost:8787`), e.g. a running `ocre dev`.
143    ///
144    /// # Examples
145    ///
146    /// ```no_run
147    /// let mut client = ocre::testing::Client::with_base_url("http://localhost:8787");
148    /// client.get("/up").assert_status(200);
149    /// ```
150    pub fn with_base_url(base: &str) -> Self {
151        let agent = ureq::Agent::config_builder()
152            .http_status_as_error(false)
153            .max_redirects(0)
154            .allow_non_standard_methods(true)
155            .timeout_global(Some(Duration::from_secs(60)))
156            .build()
157            .into();
158        Self {
159            agent,
160            base: base.trim_end_matches('/').to_owned(),
161            headers: vec![("sec-fetch-site".to_owned(), "same-origin".to_owned())],
162            cookies: BTreeMap::new(),
163        }
164    }
165
166    /// Sends `name: value` with every request (Rails' `headers:`); replaces
167    /// an earlier value of the same header.
168    ///
169    /// # Examples
170    ///
171    /// ```no_run
172    /// let mut client = ocre::testing::Client::new().header("Accept-Language", "fr");
173    /// client.get("/").assert_contains("Bienvenue");
174    /// ```
175    pub fn header(mut self, name: &str, value: &str) -> Self {
176        let name = name.to_ascii_lowercase();
177        self.headers.retain(|(existing, _)| *existing != name);
178        self.headers.push((name, value.to_owned()));
179        self
180    }
181
182    /// Requests as a form posted from another site would (`Sec-Fetch-Site: cross-site`):
183    /// Ocre's CSRF protection answers 403 to unsafe methods.
184    ///
185    /// # Examples
186    ///
187    /// ```no_run
188    /// let mut client = ocre::testing::Client::new().cross_site();
189    /// client.post("/posts", &[("title", "x")]).assert_status(403);
190    /// ```
191    pub fn cross_site(self) -> Self {
192        self.header("Sec-Fetch-Site", "cross-site")
193    }
194
195    /// Requests as htmx does (`HX-Request: true`), Rails' `xhr: true`.
196    ///
197    /// # Examples
198    ///
199    /// ```no_run
200    /// let mut client = ocre::testing::Client::new().htmx();
201    /// client.get("/posts").assert_not_contains("<html");
202    /// ```
203    pub fn htmx(self) -> Self {
204        self.header("HX-Request", "true")
205    }
206
207    /// `GET path`.
208    ///
209    /// # Examples
210    ///
211    /// ```no_run
212    /// ocre::testing::Client::new().get("/posts?page=2").assert_status(200);
213    /// ```
214    pub fn get(&mut self, path: &str) -> Response {
215        self.request("GET", path, None)
216    }
217
218    /// `POST path` with an `application/x-www-form-urlencoded` body, as an HTML form sends it.
219    ///
220    /// `form` is anything serde_urlencoded takes: a slice of `(name, value)`
221    /// pairs, a factory's `form()`, a struct deriving `Serialize`, or `&()` for an empty body.
222    ///
223    /// # Panics
224    ///
225    /// When `form` is not a flat list of fields.
226    ///
227    /// # Examples
228    ///
229    /// ```no_run
230    /// let mut client = ocre::testing::Client::new();
231    /// client.post("/posts", &[("title", "Hello"), ("body", "World")]).assert_status(303);
232    /// client.post("/posts/1/delete", &()).assert_redirect_to("/posts");
233    /// ```
234    pub fn post(&mut self, path: &str, form: &impl Serialize) -> Response {
235        let body = serde_urlencoded::to_string(form).expect("form fields encode");
236        self.request("POST", path, Some(("application/x-www-form-urlencoded", body.into_bytes())))
237    }
238
239    /// `POST path` with `value` as a JSON body.
240    ///
241    /// # Examples
242    ///
243    /// ```no_run
244    /// let mut client = ocre::testing::Client::new();
245    /// let created = client.post_json("/api/posts", &ocre::serde_json::json!({"title": "Hello"}));
246    /// assert_eq!(created.assert_status(201).json::<ocre::serde_json::Value>()["title"], "Hello");
247    /// ```
248    pub fn post_json(&mut self, path: &str, value: &impl Serialize) -> Response {
249        self.json("POST", path, value)
250    }
251
252    /// `PATCH path` with `value` as a JSON body.
253    ///
254    /// # Examples
255    ///
256    /// ```no_run
257    /// let mut client = ocre::testing::Client::new();
258    /// client.patch_json("/api/posts/1", &ocre::serde_json::json!({"title": "New"})).assert_status(200);
259    /// ```
260    pub fn patch_json(&mut self, path: &str, value: &impl Serialize) -> Response {
261        self.json("PATCH", path, value)
262    }
263
264    /// `PUT path` with `value` as a JSON body.
265    ///
266    /// # Examples
267    ///
268    /// ```no_run
269    /// let mut client = ocre::testing::Client::new();
270    /// client.put_json("/api/settings", &ocre::serde_json::json!({"theme": "dark"})).assert_success();
271    /// ```
272    pub fn put_json(&mut self, path: &str, value: &impl Serialize) -> Response {
273        self.json("PUT", path, value)
274    }
275
276    /// `DELETE path`.
277    ///
278    /// # Examples
279    ///
280    /// ```no_run
281    /// ocre::testing::Client::new().delete("/api/posts/1").assert_status(204);
282    /// ```
283    pub fn delete(&mut self, path: &str) -> Response {
284        self.request("DELETE", path, None)
285    }
286
287    fn json(&mut self, method: &str, path: &str, value: &impl Serialize) -> Response {
288        let body = serde_json::to_vec(value).expect("the value serializes to JSON");
289        self.request(method, path, Some(("application/json", body)))
290    }
291
292    /// Sends `method path` with an optional `(content type, body)`: any
293    /// method, any body (multipart uploads, raw bytes).
294    ///
295    /// # Panics
296    ///
297    /// When the server cannot be reached.
298    ///
299    /// # Examples
300    ///
301    /// ```no_run
302    /// let mut client = ocre::testing::Client::new();
303    /// client.request("HEAD", "/up", None).assert_status(200);
304    /// client.request("POST", "/api/raw", Some(("text/plain", b"bytes".to_vec()))).assert_success();
305    /// ```
306    pub fn request(&mut self, method: &str, path: &str, body: Option<(&str, Vec<u8>)>) -> Response {
307        let url = format!("{}{path}", self.base);
308        let mut builder = ureq::http::Request::builder().method(method).uri(&url);
309        for (name, value) in &self.headers {
310            builder = builder.header(name, value);
311        }
312        if !self.cookies.is_empty() {
313            let cookies: Vec<String> = self.cookies.iter().map(|(name, value)| format!("{name}={value}")).collect();
314            builder = builder.header("cookie", cookies.join("; "));
315        }
316        let result = match body {
317            Some((content_type, bytes)) => {
318                self.agent.run(builder.header("content-type", content_type).body(bytes).expect("valid request"))
319            }
320            None => self.agent.run(builder.body(()).expect("valid request")),
321        };
322        let mut response = result.unwrap_or_else(|err| panic!("{method} {url} failed: {err}"));
323        let headers: Vec<(String, String)> = response
324            .headers()
325            .iter()
326            .map(|(name, value)| (name.as_str().to_owned(), String::from_utf8_lossy(value.as_bytes()).into_owned()))
327            .collect();
328        for (name, value) in &headers {
329            if name == "set-cookie" {
330                self.store_cookie(value);
331            }
332        }
333        let status = response.status().as_u16();
334        let body = if method == "HEAD" || status == 204 || status == 304 {
335            String::new()
336        } else {
337            let bytes = body_bytes(response.body_mut().read_to_vec(), method, &url);
338            String::from_utf8_lossy(&bytes).into_owned()
339        };
340        Response { status, headers, body }
341    }
342
343    fn store_cookie(&mut self, set_cookie: &str) {
344        let Ok(cookie) = Cookie::parse(set_cookie) else { return };
345        let removed = cookie.value().is_empty() || cookie.max_age().is_some_and(|max_age| max_age.whole_seconds() <= 0);
346        if removed {
347            self.cookies.remove(cookie.name());
348        } else {
349            self.cookies.insert(cookie.name().to_owned(), cookie.value().to_owned());
350        }
351    }
352
353    /// Follows the redirect `response` answered: `GET` of its `Location` (Rails' `follow_redirect!`).
354    ///
355    /// # Panics
356    ///
357    /// When `response` has no `Location` header.
358    ///
359    /// # Examples
360    ///
361    /// ```no_run
362    /// let mut client = ocre::testing::Client::new();
363    /// let created = client.post("/posts", &[("title", "Hello"), ("body", "World")]);
364    /// client.follow_redirect(&created).assert_contains("Post was successfully created.");
365    /// ```
366    pub fn follow_redirect(&mut self, response: &Response) -> Response {
367        let location = response.location().unwrap_or_else(|| {
368            panic!("expected a redirect, got {} without a Location header:\n{}", response.status, response.excerpt())
369        });
370        let path = location.strip_prefix(&self.base).unwrap_or(location).to_owned();
371        self.get(&path)
372    }
373
374    /// The cookie `name` as the server set it (percent-encoded), if the jar has it.
375    ///
376    /// # Examples
377    ///
378    /// ```no_run
379    /// let mut client = ocre::testing::Client::new();
380    /// client.get("/");
381    /// assert!(client.cookie("_ocre_session").is_none());
382    /// ```
383    pub fn cookie(&self, name: &str) -> Option<&str> {
384        self.cookies.get(name).map(String::as_str)
385    }
386
387    /// Sets a cookie sent with the next requests, as if the server had set it.
388    ///
389    /// # Examples
390    ///
391    /// ```no_run
392    /// let mut client = ocre::testing::Client::new();
393    /// client.set_cookie("locale", "fr");
394    /// ```
395    pub fn set_cookie(&mut self, name: &str, value: &str) {
396        self.cookies.insert(name.to_owned(), value.to_owned());
397    }
398
399    /// The session data (Rails' `session` in tests), decrypted with the
400    /// app's `SECRET_KEY_BASE` (the environment variable, else `.dev.vars`):
401    /// empty without a session cookie. Flash messages set for the next
402    /// request are under `_flash`: [`Client::flash`] reads them.
403    ///
404    /// # Panics
405    ///
406    /// When there is a session cookie but no `SECRET_KEY_BASE`, or the
407    /// cookie does not decrypt with it.
408    ///
409    /// # Examples
410    ///
411    /// ```no_run
412    /// let mut client = ocre::testing::Client::new();
413    /// client.post("/session", &[("email", "ada@example.com"), ("password", "secret")]);
414    /// assert!(client.session().contains_key("user_id"));
415    /// ```
416    pub fn session(&self) -> Map<String, Value> {
417        let Some(value) = self.cookies.get(SESSION_COOKIE) else { return Map::new() };
418        let secret = var("SECRET_KEY_BASE")
419            .expect("SECRET_KEY_BASE is not set (environment or .dev.vars): cannot read the session");
420        decrypt_session(value, &secret).expect("the session cookie does not decrypt with SECRET_KEY_BASE")
421    }
422
423    /// The flash message of `kind` (`notice`, `alert`...) set by the last
424    /// request for the next page (Rails' `flash[:notice]` after an action).
425    ///
426    /// # Examples
427    ///
428    /// ```no_run
429    /// let mut client = ocre::testing::Client::new();
430    /// client.post("/posts", &[("title", "Hello"), ("body", "World")]);
431    /// assert_eq!(client.flash("notice").as_deref(), Some("Post was successfully created."));
432    /// ```
433    pub fn flash(&self, kind: &str) -> Option<String> {
434        self.session().get("_flash")?.get(kind)?.as_str().map(str::to_owned)
435    }
436
437    /// Emails the app sent with `MAIL_ADAPTER = "log"` (Rails'
438    /// `ActionMailer::Base.deliveries`), oldest first: the last 20, kept by
439    /// the Worker instance. Reads `GET /ocre/dev/mailers/sent.json`, which
440    /// exists when `routes()` merges `ocre::mail::dev_routes` (`ocre g mailer` adds it).
441    ///
442    /// # Panics
443    ///
444    /// When the endpoint does not answer a JSON list.
445    ///
446    /// # Examples
447    ///
448    /// ```no_run
449    /// let mut client = ocre::testing::Client::new();
450    /// let before = client.deliveries().len();
451    /// client.post("/passwords", &[("email", "ada@example.com")]);
452    /// let sent = client.deliveries();
453    /// assert_eq!(sent.len(), before + 1);
454    /// assert_eq!(sent.last().unwrap().to, ["ada@example.com"]);
455    /// ```
456    pub fn deliveries(&mut self) -> Vec<Email> {
457        let response = self.get("/ocre/dev/mailers/sent.json");
458        response.assert_status(200);
459        let sent: Vec<Value> = response.json();
460        sent.into_iter()
461            .map(|entry| serde_json::from_value(entry["email"].clone()).expect("a captured email"))
462            .collect()
463    }
464
465    /// Messages the app broadcast to realtime channels (Rails'
466    /// `assert_broadcasts`), oldest first: the last 50, kept by the Worker
467    /// instance. Reads `GET /ocre/dev/realtime/sent.json`, which exists when
468    /// `routes()` merges `ocre::realtime::dev_routes()` (`ocre g scaffold ... --realtime` adds it).
469    ///
470    /// # Panics
471    ///
472    /// When the endpoint does not answer a JSON list.
473    ///
474    /// # Examples
475    ///
476    /// ```no_run
477    /// let mut client = ocre::testing::Client::new();
478    /// client.post("/posts", &[("title", "Live"), ("body", "b")]);
479    /// let last = client.broadcasts().pop().unwrap();
480    /// assert_eq!(last.channel, "posts");
481    /// assert!(last.message.contains("Live"));
482    /// ```
483    pub fn broadcasts(&mut self) -> Vec<Broadcast> {
484        let response = self.get("/ocre/dev/realtime/sent.json");
485        response.assert_status(200);
486        response.json()
487    }
488
489    /// Jobs the app enqueued and ran (Rails' `assert_enqueued_with`,
490    /// `assert_performed_jobs`): the last 50 of each, oldest first, kept by
491    /// the Worker instance. Reads `GET /ocre/dev/jobs.json`, which the first
492    /// `ocre g job` merges into `routes()` (`ocre::jobs::dev_routes()`).
493    /// Local queues deliver within a second or so: wait for a run with
494    /// [`eventually`].
495    ///
496    /// # Panics
497    ///
498    /// When the endpoint does not answer the expected JSON.
499    ///
500    /// # Examples
501    ///
502    /// ```no_run
503    /// use ocre::testing::{Client, eventually};
504    ///
505    /// let mut client = Client::new();
506    /// client.post("/signups", &[("email", "ada@example.com")]);
507    /// let jobs = client.jobs();
508    /// assert_eq!(jobs.enqueued.last().unwrap().name(), Some("send_welcome"));
509    /// eventually(|| client.jobs().performed.iter().any(|run| run.job == "send_welcome" && run.outcome == "done").then_some(()));
510    /// ```
511    pub fn jobs(&mut self) -> Jobs {
512        let response = self.get("/ocre/dev/jobs.json");
513        response.assert_status(200);
514        response.json()
515    }
516
517    /// Delivers an email to the app's mailbox (`ocre g mailbox`), as
518    /// Cloudflare Email Routing would (Rails' `receive_inbound_email_from_mail`):
519    /// a plain-text message posted to the local server's email endpoint
520    /// (`POST /cdn-cgi/local/email?from=&to=`), which runs the Worker's
521    /// `email` event. The response says whether the mailbox accepted it.
522    ///
523    /// # Examples
524    ///
525    /// ```no_run
526    /// let mut client = ocre::testing::Client::new();
527    /// client.receive_email("ada@example.com", "support@example.com", "Help", "My order is late.").assert_success();
528    /// ```
529    pub fn receive_email(&mut self, from: &str, to: &str, subject: &str, body: &str) -> Response {
530        let query = serde_urlencoded::to_string([("from", from), ("to", to)]).expect("encoding two strings");
531        let raw = raw_email(from, to, subject, body, sequence());
532        self.request("POST", &format!("/cdn-cgi/local/email?{query}"), Some(("message/rfc822", raw.into_bytes())))
533    }
534}
535
536/// A plain-text RFC 5322 message; a non-ASCII subject is RFC 2047 encoded.
537fn raw_email(from: &str, to: &str, subject: &str, body: &str, n: u64) -> String {
538    let printable = subject.bytes().all(|byte| (0x20..0x7f).contains(&byte));
539    let subject = if printable {
540        subject.to_owned()
541    } else {
542        use base64::Engine as _;
543        format!("=?UTF-8?B?{}?=", base64::engine::general_purpose::STANDARD.encode(subject))
544    };
545    let body = body.replace("\r\n", "\n").replace('\n', "\r\n");
546    format!(
547        "From: {from}\r\nTo: {to}\r\nSubject: {subject}\r\nMessage-ID: <{n}.{}@ocre.test>\r\nMIME-Version: 1.0\r\n\
548         Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n{body}",
549        crate::now()
550    )
551}
552
553/// A message broadcast to a realtime channel, from [`Client::broadcasts`].
554///
555/// # Examples
556///
557/// ```
558/// let broadcast: ocre::testing::Broadcast =
559///     ocre::serde_json::from_str(r#"{"id":1,"channel":"posts","message":"<li>Hi</li>"}"#).unwrap();
560/// assert_eq!(broadcast.channel, "posts");
561/// ```
562#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
563pub struct Broadcast {
564    /// Position in the capture, from 1.
565    pub id: u64,
566    /// The channel it went to (`posts`).
567    pub channel: String,
568    /// The message: HTML or JSON text.
569    pub message: String,
570}
571
572/// Jobs the app enqueued and ran, from [`Client::jobs`].
573///
574/// # Examples
575///
576/// ```
577/// let jobs: ocre::testing::Jobs = ocre::serde_json::from_str(
578///     r#"{"enqueued":[{"id":1,"queue":"default","job":{"send_welcome":{"user_id":7}}}],
579///         "performed":[{"id":2,"job":"send_welcome","outcome":"done"}]}"#,
580/// )
581/// .unwrap();
582/// assert_eq!(jobs.enqueued[0].name(), Some("send_welcome"));
583/// assert_eq!(jobs.performed[0].outcome, "done");
584/// ```
585#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
586pub struct Jobs {
587    /// Jobs sent to a queue, oldest first.
588    pub enqueued: Vec<EnqueuedJob>,
589    /// Jobs the queue consumer ran, oldest first.
590    pub performed: Vec<PerformedJob>,
591}
592
593/// A job sent to a queue, from [`Client::jobs`].
594#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
595pub struct EnqueuedJob {
596    /// Position in the capture, from 1 (shared with runs).
597    pub id: u64,
598    /// The queue: `default`, or the name given to `ocre::jobs::queue`.
599    pub queue: String,
600    /// The job as the app serialized it: `{"send_welcome": {"user_id": 7}}`.
601    pub job: Value,
602}
603
604impl EnqueuedJob {
605    /// The job's name: the key of its JSON object (`send_welcome`), as [`PerformedJob::job`] names it.
606    ///
607    /// # Examples
608    ///
609    /// ```
610    /// let job: ocre::testing::EnqueuedJob =
611    ///     ocre::serde_json::from_str(r#"{"id":1,"queue":"default","job":"cleanup"}"#).unwrap();
612    /// assert_eq!(job.name(), Some("cleanup"));
613    /// ```
614    pub fn name(&self) -> Option<&str> {
615        match &self.job {
616            Value::Object(map) => map.keys().next().map(String::as_str),
617            Value::String(name) => Some(name),
618            _ => None,
619        }
620    }
621}
622
623/// A job run by the queue consumer, from [`Client::jobs`].
624#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
625pub struct PerformedJob {
626    /// Position in the capture, from 1 (shared with enqueued jobs).
627    pub id: u64,
628    /// The job's name (`send_welcome`), or `mail` for `deliver_later` emails.
629    pub job: String,
630    /// `done`, `discarded` (an error a retry cannot fix) or `retried`.
631    pub outcome: String,
632}
633
634/// Runs a future to completion on the test thread: `async` handlers,
635/// helpers and `ocre::password` in plain unit tests (no async runtime runs
636/// outside workerd). It is [`pollster::block_on`].
637///
638/// # Examples
639///
640/// ```
641/// async fn up() -> &'static str {
642///     "OK"
643/// }
644///
645/// assert_eq!(ocre::testing::block_on(up()), "OK");
646/// ```
647pub use pollster::block_on;
648
649/// A variable of the app under test: the environment variable `name`, else
650/// its value in `.dev.vars` (the file `ocre dev` loads), as the Worker sees
651/// it. Request tests use it for the secrets they sign with (a webhook's).
652///
653/// # Examples
654///
655/// ```no_run
656/// let secret = ocre::testing::var("PAYMENTS_WEBHOOK_SECRET").expect("in .dev.vars");
657/// # let _ = secret;
658/// ```
659pub fn var(name: &str) -> Option<String> {
660    dev_var(name, std::env::var(name).ok(), Path::new(".dev.vars"))
661}
662
663/// `name` from the environment (`env`), else from the `dotenv` file.
664fn dev_var(name: &str, env: Option<String>, dotenv: &Path) -> Option<String> {
665    if env.is_some() {
666        return env;
667    }
668    let text = std::fs::read_to_string(dotenv).ok()?;
669    text.lines().find_map(|line| {
670        let value = line.trim().strip_prefix(name)?.trim_start().strip_prefix('=')?.trim();
671        Some(value.trim_matches('"').to_owned())
672    })
673}
674
675/// The session data in the cookie `value` (percent-encoded), `None` when it does not decrypt.
676fn decrypt_session(value: &str, secret: &str) -> Option<Map<String, Value>> {
677    let cookie = Cookie::parse_encoded(format!("{SESSION_COOKIE}={value}")).ok()?;
678    let mut jar = CookieJar::new();
679    jar.add_original(cookie.into_owned());
680    let decrypted = jar.private(&Key::derive_from(secret.as_bytes())).get(SESSION_COOKIE)?;
681    serde_json::from_str(decrypted.value()).ok()
682}
683
684/// A response in a request test, with chainable assertions (Rails'
685/// `assert_response`, `assert_redirected_to`, `assert_match`).
686///
687/// Assertions panic with the status and the start of the body, and return
688/// the response so they chain.
689///
690/// # Examples
691///
692/// ```no_run
693/// let mut client = ocre::testing::Client::new();
694/// client.get("/posts").assert_status(200).assert_contains("<h1>Posts</h1>");
695/// ```
696#[derive(Debug, Clone)]
697pub struct Response {
698    /// HTTP status code.
699    pub status: u16,
700    /// Headers in the order received, names lowercase.
701    pub headers: Vec<(String, String)>,
702    /// Body as text (invalid UTF-8 replaced); empty for `HEAD`, 204 and 304.
703    pub body: String,
704}
705
706impl Response {
707    /// The first value of the header `name` (any case).
708    ///
709    /// # Examples
710    ///
711    /// ```
712    /// let response = ocre::testing::Response { status: 200, headers: vec![("content-type".into(), "text/html".into())], body: String::new() };
713    /// assert_eq!(response.header("Content-Type"), Some("text/html"));
714    /// ```
715    pub fn header(&self, name: &str) -> Option<&str> {
716        self.headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value.as_str())
717    }
718
719    /// The `Location` header of a redirect.
720    ///
721    /// # Examples
722    ///
723    /// ```
724    /// let response = ocre::testing::Response { status: 303, headers: vec![("location".into(), "/posts/1".into())], body: String::new() };
725    /// assert_eq!(response.location(), Some("/posts/1"));
726    /// ```
727    pub fn location(&self) -> Option<&str> {
728        self.header("location")
729    }
730
731    /// The body parsed as JSON (Rails' `response.parsed_body`).
732    ///
733    /// # Panics
734    ///
735    /// When the body is not JSON of type `T`.
736    ///
737    /// # Examples
738    ///
739    /// ```
740    /// let response = ocre::testing::Response { status: 200, headers: vec![], body: r#"{"id":1}"#.into() };
741    /// assert_eq!(response.json::<ocre::serde_json::Value>()["id"], 1);
742    /// ```
743    pub fn json<T: DeserializeOwned>(&self) -> T {
744        serde_json::from_str(&self.body)
745            .unwrap_or_else(|err| panic!("the body is not the expected JSON ({err}):\n{}", self.excerpt()))
746    }
747
748    /// Asserts the status code (Rails' `assert_response 201`).
749    ///
750    /// # Examples
751    ///
752    /// ```
753    /// let response = ocre::testing::Response { status: 404, headers: vec![], body: String::new() };
754    /// response.assert_status(404);
755    /// ```
756    #[track_caller]
757    pub fn assert_status(&self, status: u16) -> &Self {
758        assert!(self.status == status, "expected status {status}, got {}:\n{}", self.status, self.excerpt());
759        self
760    }
761
762    /// Asserts a 2xx status (Rails' `assert_response :success`).
763    ///
764    /// # Examples
765    ///
766    /// ```
767    /// let response = ocre::testing::Response { status: 204, headers: vec![], body: String::new() };
768    /// response.assert_success();
769    /// ```
770    #[track_caller]
771    pub fn assert_success(&self) -> &Self {
772        assert!((200..300).contains(&self.status), "expected a 2xx status, got {}:\n{}", self.status, self.excerpt());
773        self
774    }
775
776    /// Asserts a 3xx redirect to `location` (Rails' `assert_redirected_to`).
777    ///
778    /// # Examples
779    ///
780    /// ```
781    /// let response = ocre::testing::Response { status: 303, headers: vec![("location".into(), "/posts/1".into())], body: String::new() };
782    /// response.assert_redirect_to("/posts/1");
783    /// ```
784    #[track_caller]
785    pub fn assert_redirect_to(&self, location: &str) -> &Self {
786        assert!(
787            (300..400).contains(&self.status) && self.location() == Some(location),
788            "expected a redirect to {location}, got {} to {:?}:\n{}",
789            self.status,
790            self.location(),
791            self.excerpt()
792        );
793        self
794    }
795
796    /// Asserts the body contains `text` (HTML-escaped as templates escape it: `'` is `&#39;`).
797    ///
798    /// # Examples
799    ///
800    /// ```
801    /// let response = ocre::testing::Response { status: 200, headers: vec![], body: "<h1>Posts</h1>".into() };
802    /// response.assert_contains("<h1>Posts</h1>");
803    /// ```
804    #[track_caller]
805    pub fn assert_contains(&self, text: &str) -> &Self {
806        assert!(self.body.contains(text), "expected the body to contain {text:?}:\n{}", self.excerpt());
807        self
808    }
809
810    /// Asserts the body does not contain `text`.
811    ///
812    /// # Examples
813    ///
814    /// ```
815    /// let response = ocre::testing::Response { status: 200, headers: vec![], body: "<h1>Posts</h1>".into() };
816    /// response.assert_not_contains("Error");
817    /// ```
818    #[track_caller]
819    pub fn assert_not_contains(&self, text: &str) -> &Self {
820        assert!(!self.body.contains(text), "expected the body not to contain {text:?}:\n{}", self.excerpt());
821        self
822    }
823
824    /// Asserts the header `name` has `value`.
825    ///
826    /// # Examples
827    ///
828    /// ```
829    /// let response = ocre::testing::Response { status: 200, headers: vec![("content-type".into(), "application/json".into())], body: String::new() };
830    /// response.assert_header("Content-Type", "application/json");
831    /// ```
832    #[track_caller]
833    pub fn assert_header(&self, name: &str, value: &str) -> &Self {
834        assert!(
835            self.header(name) == Some(value),
836            "expected header {name}: {value}, got {:?}:\n{}",
837            self.header(name),
838            self.excerpt()
839        );
840        self
841    }
842
843    /// Status line and the first 2,000 characters of the body, for failure messages.
844    fn excerpt(&self) -> String {
845        let body: String = self.body.chars().take(2000).collect();
846        format!("HTTP {}\n{body}", self.status)
847    }
848}
849
850/// Rows returned by `query`, run on the test database (Rails' `ActiveRecord::Base.connection.select_all`).
851///
852/// It opens miniflare's SQLite file of the test database in [`TEST_STATE`]
853/// directly (WAL mode: the running server sees the writes at once), in a
854/// few milliseconds, so a check can be polled. Several statements may be
855/// separated by `;`; the rows of the last one are returned. Values are SQL
856/// literals: build them with [`quote`]. When the state holds no single D1
857/// file (several databases), it runs the app's wrangler (`d1 execute DB
858/// --local`) instead, about a second per call.
859///
860/// # Panics
861///
862/// When wrangler fails (the message has its output), e.g. on a SQL error.
863///
864/// # Examples
865///
866/// ```no_run
867/// use ocre::testing::{quote, sql};
868///
869/// let rows = sql(&format!("SELECT id FROM posts WHERE title = {}", quote("Hello")));
870/// assert_eq!(rows.len(), 1);
871/// ```
872pub fn sql(query: &str) -> Vec<Map<String, Value>> {
873    sql_in(&app_root(), &state_dir(), query)
874}
875
876thread_local! {
877    /// The app's directory: `cargo test` runs tests in the package's directory;
878    /// Ocre's own unit tests point it at a scratch app.
879    static APP_ROOT: std::cell::RefCell<PathBuf> = std::cell::RefCell::new(PathBuf::from("."));
880}
881
882fn app_root() -> PathBuf {
883    APP_ROOT.with(|root| root.borrow().clone())
884}
885
886fn state_dir() -> String {
887    std::env::var(TEST_STATE).unwrap_or_else(|_| ".wrangler/test-state".to_owned())
888}
889
890fn sql_in(root: &Path, state: &str, query: &str) -> Vec<Map<String, Value>> {
891    if let Some(file) = d1_file(&root.join(state)) {
892        return sql_direct(&file, query);
893    }
894    sql_wrangler(root, state, query)
895}
896
897/// The one D1 database of the state (miniflare keeps each in
898/// `v3/d1/miniflare-D1DatabaseObject/<id>.sqlite`, next to its `metadata.sqlite`).
899fn d1_file(state: &Path) -> Option<PathBuf> {
900    let dir = state.join("v3/d1/miniflare-D1DatabaseObject");
901    let mut files = std::fs::read_dir(dir).ok()?.filter_map(|entry| {
902        let path = entry.ok()?.path();
903        let sqlite = path.extension().is_some_and(|ext| ext == "sqlite");
904        (sqlite && path.file_stem().is_some_and(|stem| stem != "metadata")).then_some(path)
905    });
906    let file = files.next()?;
907    files.next().is_none().then_some(file)
908}
909
910fn sql_direct(file: &Path, query: &str) -> Vec<Map<String, Value>> {
911    use rusqlite::{Batch, Connection, OpenFlags, types::ValueRef};
912
913    let fail = |err: rusqlite::Error| -> ! { panic!("SQL failed: {query}\n{err}") };
914    let conn = Connection::open_with_flags(file, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX)
915        .unwrap_or_else(|err| fail(err));
916    // The server writes too: wait for its transaction rather than fail.
917    conn.busy_timeout(Duration::from_secs(10)).unwrap_or_else(|err| fail(err));
918    let mut rows = Vec::new();
919    let mut batch = Batch::new(&conn, query);
920    while let Some(mut statement) = batch.next().unwrap_or_else(|err| fail(err)) {
921        let columns: Vec<String> = statement.column_names().into_iter().map(str::to_owned).collect();
922        let mut result = statement.raw_query();
923        rows.clear();
924        while let Some(row) = result.next().unwrap_or_else(|err| fail(err)) {
925            let mut map = Map::new();
926            for (index, column) in columns.iter().enumerate() {
927                let value = match row.get_ref(index).unwrap_or_else(|err| fail(err)) {
928                    ValueRef::Null => Value::Null,
929                    ValueRef::Integer(n) => Value::from(n),
930                    ValueRef::Real(x) => Value::from(x),
931                    ValueRef::Text(text) => Value::from(String::from_utf8_lossy(text).into_owned()),
932                    ValueRef::Blob(bytes) => Value::from(bytes.to_vec()),
933                };
934                map.insert(column.clone(), value);
935            }
936            rows.push(map);
937        }
938    }
939    rows
940}
941
942fn sql_wrangler(root: &Path, state: &str, query: &str) -> Vec<Map<String, Value>> {
943    let output = Command::new(root.join("node_modules/.bin/wrangler"))
944        .args(["d1", "execute", "DB", "--local", "--json", "--command", query])
945        .args(["-c", ".wrangler/ocre-d1.json", "--persist-to", state])
946        .current_dir(root)
947        .output()
948        .unwrap_or_else(|err| panic!("could not run node_modules/.bin/wrangler ({err}). Fix: run `npm install`"));
949    let stdout = String::from_utf8_lossy(&output.stdout);
950    assert!(
951        output.status.success(),
952        "SQL failed: {query}\n{stdout}{}\nFix: run the tests with `ocre test --e2e`, which creates the test database",
953        String::from_utf8_lossy(&output.stderr)
954    );
955    let statements: Vec<Value> =
956        serde_json::from_str(&stdout).unwrap_or_else(|err| panic!("unexpected wrangler output ({err}):\n{stdout}"));
957    let rows = statements.last().and_then(|statement| statement["results"].as_array()).cloned().unwrap_or_default();
958    rows.into_iter().filter_map(|row| if let Value::Object(row) = row { Some(row) } else { None }).collect()
959}
960
961/// `value` as a SQL literal: strings quoted (`'` doubled), numbers as is,
962/// booleans as `1`/`0`, null as `NULL`, arrays and objects as JSON text.
963///
964/// # Examples
965///
966/// ```
967/// use ocre::{serde_json::json, testing::quote};
968///
969/// assert_eq!(quote("it's"), "'it''s'");
970/// assert_eq!(quote(42), "42");
971/// assert_eq!(quote(true), "1");
972/// assert_eq!(quote(json!({"a": 1})), r#"'{"a":1}'"#);
973/// assert_eq!(quote(None::<i64>), "NULL");
974/// ```
975pub fn quote(value: impl Into<Value>) -> String {
976    quote_value(&value.into())
977}
978
979fn quote_value(value: &Value) -> String {
980    match value {
981        Value::Null => "NULL".to_owned(),
982        Value::Bool(true) => "1".to_owned(),
983        Value::Bool(false) => "0".to_owned(),
984        Value::Number(number) => number.to_string(),
985        Value::String(text) => format!("'{}'", text.replace('\'', "''")),
986        other => format!("'{}'", other.to_string().replace('\'', "''")),
987    }
988}
989
990/// Inserts a row into `table` of the test database and returns its `id`:
991/// what generated factories (`tests/factories/`) call. One statement on the test database.
992///
993/// # Panics
994///
995/// Like [`sql`], e.g. on a constraint violation.
996///
997/// # Examples
998///
999/// ```no_run
1000/// use ocre::serde_json::json;
1001///
1002/// let id = ocre::testing::insert("posts", &[("title", json!("Hello")), ("published", json!(true))]);
1003/// assert!(id > 0);
1004/// ```
1005pub fn insert(table: &str, values: &[(&str, Value)]) -> i64 {
1006    sql(&format!("{} RETURNING id", insert_sql(table, values)))
1007        .first()
1008        .and_then(|row| row.get("id"))
1009        .and_then(Value::as_i64)
1010        .expect("INSERT ... RETURNING id returns the id")
1011}
1012
1013/// Inserts a row into `table` of the test database, for tables without an integer `id` (a UUID or composite key).
1014///
1015/// # Panics
1016///
1017/// Like [`sql`], e.g. on a constraint violation.
1018///
1019/// # Examples
1020///
1021/// ```no_run
1022/// use ocre::serde_json::json;
1023///
1024/// ocre::testing::insert_row("videos", &[("id", json!("7f1c…")), ("name", json!("a.mp4"))]);
1025/// ```
1026pub fn insert_row(table: &str, values: &[(&str, Value)]) {
1027    sql(&insert_sql(table, values));
1028}
1029
1030fn insert_sql(table: &str, values: &[(&str, Value)]) -> String {
1031    let columns: Vec<&str> = values.iter().map(|(column, _)| *column).collect();
1032    let literals: Vec<String> = values.iter().map(|(_, value)| quote_value(value)).collect();
1033    format!("INSERT INTO {table} ({}) VALUES ({})", columns.join(", "), literals.join(", "))
1034}
1035
1036/// Number of rows of `table` in the test database, for [`assert_difference`].
1037///
1038/// # Examples
1039///
1040/// ```no_run
1041/// let posts = ocre::testing::count("posts");
1042/// ```
1043pub fn count(table: &str) -> i64 {
1044    sql(&format!("SELECT COUNT(*) AS count FROM {table}"))[0]["count"].as_i64().expect("COUNT(*) is an integer")
1045}
1046
1047/// The `id` of the fixture labelled `label` (Rails' `users(:david).id`):
1048/// the loader of `tests/fixtures/*.yml` gives a record without an explicit
1049/// `id` the CRC-32 of its label modulo 2^30 - 1, like Rails.
1050///
1051/// # Examples
1052///
1053/// ```
1054/// assert_eq!(ocre::testing::fixture_id("david"), 127326141);
1055/// ```
1056pub fn fixture_id(label: &str) -> i64 {
1057    i64::from(crc32(label.as_bytes()) % ((1 << 30) - 1))
1058}
1059
1060/// The row of `table` loaded from the fixture `label` (Rails' `posts(:first)`).
1061///
1062/// # Panics
1063///
1064/// When there is no such row.
1065///
1066/// # Examples
1067///
1068/// ```no_run
1069/// let post = ocre::testing::fixture("posts", "first");
1070/// assert_eq!(post["title"], "Hello");
1071/// ```
1072pub fn fixture(table: &str, label: &str) -> Map<String, Value> {
1073    let rows = sql(&format!("SELECT * FROM {table} WHERE id = {}", fixture_id(label)));
1074    rows.into_iter().next().unwrap_or_else(|| panic!("no fixture {label} in {table} (tests/fixtures/{table}.yml)"))
1075}
1076
1077/// CRC-32 (IEEE, as zlib), bit by bit: fixture labels are short.
1078fn crc32(bytes: &[u8]) -> u32 {
1079    let mut crc = !0u32;
1080    for byte in bytes {
1081        crc ^= u32::from(*byte);
1082        for _ in 0..8 {
1083            crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
1084        }
1085    }
1086    !crc
1087}
1088
1089/// A unique number per call in the test process, for unique test data
1090/// (FactoryBot's `sequence`): 1, 2, 3...
1091///
1092/// # Examples
1093///
1094/// ```
1095/// let (a, b) = (ocre::testing::sequence(), ocre::testing::sequence());
1096/// assert!(b > a);
1097/// ```
1098pub fn sequence() -> u64 {
1099    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1100    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1101}
1102
1103/// The test server's log (`cf dev` output: `console.log`, job and cron
1104/// lines, errors), read from the position of [`Log::mark`] on.
1105///
1106/// Jobs and crons log `[ocre jobs] <name> done` and failures; errors
1107/// answered 500 log `[ocre] ...`. Waiting for those lines replaces Rails'
1108/// `assert_performed_jobs` and `assert_error_reported`: queues deliver
1109/// asynchronously, as in production.
1110///
1111/// # Examples
1112///
1113/// ```no_run
1114/// use ocre::testing::{Client, Log};
1115///
1116/// let log = Log::mark();
1117/// Client::new().post("/signups", &[("email", "ada@example.com")]);
1118/// log.wait_for("[ocre jobs] send_welcome done");
1119/// ```
1120#[derive(Debug, Clone)]
1121pub struct Log {
1122    path: PathBuf,
1123    start: usize,
1124}
1125
1126impl Log {
1127    /// The log from now on ([`TEST_LOG`], else `.wrangler/test-state/dev.log`).
1128    ///
1129    /// # Examples
1130    ///
1131    /// ```no_run
1132    /// let log = ocre::testing::Log::mark();
1133    /// assert!(log.text().is_empty());
1134    /// ```
1135    pub fn mark() -> Self {
1136        let path =
1137            std::env::var(TEST_LOG).map_or_else(|_| PathBuf::from(".wrangler/test-state/dev.log"), PathBuf::from);
1138        Self::mark_at(path)
1139    }
1140
1141    fn mark_at(path: PathBuf) -> Self {
1142        let start = std::fs::metadata(&path).map_or(0, |meta| usize::try_from(meta.len()).unwrap_or(usize::MAX));
1143        Self { path, start }
1144    }
1145
1146    /// What was logged since the mark.
1147    ///
1148    /// # Examples
1149    ///
1150    /// ```no_run
1151    /// let log = ocre::testing::Log::mark();
1152    /// ocre::testing::Client::new().get("/boom");
1153    /// assert!(log.text().contains("[ocre]"));
1154    /// ```
1155    pub fn text(&self) -> String {
1156        let bytes = std::fs::read(&self.path).unwrap_or_default();
1157        String::from_utf8_lossy(bytes.get(self.start..).unwrap_or_default()).into_owned()
1158    }
1159
1160    /// Waits up to 30 seconds for a line containing `needle` and returns it.
1161    ///
1162    /// # Panics
1163    ///
1164    /// When no such line arrives in time; the message has the log since the mark.
1165    ///
1166    /// # Examples
1167    ///
1168    /// ```no_run
1169    /// let log = ocre::testing::Log::mark();
1170    /// log.wait_for("[ocre jobs] send_welcome done");
1171    /// ```
1172    #[track_caller]
1173    pub fn wait_for(&self, needle: &str) -> String {
1174        self.wait_for_within(needle, WAIT)
1175    }
1176
1177    #[track_caller]
1178    fn wait_for_within(&self, needle: &str, timeout: Duration) -> String {
1179        let found = poll(timeout, || self.text().lines().find(|line| line.contains(needle)).map(str::to_owned));
1180        found.unwrap_or_else(|| panic!("no log line containing {needle:?} within {timeout:?}; log:\n{}", self.text()))
1181    }
1182}
1183
1184/// Retries `check` every 100 ms for up to 30 seconds until it returns
1185/// `Some`, for effects that happen later: a queued job, a cron, a
1186/// broadcast.
1187///
1188/// # Panics
1189///
1190/// When `check` still returns `None` after 30 seconds.
1191///
1192/// # Examples
1193///
1194/// ```
1195/// let mut tries = 0;
1196/// let value = ocre::testing::eventually(|| {
1197///     tries += 1;
1198///     (tries == 3).then_some("done")
1199/// });
1200/// assert_eq!(value, "done");
1201/// ```
1202#[track_caller]
1203pub fn eventually<T>(check: impl FnMut() -> Option<T>) -> T {
1204    eventually_within(WAIT, check)
1205}
1206
1207/// [`eventually`] with another deadline: retries `check` every 100 ms for up to `timeout`.
1208///
1209/// For effects slower than 30 seconds (a pipeline of several jobs), or to
1210/// fail fast on a quick one.
1211///
1212/// # Panics
1213///
1214/// When `check` still returns `None` after `timeout`.
1215///
1216/// # Examples
1217///
1218/// ```
1219/// use std::time::Duration;
1220///
1221/// let value = ocre::testing::eventually_within(Duration::from_secs(120), || Some(42));
1222/// assert_eq!(value, 42);
1223/// ```
1224#[track_caller]
1225pub fn eventually_within<T>(timeout: Duration, check: impl FnMut() -> Option<T>) -> T {
1226    poll(timeout, check).unwrap_or_else(|| panic!("the condition did not hold within {timeout:?}"))
1227}
1228
1229/// The body of a response, or a panic naming the request.
1230fn body_bytes(bytes: Result<Vec<u8>, ureq::Error>, method: &str, url: &str) -> Vec<u8> {
1231    bytes.unwrap_or_else(|err| panic!("{method} {url}: body: {err}"))
1232}
1233
1234fn poll<T>(timeout: Duration, mut check: impl FnMut() -> Option<T>) -> Option<T> {
1235    let deadline = Instant::now() + timeout;
1236    loop {
1237        if let Some(value) = check() {
1238            return Some(value);
1239        }
1240        if Instant::now() >= deadline {
1241            return None;
1242        }
1243        std::thread::sleep(Duration::from_millis(100));
1244    }
1245}
1246
1247/// Asserts that `block` changes the number `expression` returns by
1248/// `difference` (Rails' `assert_difference`), and returns the block's value.
1249///
1250/// # Examples
1251///
1252/// ```
1253/// let count = std::cell::Cell::new(1);
1254/// ocre::testing::assert_difference(|| count.get(), 1, || count.set(2));
1255/// ```
1256#[track_caller]
1257pub fn assert_difference<R>(mut expression: impl FnMut() -> i64, difference: i64, block: impl FnOnce() -> R) -> R {
1258    let before = expression();
1259    let result = block();
1260    let after = expression();
1261    assert!(
1262        after - before == difference,
1263        "expected a difference of {difference}, got {} ({before} -> {after})",
1264        after - before
1265    );
1266    result
1267}
1268
1269/// Asserts that `block` leaves the number `expression` returns unchanged (Rails' `assert_no_difference`).
1270///
1271/// # Examples
1272///
1273/// ```
1274/// ocre::testing::assert_no_difference(|| 3, || ());
1275/// ```
1276#[track_caller]
1277pub fn assert_no_difference<R>(expression: impl FnMut() -> i64, block: impl FnOnce() -> R) -> R {
1278    assert_difference(expression, 0, block)
1279}
1280
1281/// Asserts that `block` changes what `expression` returns (Rails'
1282/// `assert_changes`), and returns `(before, after)`.
1283///
1284/// # Examples
1285///
1286/// ```
1287/// let title = std::cell::RefCell::new("Draft".to_owned());
1288/// let (before, after) = ocre::testing::assert_changes(|| title.borrow().clone(), || *title.borrow_mut() = "Final".into());
1289/// assert_eq!((before.as_str(), after.as_str()), ("Draft", "Final"));
1290/// ```
1291#[track_caller]
1292pub fn assert_changes<T: PartialEq + Debug>(mut expression: impl FnMut() -> T, block: impl FnOnce()) -> (T, T) {
1293    let before = expression();
1294    block();
1295    let after = expression();
1296    assert!(before != after, "expected a change, still {after:?}");
1297    (before, after)
1298}
1299
1300/// Asserts that `block` leaves what `expression` returns unchanged (Rails' `assert_no_changes`).
1301///
1302/// # Examples
1303///
1304/// ```
1305/// ocre::testing::assert_no_changes(|| "same", || ());
1306/// ```
1307#[track_caller]
1308pub fn assert_no_changes<T: PartialEq + Debug>(mut expression: impl FnMut() -> T, block: impl FnOnce()) {
1309    let before = expression();
1310    block();
1311    let after = expression();
1312    assert!(before == after, "expected no change, {before:?} became {after:?}");
1313}
1314
1315/// Makes [`crate::now`] return `unix` on this thread until [`travel_back`]
1316/// (Rails' `travel_to`, frozen). Each Rust test runs on its own thread, so
1317/// other tests keep the real clock. Affects code running in the test
1318/// process (models, helpers, JWT), not the `cf dev` server.
1319///
1320/// # Examples
1321///
1322/// ```
1323/// ocre::testing::travel_to(1_767_225_600); // 2026-01-01T00:00:00Z
1324/// assert_eq!(ocre::now(), 1_767_225_600);
1325/// ocre::testing::travel_back();
1326/// ```
1327pub fn travel_to(unix: i64) {
1328    crate::clock::set_frozen(Some(unix));
1329}
1330
1331/// Moves [`crate::now`] by `seconds` from its current value and freezes it there (Rails' `travel 1.day`).
1332///
1333/// # Examples
1334///
1335/// ```
1336/// ocre::testing::travel_to(1_000);
1337/// ocre::testing::travel(3_600);
1338/// assert_eq!(ocre::now(), 4_600);
1339/// ocre::testing::travel_back();
1340/// ```
1341pub fn travel(seconds: i64) {
1342    travel_to(crate::now() + seconds);
1343}
1344
1345/// Stops [`crate::now`] at the current second (Rails' `freeze_time`); returns it.
1346///
1347/// # Examples
1348///
1349/// ```
1350/// let frozen = ocre::testing::freeze_time();
1351/// assert_eq!(ocre::now(), frozen);
1352/// ocre::testing::travel_back();
1353/// ```
1354pub fn freeze_time() -> i64 {
1355    let now = crate::now();
1356    travel_to(now);
1357    now
1358}
1359
1360/// Returns [`crate::now`] to the real clock (Rails' `travel_back`).
1361///
1362/// # Examples
1363///
1364/// ```
1365/// ocre::testing::travel_to(0);
1366/// ocre::testing::travel_back();
1367/// assert!(ocre::now() > 0);
1368/// ```
1369pub fn travel_back() {
1370    crate::clock::set_frozen(None);
1371}
1372
1373/// Replaces values that change on every run by placeholders, so a snapshot
1374/// or an `assert_eq!` on a whole page or JSON body is stable (Loco's
1375/// `cleanup_*` filters): UUIDs become `<UUID>`, ISO 8601 dates and times
1376/// (`2026-01-01`, `2026-01-01T12:00:00Z`, `2026-01-01 12:00:00`) become
1377/// `<DATE>`, and runs of 32 or more hexadecimal or base64url characters
1378/// (tokens, digests) become `<TOKEN>`.
1379///
1380/// # Examples
1381///
1382/// ```
1383/// let body = r#"{"id":"123e4567-e89b-42d3-a456-426614174000","at":"2026-09-29T10:00:00Z"}"#;
1384/// assert_eq!(ocre::testing::redact(body), r#"{"id":"<UUID>","at":"<DATE>"}"#);
1385/// ```
1386pub fn redact(text: &str) -> String {
1387    let bytes = text.as_bytes();
1388    let mut out = String::with_capacity(text.len());
1389    let mut i = 0;
1390    while i < bytes.len() {
1391        let boundary = i == 0 || !is_token_byte(bytes[i - 1]);
1392        if boundary && let Some((len, placeholder)) = sensitive_at(&bytes[i..]) {
1393            out.push_str(placeholder);
1394            i += len;
1395            continue;
1396        }
1397        let ch = text[i..].chars().next().expect("i is on a char boundary");
1398        out.push(ch);
1399        i += ch.len_utf8();
1400    }
1401    out
1402}
1403
1404fn is_token_byte(byte: u8) -> bool {
1405    byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_'
1406}
1407
1408/// Length and placeholder of the value starting `bytes`, if it is one to redact.
1409fn sensitive_at(bytes: &[u8]) -> Option<(usize, &'static str)> {
1410    if let Some(len) = uuid_len(bytes) {
1411        return Some((len, "<UUID>"));
1412    }
1413    if let Some(len) = date_len(bytes) {
1414        return Some((len, "<DATE>"));
1415    }
1416    let token = bytes.iter().take_while(|byte| is_token_byte(**byte)).count();
1417    let digits_or_letters =
1418        bytes[..token].iter().any(u8::is_ascii_digit) && bytes[..token].iter().any(u8::is_ascii_alphabetic);
1419    (token >= 32 && digits_or_letters).then_some((token, "<TOKEN>"))
1420}
1421
1422/// Matches `pattern` (`9` a digit, `x` a hex digit, others literal) at the start of `bytes`.
1423fn matches(bytes: &[u8], pattern: &[u8]) -> bool {
1424    bytes.len() >= pattern.len()
1425        && pattern.iter().zip(bytes).all(|(want, got)| match want {
1426            b'9' => got.is_ascii_digit(),
1427            b'x' => got.is_ascii_hexdigit(),
1428            literal => literal == got,
1429        })
1430}
1431
1432fn uuid_len(bytes: &[u8]) -> Option<usize> {
1433    const UUID: &[u8] = b"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
1434    (matches(bytes, UUID) && bytes.get(UUID.len()).is_none_or(|byte| !is_token_byte(*byte))).then_some(UUID.len())
1435}
1436
1437fn date_len(bytes: &[u8]) -> Option<usize> {
1438    if !matches(bytes, b"9999-99-99") {
1439        return None;
1440    }
1441    let mut len = 10;
1442    if matches(&bytes[len..], b"T99:99") || matches(&bytes[len..], b" 99:99") {
1443        len += 6;
1444        if matches(&bytes[len..], b":99") {
1445            len += 3;
1446        }
1447        if bytes.get(len) == Some(&b'.') {
1448            len += 1 + bytes[len + 1..].iter().take_while(|byte| byte.is_ascii_digit()).count();
1449        }
1450        if bytes.get(len) == Some(&b'Z') {
1451            len += 1;
1452        } else if matches(&bytes[len..], b"+99:99") || matches(&bytes[len..], b"-99:99") {
1453            len += 6;
1454        }
1455    }
1456    Some(len)
1457}
1458
1459#[cfg(test)]
1460#[path = "../tests/testing.rs"]
1461mod tests;