1use std::fmt;
23use std::future::Future;
24use std::sync::Arc;
25
26use http::{HeaderMap, Method, StatusCode};
27use serde::Serialize;
28
29use super::{TestClient, setup};
30use crate::app::App;
31use crate::config::Config;
32use crate::context::Params;
33use crate::db::migration::Migration;
34use crate::db::{Changeset, Repo, Save};
35use crate::model::Model;
36use crate::response::Response;
37use crate::router::ToPath;
38
39#[derive(Clone, Copy)]
41pub struct Harness {
42 app: fn(Config, Repo) -> crate::Result<App>,
43 migrations: fn() -> Vec<Migration>,
44}
45
46impl Harness {
47 pub fn new(
48 app: fn(Config, Repo) -> crate::Result<App>,
49 migrations: fn() -> Vec<Migration>,
50 ) -> Self {
51 Self { app, migrations }
52 }
53}
54
55tokio::task_local! {
56 static CLIENT: Arc<TestClient>;
57}
58
59pub async fn run<F: Future<Output = ()>>(harness: Harness, test: F) {
71 let (config, repo) = setup((harness.migrations)()).await;
72 let url: String = config.get("database.url").unwrap_or_default();
73 let fresh = url.starts_with("sqlite:") && url.contains(":memory:");
74 let app = (harness.app)(config, repo.clone()).expect("building the app under test");
75 let client = Arc::new(TestClient::new(app));
76 let service = client.service();
77 service
78 .migrate_named()
79 .await
80 .expect("migrating the named test databases");
81 let databases = service
82 .named_databases()
83 .await
84 .expect("connecting to the named test databases");
85 if fresh {
86 let named = databases
87 .iter()
88 .map(|(name, repo)| (name.clone(), crate::db::Connection::from(repo)))
89 .collect();
90 let test = crate::db::scope_named(named, test);
91 CLIENT.scope(client, crate::db::with(&repo, test)).await;
92 } else {
93 let mut transactions = Vec::new();
96 for (name, repo) in &databases {
97 let tx = repo
98 .begin()
99 .await
100 .expect("starting a named test transaction");
101 transactions.push((name.clone(), tx));
102 }
103 let named = transactions
104 .iter()
105 .map(|(name, tx)| (name.clone(), crate::db::Connection::from(tx)))
106 .collect();
107 let test = crate::db::scope_named(named, test);
108 CLIENT
109 .scope(client, crate::db::sandbox(&repo, test))
110 .await
111 .expect("rolling back the test's transaction");
112 for (_, tx) in transactions {
113 tx.rollback()
114 .await
115 .expect("rolling back a named test transaction");
116 }
117 }
118}
119
120pub fn bearer(token: impl AsRef<str>) {
123 client().bearer(token);
124}
125
126pub fn path_prefix(prefix: impl Into<String>) {
130 client().path_prefix(prefix);
131}
132
133pub fn header(name: &str, value: impl AsRef<str>) {
136 client().header(name, value);
137}
138
139pub fn set_cookie(name: &str, value: impl Into<String>) {
142 client().set_cookie(name, value);
143}
144
145pub fn basic_auth(name: &str, password: &str) {
148 use base64::Engine;
149 let encoded = base64::engine::general_purpose::STANDARD.encode(format!("{name}:{password}"));
150 client().header("authorization", format!("Basic {encoded}"));
151}
152
153fn client() -> Arc<TestClient> {
154 CLIENT.try_with(Arc::clone).expect(
155 "get/post/patch/put/delete need a test client: use them in a .glacier test \
156 or a #[glacier::test(app)] function",
157 )
158}
159
160pub fn test_config() -> crate::Config {
163 client().config()
164}
165
166pub fn sequence() -> u64 {
170 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
171 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
172}
173
174#[track_caller]
183pub fn cycle<T: Clone, const N: usize>(values: [T; N]) -> T {
184 assert!(N > 0, "cycle needs at least one value");
185 let at = std::panic::Location::caller();
186 let site = (at.file(), at.line(), at.column());
187 let turn = match CLIENT.try_with(Arc::clone) {
188 Ok(client) => {
189 let mut cycles = client.cycles.lock().unwrap_or_else(|e| e.into_inner());
190 let turn = cycles.entry(site).or_insert(0);
191 *turn += 1;
192 *turn - 1
193 }
194 Err(_) => usize::try_from(sequence()).unwrap_or(0),
195 };
196 values[turn % N].clone()
197}
198
199pub fn recycle<M: Clone + Send + 'static>(record: &M) {
204 let client = client();
205 client
206 .recycled
207 .lock()
208 .unwrap_or_else(|e| e.into_inner())
209 .insert(std::any::TypeId::of::<M>(), Box::new(record.clone()));
210}
211
212#[doc(hidden)]
215pub async fn recycled_or<M: Clone + Send + 'static>(insert: impl Future<Output = M>) -> M {
216 let recycled = CLIENT.try_with(|client| {
217 client
218 .recycled
219 .lock()
220 .unwrap_or_else(|e| e.into_inner())
221 .get(&std::any::TypeId::of::<M>())
222 .and_then(|record| record.downcast_ref::<M>().cloned())
223 });
224 match recycled {
225 Ok(Some(record)) => record,
226 _ => insert.await,
227 }
228}
229
230pub async fn perform_jobs() -> crate::Result<usize> {
233 client().perform_jobs().await
234}
235
236pub async fn run_task<T: std::fmt::Display>(
239 name: &str,
240 args: impl IntoIterator<Item = T>,
241) -> crate::Result<()> {
242 let args = args.into_iter().map(|a| a.to_string()).collect();
243 client().run_task(name, args).await
244}
245
246pub async fn get(path: impl ToPath) -> TestResponse {
248 client().get(&path.to_path()).await.into()
249}
250
251pub async fn post(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
253 send(Method::POST, path, form.into()).await
254}
255
256pub async fn patch(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
258 send(Method::PATCH, path, form.into()).await
259}
260
261pub async fn put(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
263 send(Method::PUT, path, form.into()).await
264}
265
266pub async fn post_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
270 send_json(Method::POST, path, json.json_body()).await
271}
272
273pub async fn patch_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
275 send_json(Method::PATCH, path, json.json_body()).await
276}
277
278pub async fn put_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
280 send_json(Method::PUT, path, json.json_body()).await
281}
282
283pub async fn delete_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
285 send_json(Method::DELETE, path, json.json_body()).await
286}
287
288async fn send_json(method: Method, path: impl ToPath, json: String) -> TestResponse {
289 let req = http::Request::builder()
290 .method(method)
291 .uri(path.to_path())
292 .header(http::header::CONTENT_TYPE, "application/json")
293 .body(bytes::Bytes::from(json))
294 .expect("invalid test request");
295 client().request(req).await.into()
296}
297
298pub trait JsonBody {
301 fn json_body(&self) -> String;
302}
303
304impl JsonBody for str {
305 fn json_body(&self) -> String {
306 self.to_owned()
307 }
308}
309
310impl JsonBody for String {
311 fn json_body(&self) -> String {
312 self.clone()
313 }
314}
315
316impl JsonBody for Form {
317 fn json_body(&self) -> String {
320 let mut root = serde_json::Map::new();
321 for (name, value) in &self.0 {
322 let mut keys: Vec<&str> = Vec::new();
323 let (first, mut rest) = name
324 .split_once('[')
325 .map_or((name.as_str(), ""), |(a, b)| (a, b));
326 keys.push(first);
327 while let Some((key, after)) = rest.split_once(']') {
328 keys.push(key);
329 rest = after.strip_prefix('[').unwrap_or(after);
330 }
331 insert_json(&mut root, &keys, value);
332 }
333 serde_json::Value::Object(root).to_string()
334 }
335}
336
337fn insert_json(
338 object: &mut serde_json::Map<String, serde_json::Value>,
339 keys: &[&str],
340 value: &str,
341) {
342 use serde_json::Value;
343 let (key, rest) = (keys[0].to_owned(), &keys[1..]);
344 match rest {
345 [] => {
346 object.insert(key, Value::String(value.to_owned()));
347 }
348 [""] => {
349 let entry = object
350 .entry(key)
351 .or_insert_with(|| Value::Array(Vec::new()));
352 if let Value::Array(items) = entry {
353 items.push(Value::String(value.to_owned()));
354 }
355 }
356 _ => {
357 let entry = object
358 .entry(key)
359 .or_insert_with(|| Value::Object(serde_json::Map::new()));
360 if !entry.is_object() {
361 *entry = Value::Object(serde_json::Map::new());
362 }
363 if let Value::Object(inner) = entry {
364 insert_json(inner, rest, value);
365 }
366 }
367 }
368}
369
370impl<T: JsonBody + ?Sized> JsonBody for &T {
371 fn json_body(&self) -> String {
372 (**self).json_body()
373 }
374}
375
376pub async fn delete(path: impl ToPath) -> TestResponse {
378 client().delete(&path.to_path()).await.into()
379}
380
381async fn send(method: Method, path: impl ToPath, form: Form) -> TestResponse {
382 if form.1.is_empty() {
383 return client()
384 .send_form(method, &path.to_path(), &form.0)
385 .await
386 .into();
387 }
388 let boundary = format!("----glacier{:016x}", rand_boundary());
390 let mut body = Vec::new();
391 for (name, value) in &form.0 {
392 body.extend_from_slice(
393 format!(
394 "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
395 )
396 .as_bytes(),
397 );
398 }
399 for (name, upload) in &form.1 {
400 body.extend_from_slice(
401 format!(
402 "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
403 upload.filename, upload.content_type
404 )
405 .as_bytes(),
406 );
407 body.extend_from_slice(&upload.bytes);
408 body.extend_from_slice(b"\r\n");
409 }
410 body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
411 let req = http::Request::builder()
412 .method(method)
413 .uri(path.to_path())
414 .header(
415 http::header::CONTENT_TYPE,
416 format!("multipart/form-data; boundary={boundary}"),
417 )
418 .body(bytes::Bytes::from(body))
419 .expect("invalid test request");
420 client().request(req).await.into()
421}
422
423fn rand_boundary() -> u64 {
424 use std::hash::{BuildHasher, Hasher};
425 let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
426 hasher.write_u128(
427 std::time::SystemTime::now()
428 .duration_since(std::time::UNIX_EPOCH)
429 .unwrap_or_default()
430 .as_nanos(),
431 );
432 hasher.finish()
433}
434
435pub fn file(
438 filename: &str,
439 content_type: &str,
440 bytes: impl Into<bytes::Bytes>,
441) -> crate::upload::Upload {
442 crate::upload::Upload {
443 filename: filename.to_owned(),
444 content_type: content_type.to_owned(),
445 bytes: bytes.into(),
446 }
447}
448
449#[derive(Debug)]
452pub struct TestResponse {
453 pub status: Status,
454 pub body: String,
455 pub location: String,
457 pub headers: HeaderMap,
458}
459
460impl TestResponse {
461 pub fn header(&self, name: &str) -> Option<&str> {
464 self.headers.get(name).and_then(|value| value.to_str().ok())
465 }
466
467 #[track_caller]
473 pub fn json(&self) -> serde_json::Value {
474 serde_json::from_str(&self.body)
475 .unwrap_or_else(|e| panic!("the response isn't JSON ({e}):\n{}", self.body))
476 }
477}
478
479impl From<Response> for TestResponse {
480 fn from(res: Response) -> Self {
481 Self {
482 status: Status(res.status()),
483 body: res.body_text(),
484 location: res.header("location").unwrap_or_default().to_owned(),
485 headers: res.headers().clone(),
486 }
487 }
488}
489
490#[derive(Clone, Copy, PartialEq, Eq)]
493pub struct Status(pub StatusCode);
494
495impl Status {
496 pub fn name(&self) -> String {
498 crate::response::status_name(self.0)
499 }
500
501 #[track_caller]
508 pub fn named(name: &str) -> Self {
509 crate::response::status_named(name)
510 .map(Status)
511 .unwrap_or_else(|| panic!("no HTTP status is called `:{name}`"))
512 }
513}
514
515impl fmt::Debug for Status {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 write!(f, ":{} ({})", self.name(), self.0.as_u16())
518 }
519}
520
521impl PartialEq<&str> for Status {
522 #[track_caller]
523 fn eq(&self, name: &&str) -> bool {
524 *self == Status::named(name)
525 }
526}
527
528impl PartialEq<u16> for Status {
529 fn eq(&self, code: &u16) -> bool {
530 self.0.as_u16() == *code
531 }
532}
533
534impl PartialEq<i32> for Status {
535 fn eq(&self, code: &i32) -> bool {
536 i32::from(self.0.as_u16()) == *code
537 }
538}
539
540impl PartialEq<StatusCode> for Status {
541 fn eq(&self, code: &StatusCode) -> bool {
542 self.0 == *code
543 }
544}
545
546#[derive(Debug, Clone, Default, PartialEq, Serialize)]
549pub struct Form(
550 Vec<(String, String)>,
551 #[serde(skip)]
553 Vec<(String, crate::upload::Upload)>,
554);
555
556impl Form {
557 pub fn new() -> Self {
558 Self::default()
559 }
560
561 #[must_use]
565 pub fn with(self, name: &str, value: impl FormValue) -> Self {
566 value.add_to(self, name)
567 }
568
569 #[must_use]
572 pub fn with_all<T: fmt::Display>(
573 mut self,
574 name: &str,
575 values: impl IntoIterator<Item = T>,
576 ) -> Self {
577 let field = format!("{name}[]");
578 self.0.retain(|(k, _)| *k != field);
579 self.0.extend(
580 values
581 .into_iter()
582 .map(|value| (field.clone(), value.to_string())),
583 );
584 self
585 }
586
587 fn set(mut self, name: &str, value: String) -> Self {
588 match self.0.iter_mut().find(|(k, _)| k == name) {
589 Some(field) => field.1 = value,
590 None => self.0.push((name.to_owned(), value)),
591 }
592 self
593 }
594
595 #[must_use]
597 pub fn without(mut self, name: &str) -> Self {
598 self.0.retain(|(k, _)| k != name);
599 self
600 }
601
602 pub fn get(&self, name: &str) -> Option<&str> {
603 self.0
604 .iter()
605 .find(|(k, _)| k == name)
606 .map(|(_, v)| v.as_str())
607 }
608}
609
610pub trait FormValue {
612 fn add_to(self, form: Form, name: &str) -> Form;
613}
614
615impl<T: fmt::Display> FormValue for T {
616 fn add_to(self, form: Form, name: &str) -> Form {
617 form.set(name, self.to_string())
618 }
619}
620
621impl FormValue for Form {
622 fn add_to(self, form: Form, name: &str) -> Form {
623 let nest = |field: &str| {
625 let (head, rest) = field.split_at(field.find('[').unwrap_or(field.len()));
626 format!("{name}[{head}]{rest}")
627 };
628 let mut form = self
629 .0
630 .into_iter()
631 .fold(form, |form, (field, value)| form.set(&nest(&field), value));
632 for (field, upload) in self.1 {
633 let field = nest(&field);
634 form.1.retain(|(name, _)| *name != field);
635 form.1.push((field, upload));
636 }
637 form
638 }
639}
640
641impl FormValue for crate::upload::Upload {
643 fn add_to(self, mut form: Form, name: &str) -> Form {
644 form.1.retain(|(field, _)| field != name);
645 form.1.push((name.to_owned(), self));
646 form
647 }
648}
649
650impl From<&Form> for Form {
651 fn from(form: &Form) -> Self {
652 form.clone()
653 }
654}
655
656impl From<()> for Form {
657 fn from((): ()) -> Self {
658 Form::new()
659 }
660}
661
662impl From<Form> for Params {
663 fn from(form: Form) -> Self {
664 form.0.into_iter().collect()
665 }
666}
667
668impl<K: AsRef<str>, V: fmt::Display> FromIterator<(K, V)> for Form {
669 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
670 iter.into_iter()
671 .fold(Form::new(), |form, (k, v)| form.with(k.as_ref(), v))
672 }
673}
674
675impl<M: Model> From<Form> for Changeset<M> {
677 fn from(form: Form) -> Self {
678 Params::from(form).into()
679 }
680}
681
682#[track_caller]
689pub fn errors_on<M: Model>(save: Save<M>) -> String {
690 save.unwrap_invalid().messages().join("; ")
691}
692
693pub async fn insert<M: Model + Default + Clone>(form: Form) -> Save<M> {
700 let params = Params::from(form);
704 let mut record = M::build(params.clone());
705 record.assign_protected(¶ms);
706 save_inserted(record).await
707}
708
709pub async fn insert_for<M, A>(access: &A, form: Form) -> Save<M>
719where
720 M: Model + Default + Clone,
721 A: crate::access::Access + Clone,
722{
723 let params = Params::from(form);
724 let mut built = M::build(params.clone());
725 built.assign_protected(¶ms);
726 let record = M::r#for(access).build_with(|record| *record = built);
727 crate::access::with_access(access.clone(), save_inserted(record)).await
728}
729
730async fn save_inserted<M: Model + Clone>(mut record: M) -> Save<M> {
731 let saved = record
732 .save()
733 .await
734 .unwrap_or_else(|e| panic!("inserting a {}: {e}", std::any::type_name::<M>()));
735 if saved {
736 return Save::Saved(record);
737 }
738 let mut changeset = Changeset::<M>::new();
739 for (column, message) in record.errors() {
740 changeset = changeset.push_error(column, message.clone());
741 }
742 Save::Invalid(changeset)
743}
744
745#[track_caller]
747pub fn assert_equal<L, R>(left: &L, right: &R, source: &str)
748where
749 L: PartialEq<R> + fmt::Debug + ?Sized,
750 R: fmt::Debug + ?Sized,
751{
752 if left != right {
753 panic!("assertion failed: {source}\n left: {left:?}\n right: {right:?}");
754 }
755}
756
757#[track_caller]
759pub fn assert_not_equal<L, R>(left: &L, right: &R, source: &str)
760where
761 L: PartialEq<R> + fmt::Debug + ?Sized,
762 R: fmt::Debug + ?Sized,
763{
764 if left == right {
765 panic!("assertion failed: {source}\n both sides: {left:?}");
766 }
767}
768
769#[track_caller]
771pub fn assert_contains(
772 text: &(impl AsRef<str> + ?Sized),
773 part: &(impl AsRef<str> + ?Sized),
774 source: &str,
775) {
776 let (text, part) = (text.as_ref(), part.as_ref());
777 if !text.contains(part) {
778 panic!(
779 "assertion failed: {source}\n expected to contain: {part:?}\n but was: {}",
780 excerpt(text)
781 );
782 }
783}
784
785#[track_caller]
787pub fn refute_contains(
788 text: &(impl AsRef<str> + ?Sized),
789 part: &(impl AsRef<str> + ?Sized),
790 source: &str,
791) {
792 let (text, part) = (text.as_ref(), part.as_ref());
793 if text.contains(part) {
794 panic!(
795 "refute failed: {source}\n expected not to contain: {part:?}\n but was: {}",
796 excerpt(text)
797 );
798 }
799}
800
801#[track_caller]
803pub fn assert_true(condition: bool, source: &str) {
804 if !condition {
805 panic!("assertion failed: {source}");
806 }
807}
808
809#[track_caller]
811pub fn refute_true(condition: bool, source: &str) {
812 if condition {
813 panic!("refute failed: {source}");
814 }
815}
816
817fn excerpt(text: &str) -> String {
819 const MAX: usize = 600;
820 match text.char_indices().nth(MAX) {
821 Some((cut, _)) => format!("{:?}… ({} more bytes)", &text[..cut], text.len() - cut),
822 None => format!("{text:?}"),
823 }
824}
825
826#[cfg(test)]
827mod tests {
828 use super::*;
829
830 #[test]
831 fn statuses_compare_by_name_and_number() {
832 let s = Status(StatusCode::SEE_OTHER);
833 assert_eq!(s.name(), "see_other");
834 assert!(s == "see_other");
835 assert!(s == 303);
836 assert!(Status(StatusCode::UNPROCESSABLE_ENTITY) == "unprocessable_entity");
837 assert!(Status(StatusCode::OK) == "ok");
838 assert_eq!(format!("{s:?}"), ":see_other (303)");
839 }
840
841 #[test]
842 #[should_panic(expected = "no HTTP status is called `:se_other`")]
843 fn unknown_status_names_fail() {
844 let _ = Status(StatusCode::OK) == "se_other";
845 }
846
847 #[test]
848 fn forms_replace_fields() {
849 let form = Form::new()
850 .with("title", "a")
851 .with("n", 1)
852 .with("title", "b");
853 assert_eq!(form.get("title"), Some("b"));
854 assert_eq!(form.without("n"), Form::new().with("title", "b"));
855 }
856
857 #[test]
858 fn nested_forms_send_rails_style_keys() {
859 let tags = Form::new().with("0", "a");
860 let form = Form::new().with("post", Form::new().with("title", "Hi").with("tags", tags));
861 assert_eq!(form.get("post[title]"), Some("Hi"));
862 assert_eq!(form.get("post[tags][0]"), Some("a"));
863 }
864
865 #[test]
866 #[should_panic(expected = "assertion failed: res.body =~ \"x\"")]
867 fn contains_explains_itself() {
868 assert_contains("hello", "x", "res.body =~ \"x\"");
869 }
870
871 #[test]
872 fn forms_become_json_objects() {
873 let form = Form::new()
874 .with("post", Form::new().with("title", "Hi").with("n", 3))
875 .with("ids[]", 1)
876 .with("ids[]", 2)
877 .with("q", "x");
878 assert_eq!(
879 form.json_body(),
880 r#"{"post":{"title":"Hi","n":"3"},"ids":["2"],"q":"x"}"#,
881 "setting ids[] again replaces it, as in a form"
882 );
883 assert_eq!("{}".json_body(), "{}");
884 }
885}