1388 lines
44 KiB
Rust
1388 lines
44 KiB
Rust
//! `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 reqlite_core::folder::{AuthHeader, AuthMode, FolderAuth};
|
||
|
||
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 {
|
||
with_collection_at(s, "/c", files)
|
||
}
|
||
|
||
/// Loads a collection at `root` with the given files.
|
||
fn with_collection_at(s: &mut AppState, root: &str, files: &[(&str, &str)]) -> PathBuf {
|
||
let root = PathBuf::from(root);
|
||
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(),
|
||
folders: Default::default(),
|
||
folder_errors: Vec::new(),
|
||
};
|
||
let fx = update(s, Action::CollectionLoaded(Ok(c)));
|
||
assert!(fx.iter().any(|e| matches!(e, Effect::Watch(_))));
|
||
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 {
|
||
root: root.clone(),
|
||
result: 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(s.tab(id).unwrap(), "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_of(&other).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(&root).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))));
|
||
}
|
||
|
||
// ------------------------------------------------- several collections
|
||
|
||
fn load_envs(s: &mut AppState, root: &Path, public: &str) {
|
||
let envs = Environments {
|
||
public: EnvFile::parse(public, root).unwrap(),
|
||
private: EnvFile::default(),
|
||
};
|
||
update(
|
||
s,
|
||
Action::EnvironmentsLoaded {
|
||
root: root.to_path_buf(),
|
||
result: Ok((envs, false)),
|
||
},
|
||
);
|
||
}
|
||
|
||
fn sent_url(s: &mut AppState, id: TabId) -> String {
|
||
let fx = update(s, Action::Send(id));
|
||
let Effect::SendRequest { request, seq, .. } = &fx[0] else {
|
||
panic!("{fx:?} / {:?}", s.tab(id).unwrap().error)
|
||
};
|
||
let (url, seq) = (request.url.clone(), *seq);
|
||
update(
|
||
s,
|
||
Action::ResponseReceived {
|
||
tab: id,
|
||
seq,
|
||
result: Err(HttpError::Timeout),
|
||
},
|
||
);
|
||
url
|
||
}
|
||
|
||
#[test]
|
||
fn each_collection_has_its_own_environment() {
|
||
let mut s = state();
|
||
let a = with_collection_at(&mut s, "/a", &[("a.http", "### A\nGET {{base}}/a\n")]);
|
||
let b = with_collection_at(&mut s, "/b", &[("b.http", "### B\nGET {{base}}/b\n")]);
|
||
assert_eq!(s.collections.len(), 2);
|
||
load_envs(&mut s, &a, r#"{"dev": {"base": "http://a-dev"}}"#);
|
||
load_envs(
|
||
&mut s,
|
||
&b,
|
||
r#"{"dev": {"base": "http://b-dev"}, "prod": {"base": "https://b-prod"}}"#,
|
||
);
|
||
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: a.join("a.http"),
|
||
index: 0,
|
||
},
|
||
);
|
||
let ta = active(&s);
|
||
update(&mut s, Action::SelectEnv(Some("dev".into())));
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: b.join("b.http"),
|
||
index: 0,
|
||
},
|
||
);
|
||
let tb = active(&s);
|
||
// The picker now acts on /b, which has no environment selected yet.
|
||
assert_eq!(s.current_collection().unwrap().root, b);
|
||
assert!(s.current_collection().unwrap().selected_env.is_none());
|
||
update(&mut s, Action::SelectEnv(Some("prod".into())));
|
||
|
||
assert_eq!(sent_url(&mut s, ta), "http://a-dev/a");
|
||
assert_eq!(sent_url(&mut s, tb), "https://b-prod/b");
|
||
assert_eq!(s.collection(&a).unwrap().selected_env.as_deref(), Some("dev"));
|
||
}
|
||
|
||
#[test]
|
||
fn untitled_tabs_use_the_active_collection() {
|
||
let mut s = state();
|
||
let a = with_collection_at(&mut s, "/a", &[]);
|
||
let b = with_collection_at(&mut s, "/b", &[]);
|
||
load_envs(&mut s, &a, r#"{"dev": {"base": "http://a"}}"#);
|
||
load_envs(&mut s, &b, r#"{"dev": {"base": "http://b"}}"#);
|
||
for root in [&a, &b] {
|
||
update(&mut s, Action::SetActiveCollection(root.clone()));
|
||
update(&mut s, Action::SelectEnv(Some("dev".into())));
|
||
}
|
||
update(&mut s, Action::NewTab);
|
||
let id = active(&s);
|
||
update(&mut s, Action::UrlEdited(id, "{{base}}/x".into()));
|
||
assert_eq!(sent_url(&mut s, id), "http://b/x", "the last opened/clicked collection");
|
||
update(&mut s, Action::SetActiveCollection(a.clone()));
|
||
assert_eq!(sent_url(&mut s, id), "http://a/x");
|
||
}
|
||
|
||
#[test]
|
||
fn opening_a_collection_twice_or_nested_is_refused() {
|
||
let mut s = state();
|
||
let a = with_collection_at(&mut s, "/work/api", &[]);
|
||
with_collection_at(&mut s, "/other", &[]);
|
||
// Already open: just becomes current, nothing is loaded again.
|
||
assert!(update(&mut s, Action::OpenCollection(a.clone())).is_empty());
|
||
assert_eq!(s.active_collection.as_ref(), Some(&a));
|
||
for overlapping in ["/work/api/sub", "/work"] {
|
||
assert!(update(&mut s, Action::OpenCollection(overlapping.into())).is_empty());
|
||
assert!(s.status.as_ref().unwrap().is_error);
|
||
}
|
||
let fx = update(&mut s, Action::OpenCollection("/work/web".into()));
|
||
assert!(fx.iter().any(|e| matches!(e, Effect::LoadCollection(_))));
|
||
assert_eq!(s.settings.open_collections, vec![PathBuf::from("/work/web")]);
|
||
}
|
||
|
||
#[test]
|
||
fn closing_a_collection_closes_its_clean_tabs_and_keeps_edits() {
|
||
let mut s = state();
|
||
let a = with_collection_at(&mut s, "/a", &[("a.http", "### A\nGET /a\n\n### A2\nGET /a2\n")]);
|
||
let b = with_collection_at(&mut s, "/b", &[("b.http", "### B\nGET /b\n")]);
|
||
s.settings.open_collections = vec![a.clone(), b.clone()];
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: a.join("a.http"),
|
||
index: 0,
|
||
},
|
||
);
|
||
let clean = active(&s);
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: a.join("a.http"),
|
||
index: 1,
|
||
},
|
||
);
|
||
let dirty = active(&s);
|
||
update(&mut s, Action::UrlEdited(dirty, "/edited".into()));
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: b.join("b.http"),
|
||
index: 0,
|
||
},
|
||
);
|
||
let other = active(&s);
|
||
|
||
let fx = update(&mut s, Action::CloseCollection(a.clone()));
|
||
assert!(fx.iter().any(|e| matches!(e, Effect::Unwatch(r) if r == &a)));
|
||
assert!(s.tab(clean).is_none());
|
||
let t = s.tab(dirty).unwrap();
|
||
assert!(t.orphaned && t.origin.is_none() && t.request.url == "/edited");
|
||
assert!(s.tab(other).unwrap().origin.is_some());
|
||
assert_eq!(s.collections.len(), 1);
|
||
assert_eq!(s.settings.open_collections, vec![b]);
|
||
}
|
||
|
||
#[test]
|
||
fn moving_a_request_between_collections() {
|
||
let mut s = state();
|
||
let a = with_collection_at(&mut s, "/a", &[("a.http", "### A\nGET /a\n")]);
|
||
let b = with_collection_at(&mut s, "/b", &[("b.http", "### B\nGET /b\n")]);
|
||
let fx = update(
|
||
&mut s,
|
||
Action::MoveRequest {
|
||
from: a.join("a.http"),
|
||
index: 0,
|
||
to: b.join("b.http"),
|
||
},
|
||
);
|
||
let w = writes(&fx);
|
||
assert!(w.contains(&(b.join("b.http"), "### B\nGET /b\n\n### A\nGET /a\n".into())));
|
||
assert!(w.contains(&(a.join("a.http"), String::new())));
|
||
assert_eq!(s.collection(&b).unwrap().files[&b.join("b.http")].request_count(), 2);
|
||
}
|
||
|
||
#[test]
|
||
fn disk_changes_go_to_the_right_collection() {
|
||
let mut s = state();
|
||
let a = with_collection_at(&mut s, "/a", &[("x.http", "GET /a\n")]);
|
||
let b = with_collection_at(&mut s, "/b", &[("x.http", "GET /b\n")]);
|
||
update(
|
||
&mut s,
|
||
Action::FileChangedOnDisk {
|
||
path: b.join("x.http"),
|
||
text: Some("GET /b2\n".into()),
|
||
},
|
||
);
|
||
assert_eq!(s.collection(&a).unwrap().files[&a.join("x.http")].text(), "GET /a\n");
|
||
assert_eq!(s.collection(&b).unwrap().files[&b.join("x.http")].text(), "GET /b2\n");
|
||
// Env files reload only their own collection, and only at its root.
|
||
let fx = update(
|
||
&mut s,
|
||
Action::FileChangedOnDisk {
|
||
path: a.join(env::PUBLIC_FILE),
|
||
text: Some("{}".into()),
|
||
},
|
||
);
|
||
assert!(matches!(&fx[..], [Effect::LoadEnvironments(r)] if r == &a));
|
||
let fx = update(
|
||
&mut s,
|
||
Action::FileChangedOnDisk {
|
||
path: a.join("sub").join(env::PUBLIC_FILE),
|
||
text: Some("{}".into()),
|
||
},
|
||
);
|
||
assert!(fx.is_empty());
|
||
}
|
||
|
||
// ------------------------------------------------- close all, rename tabs
|
||
|
||
#[test]
|
||
fn close_all_closes_clean_tabs_and_asks_once_about_the_rest() {
|
||
let mut s = state();
|
||
for url in ["", "http://edited", "", "http://also-edited"] {
|
||
update(&mut s, Action::NewTab);
|
||
if !url.is_empty() {
|
||
let id = active(&s);
|
||
update(&mut s, Action::UrlEdited(id, url.into()));
|
||
}
|
||
}
|
||
let ids: Vec<TabId> = s.tabs.iter().map(|t| t.id).collect();
|
||
update(&mut s, Action::CloseTabs(ids.clone()));
|
||
assert_eq!(s.tabs.len(), 2, "the clean tabs are gone");
|
||
let dirty = vec![ids[1], ids[3]];
|
||
assert_eq!(s.dialog, Some(Dialog::ConfirmCloseTabs(dirty.clone())));
|
||
update(&mut s, Action::DiscardAndCloseTabs(dirty));
|
||
assert!(s.tabs.is_empty());
|
||
assert!(s.active.is_none());
|
||
assert!(s.dialog.is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn close_others_keeps_the_chosen_tab() {
|
||
let mut s = state();
|
||
for _ in 0..3 {
|
||
update(&mut s, Action::NewTab);
|
||
}
|
||
let keep = s.tabs[1].id;
|
||
let others = s.tabs.iter().map(|t| t.id).filter(|&t| t != keep).collect();
|
||
update(&mut s, Action::CloseTabs(others));
|
||
assert_eq!(s.tabs.len(), 1);
|
||
assert_eq!(s.active, Some(keep));
|
||
}
|
||
|
||
#[test]
|
||
fn renaming_a_clean_tab_renames_the_request_in_its_file() {
|
||
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 fx = update(
|
||
&mut s,
|
||
Action::RenameTab {
|
||
tab: id,
|
||
title: "All users".into(),
|
||
},
|
||
);
|
||
let w = writes(&fx);
|
||
assert_eq!(
|
||
w,
|
||
vec![(file.clone(), USERS.replace("### List users", "### All users"))]
|
||
);
|
||
let t = s.tab(id).unwrap();
|
||
assert_eq!(t.title(), "All users");
|
||
assert!(!t.is_dirty());
|
||
assert_eq!(t.origin.as_ref().unwrap().key.name.as_deref(), Some("All users"));
|
||
}
|
||
|
||
#[test]
|
||
fn renaming_an_edited_or_untitled_tab_is_an_edit_that_save_writes() {
|
||
let mut s = state();
|
||
let root = with_collection(&mut s, &[("users.http", USERS)]);
|
||
let file = root.join("users.http");
|
||
// `create-user` has an @name, which follows the new title.
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: file.clone(),
|
||
index: 1,
|
||
},
|
||
);
|
||
let id = active(&s);
|
||
update(&mut s, Action::UrlEdited(id, "{{base}}/v2/users".into()));
|
||
let fx = update(
|
||
&mut s,
|
||
Action::RenameTab {
|
||
tab: id,
|
||
title: "Add user".into(),
|
||
},
|
||
);
|
||
assert!(writes(&fx).is_empty(), "nothing is written before Save");
|
||
assert_eq!(s.tab(id).unwrap().title(), "add-user");
|
||
let w = writes(&update(&mut s, Action::Save(id)));
|
||
assert!(
|
||
w[0].1
|
||
.contains("### Add user\n# @name add-user\nPOST {{base}}/v2/users"),
|
||
"{}",
|
||
w[0].1
|
||
);
|
||
|
||
update(&mut s, Action::NewTab);
|
||
let untitled = active(&s);
|
||
update(
|
||
&mut s,
|
||
Action::RenameTab {
|
||
tab: untitled,
|
||
title: "Scratch".into(),
|
||
},
|
||
);
|
||
assert_eq!(s.tab(untitled).unwrap().title(), "Scratch");
|
||
assert!(s.tab(untitled).unwrap().source.starts_with("### Scratch\n"));
|
||
}
|
||
|
||
fn sent_auth(s: &mut AppState, id: TabId) -> Option<String> {
|
||
let fx = update(s, Action::Send(id));
|
||
let Some(Effect::SendRequest { request, .. }) = fx.first() else {
|
||
panic!("not sent: {:?}", s.tab(id).unwrap().error)
|
||
};
|
||
let auth = request
|
||
.headers
|
||
.iter()
|
||
.find(|(n, _)| n.eq_ignore_ascii_case("authorization"))
|
||
.map(|(_, v)| v.clone());
|
||
update(s, Action::Cancel(id));
|
||
auth
|
||
}
|
||
|
||
fn set_folder_auth(s: &mut AppState, dir: PathBuf, auth: FolderAuth) -> Vec<Effect> {
|
||
update(s, Action::SetFolderAuth { dir, auth })
|
||
}
|
||
|
||
#[test]
|
||
fn requests_inherit_folder_auth_unless_they_opt_out() {
|
||
let mut s = state();
|
||
let root = with_collection(
|
||
&mut s,
|
||
&[
|
||
(
|
||
"a.http",
|
||
"### Plain\nGET http://x/a\n\n### Own\nGET http://x/b\nAuthorization: Bearer own\n",
|
||
),
|
||
("api/b.http", "GET http://x/c\n"),
|
||
],
|
||
);
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: root.join("a.http"),
|
||
index: 0,
|
||
},
|
||
);
|
||
let plain = active(&s);
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: root.join("a.http"),
|
||
index: 1,
|
||
},
|
||
);
|
||
let own = active(&s);
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: root.join("api/b.http"),
|
||
index: 0,
|
||
},
|
||
);
|
||
let nested = active(&s);
|
||
assert_eq!(sent_auth(&mut s, plain), None);
|
||
|
||
let fx = set_folder_auth(&mut s, root.clone(), FolderAuth::Header("Bearer root".into()));
|
||
assert_eq!(
|
||
writes(&fx),
|
||
vec![(
|
||
root.join(".reqlite/folder.json"),
|
||
"{\n \"auth\": \"Bearer root\"\n}\n".into()
|
||
)]
|
||
);
|
||
assert_eq!(sent_auth(&mut s, plain).as_deref(), Some("Bearer root"));
|
||
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer own"));
|
||
assert_eq!(sent_auth(&mut s, nested).as_deref(), Some("Bearer root"));
|
||
|
||
// A subfolder overrides, and "no auth" stops inheritance.
|
||
set_folder_auth(&mut s, root.join("api"), FolderAuth::Header("Basic u p".into()));
|
||
assert_eq!(sent_auth(&mut s, nested).as_deref(), Some("Basic dTpw"));
|
||
set_folder_auth(&mut s, root.join("api"), FolderAuth::None);
|
||
assert_eq!(sent_auth(&mut s, nested), None);
|
||
// Back to inherit: the empty settings file is removed.
|
||
let fx = set_folder_auth(&mut s, root.join("api"), FolderAuth::Inherit);
|
||
assert!(fx.iter().any(|e| matches!(e, Effect::FileOps { ops, .. } if ops == &vec![FileOp::Delete(root.join("api/.reqlite/folder.json"))])));
|
||
assert_eq!(sent_auth(&mut s, nested).as_deref(), Some("Bearer root"));
|
||
|
||
// The Auth tab's None writes `# @no-auth`; Inherit removes it again.
|
||
update(&mut s, Action::AuthEdited(plain, AuthMode::NoAuth));
|
||
assert!(s.tab(plain).unwrap().source.contains("# @no-auth\nGET"));
|
||
assert_eq!(sent_auth(&mut s, plain), None);
|
||
update(&mut s, Action::AuthEdited(plain, AuthMode::Inherit));
|
||
assert!(!s.tab(plain).unwrap().source.contains("@no-auth"));
|
||
assert!(!s.tab(plain).unwrap().is_dirty());
|
||
update(&mut s, Action::AuthEdited(own, AuthMode::Inherit));
|
||
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer root"));
|
||
}
|
||
|
||
fn sent_header(s: &mut AppState, id: TabId, name: &str) -> Option<String> {
|
||
let fx = update(s, Action::Send(id));
|
||
let Some(Effect::SendRequest { request, .. }) = fx.first() else {
|
||
panic!("not sent: {:?}", s.tab(id).unwrap().error)
|
||
};
|
||
let v = request
|
||
.headers
|
||
.iter()
|
||
.find(|(n, _)| n.eq_ignore_ascii_case(name))
|
||
.map(|(_, v)| v.clone());
|
||
update(s, Action::Cancel(id));
|
||
v
|
||
}
|
||
|
||
#[test]
|
||
fn folder_and_request_auth_can_use_a_custom_header() {
|
||
let mut s = state();
|
||
let root = with_collection(
|
||
&mut s,
|
||
&[("a.http", "### Plain\nGET http://x/a\n\n### Own\nGET http://x/b\n")],
|
||
);
|
||
let open = |s: &mut AppState, index| {
|
||
update(
|
||
s,
|
||
Action::OpenRequest {
|
||
file: root.join("a.http"),
|
||
index,
|
||
},
|
||
);
|
||
active(s)
|
||
};
|
||
let plain = open(&mut s, 0);
|
||
let own = open(&mut s, 1);
|
||
|
||
let key = |v: &str| AuthHeader::custom("X-API-Key", v);
|
||
let fx = set_folder_auth(&mut s, root.clone(), FolderAuth::Header(key("k-root")));
|
||
assert_eq!(
|
||
writes(&fx),
|
||
vec![(
|
||
root.join(".reqlite/folder.json"),
|
||
"{\n \"auth\": {\n \"header\": \"X-API-Key\",\n \"value\": \"k-root\"\n }\n}\n".into()
|
||
)]
|
||
);
|
||
assert_eq!(sent_header(&mut s, plain, "x-api-key").as_deref(), Some("k-root"));
|
||
assert_eq!(sent_auth(&mut s, plain), None);
|
||
|
||
// A request's own custom header replaces the folder's.
|
||
update(&mut s, Action::AuthEdited(own, AuthMode::Own(key("k-own"))));
|
||
assert!(s
|
||
.tab(own)
|
||
.unwrap()
|
||
.source
|
||
.contains("# @auth-header X-API-Key\nGET http://x/b\nX-API-Key: k-own\n"));
|
||
assert_eq!(sent_header(&mut s, own, "x-api-key").as_deref(), Some("k-own"));
|
||
|
||
// Switching to Bearer drops the custom header and the directive.
|
||
update(&mut s, Action::AuthEdited(own, AuthMode::Own("Bearer t".into())));
|
||
let src = &s.tab(own).unwrap().source;
|
||
assert!(!src.contains("X-API-Key") && !src.contains("@auth-header"), "{src}");
|
||
assert_eq!(sent_auth(&mut s, own).as_deref(), Some("Bearer t"));
|
||
assert_eq!(sent_header(&mut s, own, "x-api-key"), None);
|
||
}
|
||
|
||
#[test]
|
||
fn folder_settings_files_are_reloaded_when_they_change() {
|
||
let mut s = state();
|
||
let root = with_collection(&mut s, &[("a.http", "GET http://x/a\n")]);
|
||
let path = root.join(".reqlite/folder.json");
|
||
update(
|
||
&mut s,
|
||
Action::FileChangedOnDisk {
|
||
path: path.clone(),
|
||
text: Some(r#"{"auth": "Bearer t"}"#.into()),
|
||
},
|
||
);
|
||
let c = s.collection(&root).unwrap();
|
||
assert_eq!(c.folder_auth(&root), FolderAuth::Header("Bearer t".into()));
|
||
update(
|
||
&mut s,
|
||
Action::FileChangedOnDisk {
|
||
path: path.clone(),
|
||
text: Some("nope".into()),
|
||
},
|
||
);
|
||
assert_eq!(s.collection(&root).unwrap().folder_errors.len(), 1);
|
||
update(&mut s, Action::FileChangedOnDisk { path, text: None });
|
||
let c = s.collection(&root).unwrap();
|
||
assert_eq!(c.folder_auth(&root), FolderAuth::Inherit);
|
||
assert!(c.folder_errors.is_empty());
|
||
}
|
||
|
||
fn consolidate(s: &mut AppState, dir: PathBuf, target: Option<&str>) -> ConsolidateAuth {
|
||
update(
|
||
s,
|
||
Action::ConsolidateAuth {
|
||
dir,
|
||
target: target.map(Into::into),
|
||
},
|
||
);
|
||
match &s.dialog {
|
||
Some(Dialog::ConsolidateAuth(p)) => p.clone(),
|
||
d => panic!("{d:?}"),
|
||
}
|
||
}
|
||
|
||
const MIXED: &str = "### A\nGET http://x/a\nAuthorization: Bearer {{token}}\n\n### B\nGET http://x/b\nAuthorization: Bearer {{token}}\n\n### C\nGET http://x/c\nAuthorization: Basic u p\n\n### D\nGET http://x/d\n\n### E\n# @no-auth\nGET http://x/e\n";
|
||
|
||
#[test]
|
||
fn consolidating_adopts_the_most_common_auth_as_the_collection_default() {
|
||
let mut s = state();
|
||
let root = with_collection(&mut s, &[("a.http", MIXED)]);
|
||
let plan = consolidate(&mut s, root.clone(), None);
|
||
assert_eq!(plan.target, Some("Bearer {{token}}".into()));
|
||
assert!(plan.set_folder);
|
||
assert_eq!(
|
||
plan.choices,
|
||
vec![("Bearer {{token}}".into(), 2), ("Basic u p".into(), 1)]
|
||
);
|
||
let selected: Vec<(&str, bool)> = plan
|
||
.own
|
||
.iter()
|
||
.map(|o| (o.request.label.as_str(), o.selected))
|
||
.collect();
|
||
assert_eq!(
|
||
selected,
|
||
vec![("a.http › A", true), ("a.http › B", true), ("a.http › C", false)]
|
||
);
|
||
// D has no auth today and would start sending the token.
|
||
assert_eq!(plan.affected.len(), 1);
|
||
assert_eq!(plan.affected[0].0.label, "a.http › D");
|
||
|
||
let fx = update(&mut s, Action::ApplyConsolidateAuth(plan));
|
||
let w = writes(&fx);
|
||
assert_eq!(w.len(), 2);
|
||
assert_eq!(
|
||
w[0].1,
|
||
"### A\nGET http://x/a\n\n### B\nGET http://x/b\n\n### C\nGET http://x/c\nAuthorization: Basic u p\n\n### D\n# @no-auth\nGET http://x/d\n\n### E\n# @no-auth\nGET http://x/e\n"
|
||
);
|
||
assert_eq!(
|
||
w[1],
|
||
(
|
||
root.join(".reqlite/folder.json"),
|
||
"{\n \"auth\": \"Bearer {{token}}\"\n}\n".into()
|
||
)
|
||
);
|
||
assert!(s.dialog.is_none());
|
||
|
||
// Doing it again finds nothing more to do.
|
||
let plan = consolidate(&mut s, root.clone(), None);
|
||
assert!(!plan.set_folder && plan.affected.is_empty());
|
||
assert_eq!(plan.own.len(), 1);
|
||
assert!(!plan.own[0].selected);
|
||
}
|
||
|
||
#[test]
|
||
fn consolidating_keeps_subfolder_overrides_and_skips_unsaved_tabs() {
|
||
let mut s = state();
|
||
let root = with_collection(
|
||
&mut s,
|
||
&[
|
||
("a.http", "GET http://x/a\nAuthorization: Bearer root\n"),
|
||
("v2/b.http", "### B\nGET http://x/b\nAuthorization: Bearer root\n\n### C\nGET http://x/c\nAuthorization: Bearer v2\n"),
|
||
("v2/c.http", "GET http://x/d\nAuthorization: Bearer root\n"),
|
||
],
|
||
);
|
||
set_folder_auth(&mut s, root.clone(), FolderAuth::Header("Bearer root".into()));
|
||
set_folder_auth(&mut s, root.join("v2"), FolderAuth::Header("Bearer v2".into()));
|
||
update(
|
||
&mut s,
|
||
Action::OpenRequest {
|
||
file: root.join("v2/c.http"),
|
||
index: 0,
|
||
},
|
||
);
|
||
let id = active(&s);
|
||
update(&mut s, Action::UrlEdited(id, "http://x/edited".into()));
|
||
|
||
let plan = consolidate(&mut s, root.clone(), Some("Basic ignored"));
|
||
assert_eq!(plan.target, Some("Bearer root".into()), "the folder's own auth wins");
|
||
assert!(!plan.set_folder && plan.choices.is_empty());
|
||
let own: Vec<(&str, bool)> = plan
|
||
.own
|
||
.iter()
|
||
.map(|o| (o.request.label.as_str(), o.selected))
|
||
.collect();
|
||
// B would inherit v2's token, so removing its header isn't the default.
|
||
assert_eq!(
|
||
own,
|
||
vec![
|
||
("a.http › http://x/a", true),
|
||
("v2/b.http › B", false),
|
||
("v2/b.http › C", true)
|
||
]
|
||
);
|
||
assert_eq!(plan.skipped_dirty.len(), 1);
|
||
|
||
let w = writes(&update(&mut s, Action::ApplyConsolidateAuth(plan)));
|
||
let files: Vec<_> = w.iter().map(|(p, _)| p.clone()).collect();
|
||
assert_eq!(files, vec![root.join("a.http"), root.join("v2/b.http")]);
|
||
assert_eq!(
|
||
w[1].1,
|
||
"### B\nGET http://x/b\nAuthorization: Bearer root\n\n### C\nGET http://x/c\n"
|
||
);
|
||
assert!(s.tab(id).unwrap().is_dirty(), "the unsaved tab is left alone");
|
||
}
|