Initial impl

This commit is contained in:
Torbjörn Molin committed 2026-10-19 09:31:57 +02:00
commit 4b729c5d32
133 files changed
+20475

No files matched your search

+761
View File
@@ -0,0 +1,761 @@
//! `update()` tests: app behaviour without a window.
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use reqlite_core::collection::{Collection, Node};
use reqlite_core::env::EnvFile;
use reqlite_core::http::{BodyStore, Timings};
use super::*;
fn state() -> AppState {
AppState::default()
}
fn active(s: &AppState) -> TabId {
s.active.expect("an active tab")
}
fn response(status: u16, body: &str, headers: &[(&str, &str)]) -> Response {
Response {
status,
reason: "OK".into(),
http_version: "HTTP/1.1".into(),
headers: headers.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
body: BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())),
timings: Timings {
total: Duration::from_millis(12),
..Default::default()
},
size: body.len() as u64,
effective_url: "http://x/".into(),
}
}
/// A loaded collection at `/c` with the given files.
fn with_collection(s: &mut AppState, files: &[(&str, &str)]) -> PathBuf {
let root = PathBuf::from("/c");
let c = Collection {
root: root.clone(),
tree: Node::Folder {
name: "c".into(),
path: root.clone(),
children: files
.iter()
.map(|(n, _)| Node::File {
name: n.to_string(),
path: root.join(n),
})
.collect(),
},
files: files
.iter()
.map(|(n, t)| (root.join(n), HttpFile::parse(t.to_string())))
.collect(),
};
let fx = update(s, Action::CollectionLoaded(Ok(c)));
assert!(fx.iter().any(|e| matches!(e, Effect::Watch(Some(_)))));
assert!(fx.iter().any(|e| matches!(e, Effect::LoadEnvironments(_))));
root
}
fn writes(fx: &[Effect]) -> Vec<(PathBuf, String)> {
fx.iter()
.filter_map(|e| match e {
Effect::FileOps { ops, .. } => Some(ops),
_ => None,
})
.flatten()
.filter_map(|op| match op {
FileOp::Write(p, t) => Some((p.clone(), t.clone())),
_ => None,
})
.collect()
}
// ------------------------------------------------------------- URL & params
#[test]
fn url_and_params_stay_in_sync() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "{{base}}/users?limit=20&q=a".into()));
let t = s.tab(id).unwrap();
assert_eq!(t.params, vec![Param::new("limit", "20"), Param::new("q", "a")]);
let mut p = t.params.clone();
p[0].value = Some("50".into());
p.remove(1);
p.push(Param::new("sort", "{{order}}"));
update(&mut s, Action::ParamsEdited(id, p));
assert_eq!(s.tab(id).unwrap().request.url, "{{base}}/users?limit=50&sort={{order}}");
update(&mut s, Action::ParamsEdited(id, vec![]));
assert_eq!(s.tab(id).unwrap().request.url, "{{base}}/users");
}
#[test]
fn pasting_curl_into_the_url_bar_imports_it() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(
&mut s,
Action::UrlEdited(
id,
"curl -X POST 'https://api.x/y?z=1' -H 'A: b' --data-raw '{\"k\":1}'".into(),
),
);
let t = s.tab(id).unwrap();
assert_eq!(t.request.method, Method::Post);
assert_eq!(t.request.url, "https://api.x/y?z=1");
assert_eq!(t.request.header("A"), Some("b"));
assert_eq!(t.request.body, Body::Text("{\"k\":1}".into()));
assert_eq!(t.params, vec![Param::new("z", "1")]);
}
#[test]
fn form_edits_update_the_source_and_source_edits_update_the_form() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://x/a".into()));
assert_eq!(s.tab(id).unwrap().source, "GET http://x/a\n");
update(&mut s, Action::SourceEdited(id, "POST http://x/b\nA: 1\n\nbody".into()));
let t = s.tab(id).unwrap();
assert_eq!(t.request.method, Method::Post);
assert_eq!(t.request.url, "http://x/b");
assert_eq!(t.request.body, Body::Text("body".into()));
assert!(t.source_error.is_none());
update(&mut s, Action::SourceEdited(id, "GET /a\n\n###\nGET /b\n".into()));
assert!(s.tab(id).unwrap().source_error.is_some());
// Sending is refused while the source is broken.
assert!(update(&mut s, Action::Send(id)).is_empty());
}
// ---------------------------------------------------------- send & receive
#[test]
fn send_then_receive() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://localhost/x".into()));
let fx = update(&mut s, Action::Send(id));
let (seq, cancel) = match &fx[..] {
[Effect::SendRequest {
tab,
seq,
request,
cancel,
}] => {
assert_eq!(*tab, id);
assert_eq!(request.url, "http://localhost/x");
(*seq, cancel.clone())
}
other => panic!("{other:?}"),
};
assert!(s.tab(id).unwrap().in_flight.is_some());
// A second send while in flight is ignored.
assert!(update(&mut s, Action::Send(id)).is_empty());
let fx = update(
&mut s,
Action::ResponseReceived {
tab: id,
seq,
result: Ok(response(200, "{\"a\":1}", &[("content-type", "application/json")])),
},
);
assert!(!cancel.is_cancelled());
let t = s.tab(id).unwrap();
assert!(t.in_flight.is_none());
assert_eq!(t.response.as_ref().unwrap().response.status, 200);
assert!(fx.iter().any(|e| matches!(e, Effect::PrepareBody { .. })));
assert!(fx
.iter()
.any(|e| matches!(e, Effect::AppendHistory(h) if h.status == Some(200))));
assert_eq!(s.history.len(), 1);
}
#[test]
fn cancel_stops_the_request_and_ignores_a_late_response() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://localhost/slow".into()));
let fx = update(&mut s, Action::Send(id));
let Effect::SendRequest { seq, cancel, .. } = &fx[0] else {
panic!()
};
let (seq, cancel) = (*seq, cancel.clone());
update(&mut s, Action::Cancel(id));
assert!(cancel.is_cancelled());
let t = s.tab(id).unwrap();
assert!(t.in_flight.is_none());
assert_eq!(t.error.as_deref(), Some("Cancelled"));
let fx = update(
&mut s,
Action::ResponseReceived {
tab: id,
seq,
result: Ok(response(200, "late", &[])),
},
);
assert!(fx.is_empty());
assert!(s.tab(id).unwrap().response.is_none());
assert!(s.history.is_empty());
}
#[test]
fn unresolved_variables_are_reported_not_sent() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "{{base}}/x".into()));
assert!(update(&mut s, Action::Send(id)).is_empty());
assert_eq!(s.tab(id).unwrap().error.as_deref(), Some("unknown variable `base`"));
}
#[test]
fn environments_resolve_and_switch() {
let mut s = state();
let root = with_collection(
&mut s,
&[("a.http", "### A\nGET {{base}}/x\nAuthorization: Bearer {{token}}\n")],
);
let envs = Environments {
public: EnvFile::parse(
r#"{"dev": {"base": "http://dev"}, "prod": {"base": "https://prod"}}"#,
&root,
)
.unwrap(),
private: EnvFile::parse(r#"{"dev": {"token": "t-dev"}, "prod": {"token": "t-prod"}}"#, &root).unwrap(),
};
update(&mut s, Action::EnvironmentsLoaded(Ok((envs, false))));
update(
&mut s,
Action::OpenRequest {
file: root.join("a.http"),
index: 0,
},
);
let id = active(&s);
for (env, url, auth) in [
("dev", "http://dev/x", "Bearer t-dev"),
("prod", "https://prod/x", "Bearer t-prod"),
] {
update(&mut s, Action::SelectEnv(Some(env.into())));
let fx = update(&mut s, Action::Send(id));
let Effect::SendRequest { request, seq, .. } = &fx[0] else {
panic!()
};
assert_eq!(request.url, url);
assert_eq!(request.headers[0].1, auth);
assert!(s.is_private_var("token"));
let seq = *seq;
update(
&mut s,
Action::ResponseReceived {
tab: id,
seq,
result: Err(HttpError::Timeout),
},
);
}
}
#[test]
fn cookies_are_stored_and_sent_unless_disabled() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://h/login".into()));
let fx = update(&mut s, Action::Send(id));
let Effect::SendRequest { seq, .. } = &fx[0] else {
panic!()
};
let seq = *seq;
update(
&mut s,
Action::ResponseReceived {
tab: id,
seq,
result: Ok(response(200, "", &[("set-cookie", "sid=1; Path=/")])),
},
);
let fx = update(&mut s, Action::Send(id));
let Effect::SendRequest { request, seq, .. } = &fx[0] else {
panic!()
};
assert!(request.headers.contains(&("Cookie".into(), "sid=1".into())));
let seq = *seq;
update(
&mut s,
Action::ResponseReceived {
tab: id,
seq,
result: Err(HttpError::Timeout),
},
);
update(
&mut s,
Action::SourceEdited(id, "# @no-cookie-jar\nGET http://h/login\n".into()),
);
let fx = update(&mut s, Action::Send(id));
let Effect::SendRequest { request, .. } = &fx[0] else {
panic!()
};
assert!(request.headers.iter().all(|(n, _)| n != "Cookie"));
}
#[test]
fn no_log_keeps_requests_out_of_history() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(
&mut s,
Action::SourceEdited(id, "# @no-log\nGET http://h/secret\n".into()),
);
let fx = update(&mut s, Action::Send(id));
let Effect::SendRequest { seq, .. } = &fx[0] else {
panic!()
};
let seq = *seq;
let fx = update(
&mut s,
Action::ResponseReceived {
tab: id,
seq,
result: Ok(response(200, "", &[])),
},
);
assert!(s.history.is_empty());
assert!(!fx.iter().any(|e| matches!(e, Effect::AppendHistory(_))));
}
#[test]
fn search_finds_matches_in_the_prepared_body() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://h/".into()));
let fx = update(&mut s, Action::Send(id));
let Effect::SendRequest { seq, .. } = &fx[0] else {
panic!()
};
let seq = *seq;
let body = "{\"name\":\"Ada\",\"friend\":{\"name\":\"Grace\"}}";
update(
&mut s,
Action::ResponseReceived {
tab: id,
seq,
result: Ok(response(200, body, &[("content-type", "application/json")])),
},
);
let prepared = prepare_body(
&BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())),
"application/json",
1 << 20,
);
assert_eq!(prepared.kind, BodyKind::Json);
update(
&mut s,
Action::BodyPrepared {
tab: id,
seq,
body: prepared,
},
);
update(&mut s, Action::SearchQuery(id, "NAME".into()));
let t = s.tab(id).unwrap();
assert_eq!(t.search.matches.len(), 2);
assert_eq!(t.search.scroll_to, Some(t.search.matches[0].0));
update(&mut s, Action::SearchStep(id, 1));
update(&mut s, Action::SearchStep(id, 1));
assert_eq!(s.tab(id).unwrap().search.current, 0, "wraps around");
}
// ----------------------------------------------------------- collections
const USERS: &str = "### List users\nGET {{base}}/users\n\n### Create user\n# @name create-user\nPOST {{base}}/users\nContent-Type: application/json\n\n{\"name\": \"Ada\"}\n\n> {% client.global.set(\"id\", response.body.id) %}\n";
#[test]
fn saving_an_unchanged_request_writes_nothing() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS)]);
update(
&mut s,
Action::OpenRequest {
file: root.join("users.http"),
index: 1,
},
);
let id = active(&s);
assert!(!s.tab(id).unwrap().is_dirty());
let fx = update(&mut s, Action::Save(id));
assert!(writes(&fx).is_empty(), "{fx:?}");
}
#[test]
fn saving_an_edit_rewrites_only_that_request() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS)]);
let file = root.join("users.http");
update(
&mut s,
Action::OpenRequest {
file: file.clone(),
index: 1,
},
);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "{{base}}/v2/users".into()));
assert!(s.tab(id).unwrap().is_dirty());
let fx = update(&mut s, Action::Save(id));
let w = writes(&fx);
assert_eq!(w.len(), 1);
assert_eq!(w[0].0, file);
assert_eq!(w[0].1, USERS.replace("POST {{base}}/users", "POST {{base}}/v2/users"));
assert!(!s.tab(id).unwrap().is_dirty());
// A second save is a no-op.
assert!(writes(&update(&mut s, Action::Save(id))).is_empty());
}
#[test]
fn saving_from_the_source_tab_keeps_comments() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS)]);
let file = root.join("users.http");
update(
&mut s,
Action::OpenRequest {
file: file.clone(),
index: 0,
},
);
let id = active(&s);
let src = s.tab(id).unwrap().source.clone();
assert_eq!(src, "### List users\nGET {{base}}/users\n");
update(&mut s, Action::SourceEdited(id, format!("{src}# a new comment\n")));
assert!(s.tab(id).unwrap().is_dirty(), "a comment-only edit is still a change");
let w = writes(&update(&mut s, Action::Save(id)));
assert_eq!(
w[0].1,
USERS.replace("GET {{base}}/users\n", "GET {{base}}/users\n# a new comment\n")
);
}
#[test]
fn untitled_tabs_save_as_into_a_file() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS)]);
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://new".into()));
assert!(matches!(update(&mut s, Action::Save(id))[..], [Effect::PickSaveTarget(t)] if t == id));
let file = root.join("users.http");
let fx = update(
&mut s,
Action::SaveAs {
tab: id,
path: file.clone(),
existing: None,
},
);
let w = writes(&fx);
assert_eq!(w[0].1, format!("{USERS}\n###\nGET http://new\n"));
let t = s.tab(id).unwrap();
assert_eq!(t.origin.as_ref().unwrap().file, file);
assert_eq!(t.origin.as_ref().unwrap().key.index, 2);
assert!(!t.is_dirty());
}
#[test]
fn external_change_reloads_clean_tabs_and_prompts_for_dirty_ones() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS)]);
let file = root.join("users.http");
update(
&mut s,
Action::OpenRequest {
file: file.clone(),
index: 0,
},
);
let clean = active(&s);
update(
&mut s,
Action::OpenRequest {
file: file.clone(),
index: 1,
},
);
let dirty = active(&s);
update(&mut s, Action::UrlEdited(dirty, "{{base}}/mine".into()));
// Our own write echoing back changes nothing.
update(
&mut s,
Action::FileChangedOnDisk {
path: file.clone(),
text: Some(USERS.into()),
},
);
assert!(s.dialog.is_none());
let changed = USERS.replace("GET {{base}}/users", "GET {{base}}/people");
update(
&mut s,
Action::FileChangedOnDisk {
path: file.clone(),
text: Some(changed),
},
);
assert_eq!(s.tab(clean).unwrap().request.url, "{{base}}/people");
assert_eq!(
s.dialog,
Some(Dialog::Conflict {
tab: dirty,
path: file.clone()
})
);
update(
&mut s,
Action::ResolveConflict {
tab: dirty,
keep_mine: false,
},
);
assert_eq!(s.tab(dirty).unwrap().request.url, "{{base}}/users");
assert!(!s.tab(dirty).unwrap().is_dirty());
}
#[test]
fn create_rename_duplicate_move_delete() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS), ("other.http", "### X\nGET /x\n")]);
let users = root.join("users.http");
let other = root.join("other.http");
// New request in a file.
let w = writes(&update(&mut s, Action::NewRequestIn { file: other.clone() }));
assert_eq!(w[0].1, "### X\nGET /x\n\n### New request\nGET \n");
// Rename (the @name follows the title).
let w = writes(&update(
&mut s,
Action::RenameRequest {
file: users.clone(),
index: 1,
title: "Add user".into(),
},
));
assert!(w[0].1.contains("### Add user\n# @name add-user\nPOST"));
// Duplicate.
let w = writes(&update(
&mut s,
Action::DuplicateRequest {
file: users.clone(),
index: 0,
},
));
let f = HttpFile::parse(w[0].1.clone());
let names: Vec<_> = f.requests().map(|r| r.display_name().unwrap().to_string()).collect();
assert_eq!(names, ["List users", "List users copy", "add-user"]);
// The open tab is now the copy.
let copy_tab = active(&s);
assert_eq!(s.tab(copy_tab).unwrap().origin.as_ref().unwrap().key.index, 1);
// Move the copy to the other file; its tab follows.
let fx = update(
&mut s,
Action::MoveRequest {
from: users.clone(),
index: 1,
to: other.clone(),
},
);
let w = writes(&fx);
let o = w.iter().find(|(p, _)| p == &other).unwrap();
assert!(o.1.ends_with("### List users copy\nGET {{base}}/users\n"));
let u = w.iter().find(|(p, _)| p == &users).unwrap();
assert_eq!(HttpFile::parse(u.1.clone()).request_count(), 2);
let origin = s.tab(copy_tab).unwrap().origin.clone().unwrap();
assert_eq!(origin.file, other);
assert_eq!(origin.key.index, 2);
// Delete orphans the tab.
update(
&mut s,
Action::DeleteRequest {
file: other.clone(),
index: 2,
},
);
assert!(s.tab(copy_tab).unwrap().orphaned);
assert_eq!(s.collection.as_ref().unwrap().files[&other].request_count(), 2);
}
#[test]
fn new_file_and_rename_file() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS)]);
let fx = update(
&mut s,
Action::NewFile {
dir: root.clone(),
name: "orders".into(),
},
);
let w = writes(&fx);
assert_eq!(w[0], (root.join("orders.http"), "### New request\nGET \n".to_string()));
assert!(matches!(&fx[0], Effect::FileOps { rescan: Some(_), .. }));
let id = active(&s);
let fx = update(
&mut s,
Action::RenameFile {
path: root.join("orders.http"),
new_name: "shop".into(),
},
);
assert!(
matches!(&fx[0], Effect::FileOps { ops, .. } if ops == &[FileOp::Rename(root.join("orders.http"), root.join("shop.http"))])
);
assert_eq!(s.tab(id).unwrap().origin.as_ref().unwrap().file, root.join("shop.http"));
}
#[test]
fn closing_a_dirty_tab_asks_first() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::CloseTab(id));
assert!(s.tabs.is_empty(), "a clean tab closes right away");
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://x".into()));
update(&mut s, Action::CloseTab(id));
assert_eq!(s.dialog, Some(Dialog::ConfirmCloseTab(id)));
update(&mut s, Action::DiscardAndCloseTab(id));
assert!(s.tabs.is_empty());
assert!(s.dialog.is_none());
}
#[test]
fn quitting_with_unsaved_changes_asks_first() {
let mut s = state();
update(&mut s, Action::NewTab);
let id = active(&s);
update(&mut s, Action::UrlEdited(id, "http://x".into()));
assert!(update(&mut s, Action::CloseRequested).is_empty());
assert_eq!(s.dialog, Some(Dialog::ConfirmQuit));
assert!(matches!(update(&mut s, Action::ConfirmQuit)[..], [Effect::Quit]));
assert!(s.quit_confirmed);
}
#[test]
fn restore_history_opens_a_new_tab() {
let mut s = state();
update(
&mut s,
Action::HistoryLoaded(vec![HistoryEntry {
at: 0,
method: "POST".into(),
url: "http://x/y".into(),
status: Some(201),
duration_ms: 3,
env: None,
http: "### Make\nPOST http://x/y\n\nhello\n".into(),
error: None,
}]),
);
update(&mut s, Action::RestoreHistory(0));
let t = s.active_tab().unwrap();
assert_eq!(t.request.method, Method::Post);
assert_eq!(t.request.body, Body::Text("hello".into()));
assert!(t.origin.is_none());
}
#[test]
fn env_editor_writes_both_files() {
let mut s = state();
let root = with_collection(&mut s, &[]);
update(&mut s, Action::OpenEnvEditor);
let mut ed = s.env_editor.clone().unwrap();
ed.envs.public.env_mut("dev").set("base", "http://localhost");
ed.envs.private.env_mut("dev").set("token", "secret");
update(&mut s, Action::EnvEditorChanged(ed));
let fx = update(&mut s, Action::EnvEditorSave);
let w = writes(&fx);
assert_eq!(w.len(), 2);
assert!(w
.iter()
.any(|(p, t)| p == &root.join(env::PUBLIC_FILE) && t.contains("\"base\": \"http://localhost\"")));
assert!(w
.iter()
.any(|(p, t)| p == &root.join(env::PRIVATE_FILE) && t.contains("\"token\": \"secret\"")));
assert_eq!(s.collection.as_ref().unwrap().envs.names(), vec!["dev"]);
}
#[test]
fn body_file_paths_are_stored_relative_to_the_http_file() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS)]);
update(
&mut s,
Action::OpenRequest {
file: root.join("users.http"),
index: 1,
},
);
let id = active(&s);
update(&mut s, Action::BodyFilePicked(id, root.join("payloads/a.json")));
assert_eq!(
s.tab(id).unwrap().request.body,
Body::FileRef {
path: "./payloads/a.json".into(),
substitute: false
}
);
}
#[test]
fn duplicate_file_copies_it_under_a_free_name() {
let mut s = state();
let root = with_collection(&mut s, &[("users.http", USERS), ("users copy.http", "GET /x\n")]);
let fx = update(&mut s, Action::DuplicateFile(root.join("users.http")));
assert_eq!(writes(&fx), vec![(root.join("users copy 2.http"), USERS.to_string())]);
}
#[test]
fn concurrency_setting_reaches_the_runner() {
let mut s = state();
let fx = update(
&mut s,
Action::SettingsLoaded(Settings {
max_concurrent_requests: 3,
..Settings::default()
}),
);
assert!(matches!(fx[..], [Effect::SetConcurrency(3)]));
let mut changed = s.settings.clone();
changed.max_concurrent_requests = 5;
let fx = update(&mut s, Action::SettingsChanged(changed));
assert!(fx.iter().any(|e| matches!(e, Effect::SetConcurrency(5))));
}