use std::fmt;
use std::future::Future;
use std::sync::Arc;
use http::{HeaderMap, Method, StatusCode};
use serde::Serialize;
use super::{TestClient, setup};
use crate::app::App;
use crate::config::Config;
use crate::context::Params;
use crate::db::migration::Migration;
use crate::db::{Changeset, Repo, Save};
use crate::model::Model;
use crate::response::Response;
use crate::router::ToPath;
#[derive(Clone, Copy)]
pub struct Harness {
app: fn(Config, Repo) -> crate::Result<App>,
migrations: fn() -> Vec<Migration>,
}
impl Harness {
pub fn new(
app: fn(Config, Repo) -> crate::Result<App>,
migrations: fn() -> Vec<Migration>,
) -> Self {
Self { app, migrations }
}
}
tokio::task_local! {
static CLIENT: Arc<TestClient>;
}
pub async fn run<F: Future<Output = ()>>(harness: Harness, test: F) {
let (config, repo) = setup((harness.migrations)()).await;
let url: String = config.get("database.url").unwrap_or_default();
let fresh = url.starts_with("sqlite:") && url.contains(":memory:");
let app = (harness.app)(config, repo.clone()).expect("building the app under test");
let client = Arc::new(TestClient::new(app));
let service = client.service();
service
.migrate_named()
.await
.expect("migrating the named test databases");
let databases = service
.named_databases()
.await
.expect("connecting to the named test databases");
if fresh {
let named = databases
.iter()
.map(|(name, repo)| (name.clone(), crate::db::Connection::from(repo)))
.collect();
let test = crate::db::scope_named(named, test);
CLIENT.scope(client, crate::db::with(&repo, test)).await;
} else {
let mut transactions = Vec::new();
for (name, repo) in &databases {
let tx = repo
.begin()
.await
.expect("starting a named test transaction");
transactions.push((name.clone(), tx));
}
let named = transactions
.iter()
.map(|(name, tx)| (name.clone(), crate::db::Connection::from(tx)))
.collect();
let test = crate::db::scope_named(named, test);
CLIENT
.scope(client, crate::db::sandbox(&repo, test))
.await
.expect("rolling back the test's transaction");
for (_, tx) in transactions {
tx.rollback()
.await
.expect("rolling back a named test transaction");
}
}
}
pub fn bearer(token: impl AsRef<str>) {
client().bearer(token);
}
pub fn path_prefix(prefix: impl Into<String>) {
client().path_prefix(prefix);
}
pub fn header(name: &str, value: impl AsRef<str>) {
client().header(name, value);
}
pub fn set_cookie(name: &str, value: impl Into<String>) {
client().set_cookie(name, value);
}
pub fn basic_auth(name: &str, password: &str) {
use base64::Engine;
let encoded = base64::engine::general_purpose::STANDARD.encode(format!("{name}:{password}"));
client().header("authorization", format!("Basic {encoded}"));
}
fn client() -> Arc<TestClient> {
CLIENT.try_with(Arc::clone).expect(
"get/post/patch/put/delete need a test client: use them in a .glacier test \
or a #[glacier::test(app)] function",
)
}
pub fn test_config() -> crate::Config {
client().config()
}
pub fn sequence() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
#[track_caller]
pub fn cycle<T: Clone, const N: usize>(values: [T; N]) -> T {
assert!(N > 0, "cycle needs at least one value");
let at = std::panic::Location::caller();
let site = (at.file(), at.line(), at.column());
let turn = match CLIENT.try_with(Arc::clone) {
Ok(client) => {
let mut cycles = client.cycles.lock().unwrap_or_else(|e| e.into_inner());
let turn = cycles.entry(site).or_insert(0);
*turn += 1;
*turn - 1
}
Err(_) => usize::try_from(sequence()).unwrap_or(0),
};
values[turn % N].clone()
}
pub fn recycle<M: Clone + Send + 'static>(record: &M) {
let client = client();
client
.recycled
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(std::any::TypeId::of::<M>(), Box::new(record.clone()));
}
#[doc(hidden)]
pub async fn recycled_or<M: Clone + Send + 'static>(insert: impl Future<Output = M>) -> M {
let recycled = CLIENT.try_with(|client| {
client
.recycled
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&std::any::TypeId::of::<M>())
.and_then(|record| record.downcast_ref::<M>().cloned())
});
match recycled {
Ok(Some(record)) => record,
_ => insert.await,
}
}
pub async fn perform_jobs() -> crate::Result<usize> {
client().perform_jobs().await
}
pub async fn run_task<T: std::fmt::Display>(
name: &str,
args: impl IntoIterator<Item = T>,
) -> crate::Result<()> {
let args = args.into_iter().map(|a| a.to_string()).collect();
client().run_task(name, args).await
}
pub async fn get(path: impl ToPath) -> TestResponse {
client().get(&path.to_path()).await.into()
}
pub async fn post(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
send(Method::POST, path, form.into()).await
}
pub async fn patch(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
send(Method::PATCH, path, form.into()).await
}
pub async fn put(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
send(Method::PUT, path, form.into()).await
}
pub async fn post_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
send_json(Method::POST, path, json.json_body()).await
}
pub async fn patch_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
send_json(Method::PATCH, path, json.json_body()).await
}
pub async fn put_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
send_json(Method::PUT, path, json.json_body()).await
}
pub async fn delete_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
send_json(Method::DELETE, path, json.json_body()).await
}
async fn send_json(method: Method, path: impl ToPath, json: String) -> TestResponse {
let req = http::Request::builder()
.method(method)
.uri(path.to_path())
.header(http::header::CONTENT_TYPE, "application/json")
.body(bytes::Bytes::from(json))
.expect("invalid test request");
client().request(req).await.into()
}
pub trait JsonBody {
fn json_body(&self) -> String;
}
impl JsonBody for str {
fn json_body(&self) -> String {
self.to_owned()
}
}
impl JsonBody for String {
fn json_body(&self) -> String {
self.clone()
}
}
impl JsonBody for Form {
fn json_body(&self) -> String {
let mut root = serde_json::Map::new();
for (name, value) in &self.0 {
let mut keys: Vec<&str> = Vec::new();
let (first, mut rest) = name
.split_once('[')
.map_or((name.as_str(), ""), |(a, b)| (a, b));
keys.push(first);
while let Some((key, after)) = rest.split_once(']') {
keys.push(key);
rest = after.strip_prefix('[').unwrap_or(after);
}
insert_json(&mut root, &keys, value);
}
serde_json::Value::Object(root).to_string()
}
}
fn insert_json(
object: &mut serde_json::Map<String, serde_json::Value>,
keys: &[&str],
value: &str,
) {
use serde_json::Value;
let (key, rest) = (keys[0].to_owned(), &keys[1..]);
match rest {
[] => {
object.insert(key, Value::String(value.to_owned()));
}
[""] => {
let entry = object
.entry(key)
.or_insert_with(|| Value::Array(Vec::new()));
if let Value::Array(items) = entry {
items.push(Value::String(value.to_owned()));
}
}
_ => {
let entry = object
.entry(key)
.or_insert_with(|| Value::Object(serde_json::Map::new()));
if !entry.is_object() {
*entry = Value::Object(serde_json::Map::new());
}
if let Value::Object(inner) = entry {
insert_json(inner, rest, value);
}
}
}
}
impl<T: JsonBody + ?Sized> JsonBody for &T {
fn json_body(&self) -> String {
(**self).json_body()
}
}
pub async fn delete(path: impl ToPath) -> TestResponse {
client().delete(&path.to_path()).await.into()
}
async fn send(method: Method, path: impl ToPath, form: Form) -> TestResponse {
if form.1.is_empty() {
return client()
.send_form(method, &path.to_path(), &form.0)
.await
.into();
}
let boundary = format!("----glacier{:016x}", rand_boundary());
let mut body = Vec::new();
for (name, value) in &form.0 {
body.extend_from_slice(
format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
)
.as_bytes(),
);
}
for (name, upload) in &form.1 {
body.extend_from_slice(
format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
upload.filename, upload.content_type
)
.as_bytes(),
);
body.extend_from_slice(&upload.bytes);
body.extend_from_slice(b"\r\n");
}
body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
let req = http::Request::builder()
.method(method)
.uri(path.to_path())
.header(
http::header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
)
.body(bytes::Bytes::from(body))
.expect("invalid test request");
client().request(req).await.into()
}
fn rand_boundary() -> u64 {
use std::hash::{BuildHasher, Hasher};
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u128(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos(),
);
hasher.finish()
}
pub fn file(
filename: &str,
content_type: &str,
bytes: impl Into<bytes::Bytes>,
) -> crate::upload::Upload {
crate::upload::Upload {
filename: filename.to_owned(),
content_type: content_type.to_owned(),
bytes: bytes.into(),
}
}
#[derive(Debug)]
pub struct TestResponse {
pub status: Status,
pub body: String,
pub location: String,
pub headers: HeaderMap,
}
impl TestResponse {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.get(name).and_then(|value| value.to_str().ok())
}
#[track_caller]
pub fn json(&self) -> serde_json::Value {
serde_json::from_str(&self.body)
.unwrap_or_else(|e| panic!("the response isn't JSON ({e}):\n{}", self.body))
}
}
impl From<Response> for TestResponse {
fn from(res: Response) -> Self {
Self {
status: Status(res.status()),
body: res.body_text(),
location: res.header("location").unwrap_or_default().to_owned(),
headers: res.headers().clone(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Status(pub StatusCode);
impl Status {
pub fn name(&self) -> String {
crate::response::status_name(self.0)
}
#[track_caller]
pub fn named(name: &str) -> Self {
crate::response::status_named(name)
.map(Status)
.unwrap_or_else(|| panic!("no HTTP status is called `:{name}`"))
}
}
impl fmt::Debug for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, ":{} ({})", self.name(), self.0.as_u16())
}
}
impl PartialEq<&str> for Status {
#[track_caller]
fn eq(&self, name: &&str) -> bool {
*self == Status::named(name)
}
}
impl PartialEq<u16> for Status {
fn eq(&self, code: &u16) -> bool {
self.0.as_u16() == *code
}
}
impl PartialEq<i32> for Status {
fn eq(&self, code: &i32) -> bool {
i32::from(self.0.as_u16()) == *code
}
}
impl PartialEq<StatusCode> for Status {
fn eq(&self, code: &StatusCode) -> bool {
self.0 == *code
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Form(
Vec<(String, String)>,
#[serde(skip)]
Vec<(String, crate::upload::Upload)>,
);
impl Form {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(self, name: &str, value: impl FormValue) -> Self {
value.add_to(self, name)
}
#[must_use]
pub fn with_all<T: fmt::Display>(
mut self,
name: &str,
values: impl IntoIterator<Item = T>,
) -> Self {
let field = format!("{name}[]");
self.0.retain(|(k, _)| *k != field);
self.0.extend(
values
.into_iter()
.map(|value| (field.clone(), value.to_string())),
);
self
}
fn set(mut self, name: &str, value: String) -> Self {
match self.0.iter_mut().find(|(k, _)| k == name) {
Some(field) => field.1 = value,
None => self.0.push((name.to_owned(), value)),
}
self
}
#[must_use]
pub fn without(mut self, name: &str) -> Self {
self.0.retain(|(k, _)| k != name);
self
}
pub fn get(&self, name: &str) -> Option<&str> {
self.0
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
}
}
pub trait FormValue {
fn add_to(self, form: Form, name: &str) -> Form;
}
impl<T: fmt::Display> FormValue for T {
fn add_to(self, form: Form, name: &str) -> Form {
form.set(name, self.to_string())
}
}
impl FormValue for Form {
fn add_to(self, form: Form, name: &str) -> Form {
let nest = |field: &str| {
let (head, rest) = field.split_at(field.find('[').unwrap_or(field.len()));
format!("{name}[{head}]{rest}")
};
let mut form = self
.0
.into_iter()
.fold(form, |form, (field, value)| form.set(&nest(&field), value));
for (field, upload) in self.1 {
let field = nest(&field);
form.1.retain(|(name, _)| *name != field);
form.1.push((field, upload));
}
form
}
}
impl FormValue for crate::upload::Upload {
fn add_to(self, mut form: Form, name: &str) -> Form {
form.1.retain(|(field, _)| field != name);
form.1.push((name.to_owned(), self));
form
}
}
impl From<&Form> for Form {
fn from(form: &Form) -> Self {
form.clone()
}
}
impl From<()> for Form {
fn from((): ()) -> Self {
Form::new()
}
}
impl From<Form> for Params {
fn from(form: Form) -> Self {
form.0.into_iter().collect()
}
}
impl<K: AsRef<str>, V: fmt::Display> FromIterator<(K, V)> for Form {
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
iter.into_iter()
.fold(Form::new(), |form, (k, v)| form.with(k.as_ref(), v))
}
}
impl<M: Model> From<Form> for Changeset<M> {
fn from(form: Form) -> Self {
Params::from(form).into()
}
}
#[track_caller]
pub fn errors_on<M: Model>(save: Save<M>) -> String {
save.unwrap_invalid().messages().join("; ")
}
pub async fn insert<M: Model + Default + Clone>(form: Form) -> Save<M> {
let params = Params::from(form);
let mut record = M::build(params.clone());
record.assign_protected(¶ms);
save_inserted(record).await
}
pub async fn insert_for<M, A>(access: &A, form: Form) -> Save<M>
where
M: Model + Default + Clone,
A: crate::access::Access + Clone,
{
let params = Params::from(form);
let mut built = M::build(params.clone());
built.assign_protected(¶ms);
let record = M::r#for(access).build_with(|record| *record = built);
crate::access::with_access(access.clone(), save_inserted(record)).await
}
async fn save_inserted<M: Model + Clone>(mut record: M) -> Save<M> {
let saved = record
.save()
.await
.unwrap_or_else(|e| panic!("inserting a {}: {e}", std::any::type_name::<M>()));
if saved {
return Save::Saved(record);
}
let mut changeset = Changeset::<M>::new();
for (column, message) in record.errors() {
changeset = changeset.push_error(column, message.clone());
}
Save::Invalid(changeset)
}
#[track_caller]
pub fn assert_equal<L, R>(left: &L, right: &R, source: &str)
where
L: PartialEq<R> + fmt::Debug + ?Sized,
R: fmt::Debug + ?Sized,
{
if left != right {
panic!("assertion failed: {source}\n left: {left:?}\n right: {right:?}");
}
}
#[track_caller]
pub fn assert_not_equal<L, R>(left: &L, right: &R, source: &str)
where
L: PartialEq<R> + fmt::Debug + ?Sized,
R: fmt::Debug + ?Sized,
{
if left == right {
panic!("assertion failed: {source}\n both sides: {left:?}");
}
}
#[track_caller]
pub fn assert_contains(
text: &(impl AsRef<str> + ?Sized),
part: &(impl AsRef<str> + ?Sized),
source: &str,
) {
let (text, part) = (text.as_ref(), part.as_ref());
if !text.contains(part) {
panic!(
"assertion failed: {source}\n expected to contain: {part:?}\n but was: {}",
excerpt(text)
);
}
}
#[track_caller]
pub fn refute_contains(
text: &(impl AsRef<str> + ?Sized),
part: &(impl AsRef<str> + ?Sized),
source: &str,
) {
let (text, part) = (text.as_ref(), part.as_ref());
if text.contains(part) {
panic!(
"refute failed: {source}\n expected not to contain: {part:?}\n but was: {}",
excerpt(text)
);
}
}
#[track_caller]
pub fn assert_true(condition: bool, source: &str) {
if !condition {
panic!("assertion failed: {source}");
}
}
#[track_caller]
pub fn refute_true(condition: bool, source: &str) {
if condition {
panic!("refute failed: {source}");
}
}
fn excerpt(text: &str) -> String {
const MAX: usize = 600;
match text.char_indices().nth(MAX) {
Some((cut, _)) => format!("{:?}… ({} more bytes)", &text[..cut], text.len() - cut),
None => format!("{text:?}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn statuses_compare_by_name_and_number() {
let s = Status(StatusCode::SEE_OTHER);
assert_eq!(s.name(), "see_other");
assert!(s == "see_other");
assert!(s == 303);
assert!(Status(StatusCode::UNPROCESSABLE_ENTITY) == "unprocessable_entity");
assert!(Status(StatusCode::OK) == "ok");
assert_eq!(format!("{s:?}"), ":see_other (303)");
}
#[test]
#[should_panic(expected = "no HTTP status is called `:se_other`")]
fn unknown_status_names_fail() {
let _ = Status(StatusCode::OK) == "se_other";
}
#[test]
fn forms_replace_fields() {
let form = Form::new()
.with("title", "a")
.with("n", 1)
.with("title", "b");
assert_eq!(form.get("title"), Some("b"));
assert_eq!(form.without("n"), Form::new().with("title", "b"));
}
#[test]
fn nested_forms_send_rails_style_keys() {
let tags = Form::new().with("0", "a");
let form = Form::new().with("post", Form::new().with("title", "Hi").with("tags", tags));
assert_eq!(form.get("post[title]"), Some("Hi"));
assert_eq!(form.get("post[tags][0]"), Some("a"));
}
#[test]
#[should_panic(expected = "assertion failed: res.body =~ \"x\"")]
fn contains_explains_itself() {
assert_contains("hello", "x", "res.body =~ \"x\"");
}
#[test]
fn forms_become_json_objects() {
let form = Form::new()
.with("post", Form::new().with("title", "Hi").with("n", 3))
.with("ids[]", 1)
.with("ids[]", 2)
.with("q", "x");
assert_eq!(
form.json_body(),
r#"{"post":{"title":"Hi","n":"3"},"ids":["2"],"q":"x"}"#,
"setting ids[] again replaces it, as in a form"
);
assert_eq!("{}".json_body(), "{}");
}
}