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

+36
View File
@@ -0,0 +1,36 @@
//! Every non-ASCII character in the UI code must be drawable with the
//! bundled fonts (a missing glyph panics in debug builds).
#[test]
fn ui_symbols_exist_in_the_bundled_fonts() {
let mut harness = egui_kittest::Harness::new_ui(|_ui| {});
harness.step();
let ctx = harness.ctx.clone();
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui");
let mut missing = Vec::new();
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
let src = std::fs::read_to_string(&path).unwrap();
for (n, line) in src.lines().enumerate() {
// Only string literals in code matter, not comments.
if line.trim_start().starts_with("//") {
continue;
}
for c in line.chars().filter(|c| !c.is_ascii()) {
for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
let ok = ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::new(14.0, family.clone()), c));
if !ok {
missing.push(format!(
"{c:?} (U+{:04X}) {family:?} at {}:{}",
c as u32,
path.display(),
n + 1
));
}
}
}
}
}
missing.dedup();
assert!(missing.is_empty(), "missing glyphs:\n{}", missing.join("\n"));
}
+148
View File
@@ -0,0 +1,148 @@
//! Renders the real UI to PNG files for a visual check. Needs a GPU (or a
//! software Vulkan driver), so it is ignored by default:
//!
//! REQLITE_RENDER_DIR=/tmp/shots cargo test -p reqlite-app --test render -- --ignored
use std::sync::Arc;
use std::time::{Duration, Instant};
use egui_kittest::Harness;
use reqlite_app::action::Action;
use reqlite_app::state::{RequestTab, ResponseTab};
use reqlite_app::ReqliteApp;
use reqlite_core::http::{BodyStore, HttpClient, HttpError, ResolvedRequest, Response, Timings};
use reqlite_core::CancelToken;
struct Canned;
impl HttpClient for Canned {
async fn send(&self, req: ResolvedRequest, _c: CancelToken) -> Result<Response, HttpError> {
let body = r#"{"id":42,"name":"Ada Lovelace","email":"ada@example.com","roles":["admin","author"],"active":true,"manager":null,"stats":{"posts":128,"score":9.75}}"#;
Ok(Response {
status: 200,
reason: "OK".into(),
http_version: "HTTP/2".into(),
headers: vec![
("content-type".into(), "application/json; charset=utf-8".into()),
("cache-control".into(), "no-store".into()),
("x-request-id".into(), "7f3a9c2e".into()),
],
size: body.len() as u64,
body: BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())),
timings: Timings {
dns: Duration::from_millis(4),
connect: Duration::from_millis(19),
tls: Duration::from_millis(48),
ttfb: Duration::from_millis(112),
total: Duration::from_millis(118),
},
effective_url: req.url,
})
}
}
fn shoot(h: &mut Harness<'_, ReqliteApp>, name: &str) {
let Ok(dir) = std::env::var("REQLITE_RENDER_DIR") else {
return;
};
std::fs::create_dir_all(&dir).unwrap();
for _ in 0..3 {
h.step();
}
let img = h.render().expect("render");
img.save(format!("{dir}/{name}.png")).unwrap();
}
fn wait(h: &mut Harness<'_, ReqliteApp>, done: impl Fn(&ReqliteApp) -> bool) {
let start = Instant::now();
while !done(h.state()) {
assert!(start.elapsed() < Duration::from_secs(5));
h.step();
std::thread::sleep(Duration::from_millis(10));
}
}
#[test]
#[ignore = "needs a GPU; run with --ignored"]
fn screenshots() {
let rt = tokio::runtime::Runtime::new().unwrap();
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::create_dir(root.join("orders")).unwrap();
std::fs::write(
root.join("users.http"),
"### List users\nGET {{base_url}}/users?limit=20&sort=name\nAccept: application/json\n\n### Create user\n# @name create-user\nPOST {{base_url}}/users\nContent-Type: application/json\nAuthorization: Bearer {{token}}\n\n{\n \"name\": \"Ada\",\n \"team\": \"{{team}}\"\n}\n\n### Delete user\nDELETE {{base_url}}/users/{{id}}\n",
)
.unwrap();
std::fs::write(
root.join("orders/orders.http"),
"### Get order\nGET {{base_url}}/orders/1\n",
)
.unwrap();
std::fs::write(
root.join("http-client.env.json"),
r#"{"dev": {"base_url": "http://localhost:8080", "team": "core"}, "prod": {"base_url": "https://api.example.com"}}"#,
)
.unwrap();
std::fs::write(
root.join("http-client.private.env.json"),
r#"{"dev": {"token": "dev-secret"}}"#,
)
.unwrap();
let app = ReqliteApp::new(None, rt.handle().clone(), Arc::new(Canned), None);
let mut h = Harness::builder()
.with_size(egui::vec2(1280.0, 800.0))
.wgpu()
.build_ui_state(
|ui, app: &mut ReqliteApp| {
egui_extras::install_image_loaders(ui.ctx());
app.frame(ui)
},
app,
);
shoot(&mut h, "01-welcome");
h.state_mut().dispatch(Action::OpenCollection(root.clone()));
wait(&mut h, |a| {
a.state.collection.as_ref().is_some_and(|c| !c.envs.names().is_empty())
});
h.state_mut().dispatch(Action::SelectEnv(Some("dev".into())));
h.state_mut().dispatch(Action::OpenRequest {
file: root.join("users.http"),
index: 1,
});
let id = h.state().state.active.unwrap();
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Body));
shoot(&mut h, "02-collection-body-tab");
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Headers));
h.state_mut().dispatch(Action::Send(id));
wait(&mut h, |a| {
a.state
.active_tab()
.and_then(|t| t.response.as_ref())
.is_some_and(|r| r.prepared.is_some())
});
shoot(&mut h, "03-json-response");
h.state_mut().dispatch(Action::SearchOpen(id, true));
h.state_mut().dispatch(Action::SearchQuery(id, "a".into()));
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Source));
shoot(&mut h, "04-source-and-search");
h.state_mut().dispatch(Action::SetResponseTab(id, ResponseTab::Timings));
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Auth));
shoot(&mut h, "05-auth-and-timings");
h.state_mut().dispatch(Action::OpenEnvEditor);
shoot(&mut h, "06-env-editor");
h.state_mut().dispatch(Action::EnvEditorClose);
let mut s = h.state().state.settings.clone();
s.theme = reqlite_app::settings::ThemeChoice::Light;
h.state_mut().dispatch(Action::SettingsChanged(s));
h.state_mut().dispatch(Action::SetResponseTab(id, ResponseTab::Body));
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Params));
shoot(&mut h, "07-light-theme");
}
+163
View File
@@ -0,0 +1,163 @@
//! UI smoke tests with egui_kittest and a fake async HttpClient.
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use egui_kittest::kittest::Queryable;
use egui_kittest::Harness;
use reqlite_app::action::Action;
use reqlite_app::ReqliteApp;
use reqlite_core::http::{BodyStore, HttpClient, HttpError, ResolvedRequest, Response, Timings};
use reqlite_core::CancelToken;
/// Answers every request with a small JSON body after a short delay.
#[derive(Default)]
struct FakeClient {
seen: Mutex<Vec<ResolvedRequest>>,
}
impl HttpClient for FakeClient {
fn send(
&self,
req: ResolvedRequest,
cancel: CancelToken,
) -> impl std::future::Future<Output = Result<Response, HttpError>> + Send {
self.seen.lock().unwrap().push(req.clone());
async move {
tokio::select! {
_ = tokio::time::sleep(Duration::from_millis(30)) => {}
_ = cancel.cancelled() => return Err(HttpError::Cancelled),
}
let body = format!("{{\"echo\": \"{}\", \"items\": [1, 2, 3]}}", req.url);
Ok(Response {
status: 200,
reason: "OK".into(),
http_version: "HTTP/1.1".into(),
headers: vec![("content-type".into(), "application/json".into())],
size: body.len() as u64,
body: BodyStore::InMemory(Arc::new(body.into_bytes())),
timings: Timings {
total: Duration::from_millis(30),
..Default::default()
},
effective_url: req.url,
})
}
}
}
fn harness(rt: &tokio::runtime::Runtime, client: Arc<FakeClient>) -> Harness<'static, ReqliteApp> {
let app = ReqliteApp::new(None, rt.handle().clone(), client, None);
Harness::builder()
.with_size(egui::vec2(1100.0, 760.0))
.build_ui_state(|ui, app: &mut ReqliteApp| app.frame(ui), app)
}
/// Steps the UI until `done` holds (effects finish on other threads).
fn step_until(h: &mut Harness<'_, ReqliteApp>, what: &str, done: impl Fn(&Harness<'_, ReqliteApp>) -> bool) {
let start = Instant::now();
while !done(h) {
assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for {what}");
h.step();
std::thread::sleep(Duration::from_millis(10));
}
}
#[test]
fn send_a_request_and_see_the_response() {
let rt = tokio::runtime::Runtime::new().unwrap();
let client = Arc::new(FakeClient::default());
let mut h = harness(&rt, client.clone());
h.step();
// The welcome screen offers a new request.
h.get_by_label("New request (Ctrl+T)").click();
h.step();
let id = h.state().state.active.expect("a tab");
h.state_mut()
.dispatch(Action::UrlEdited(id, "http://example.test/items?limit=3".into()));
h.step();
// The URL query shows up in the Params tab.
assert!(h.query_by_label("Params (1)").is_some());
h.get_by_label("Send").click();
step_until(&mut h, "the response", |h| {
h.query_by_label_contains("200 OK").is_some()
});
step_until(&mut h, "the prepared body", |h| {
h.state()
.state
.active_tab()
.unwrap()
.response
.as_ref()
.unwrap()
.prepared
.is_some()
});
h.step();
assert!(h.query_by_label_contains("\"items\"").is_some(), "pretty JSON is shown");
assert_eq!(client.seen.lock().unwrap()[0].url, "http://example.test/items?limit=3");
// Headers and Timings tabs render.
h.get_by_label("Headers (1)").click();
h.step();
h.step();
assert!(h.query_by_label("content-type").is_some());
h.get_by_label("Timings").click();
h.step();
h.step();
assert!(h.query_by_label("Total").is_some());
}
#[test]
fn keyboard_shortcuts_open_and_close_tabs() {
let rt = tokio::runtime::Runtime::new().unwrap();
let mut h = harness(&rt, Arc::new(FakeClient::default()));
h.step();
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T);
h.step();
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T);
h.step();
assert_eq!(h.state().state.tabs.len(), 2);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::W);
h.step();
assert_eq!(h.state().state.tabs.len(), 1);
}
#[test]
fn opens_a_collection_and_shows_its_requests() {
let rt = tokio::runtime::Runtime::new().unwrap();
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("users.http"),
"### List users\nGET {{base}}/users\n\n### Create user\nPOST {{base}}/users\n",
)
.unwrap();
std::fs::write(
dir.path().join("http-client.env.json"),
r#"{"dev": {"base": "http://dev"}}"#,
)
.unwrap();
let client = Arc::new(FakeClient::default());
let mut h = harness(&rt, client.clone());
h.state_mut().dispatch(Action::OpenCollection(dir.path().to_path_buf()));
step_until(&mut h, "the collection", |h| {
h.state()
.state
.collection
.as_ref()
.is_some_and(|c| !c.envs.names().is_empty())
});
h.step();
h.get_by_label_contains("Create user").click();
h.step();
assert_eq!(h.state().state.active_tab().unwrap().title(), "Create user");
h.state_mut().dispatch(Action::SelectEnv(Some("dev".into())));
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Enter);
step_until(&mut h, "the response", |h| {
h.query_by_label_contains("200 OK").is_some()
});
assert_eq!(client.seen.lock().unwrap()[0].url, "http://dev/users");
}
+78
View File
@@ -0,0 +1,78 @@
//! The file watcher reports external edits to .http files.
use std::sync::Arc;
use std::time::Duration;
use reqlite_app::action::Action;
use reqlite_app::effects::{Effect, Runner};
use reqlite_core::http::{HttpClient, HttpError, ResolvedRequest, Response};
use reqlite_core::CancelToken;
struct NoClient;
impl HttpClient for NoClient {
async fn send(&self, _r: ResolvedRequest, _c: CancelToken) -> Result<Response, HttpError> {
Err(HttpError::Other("unused".into()))
}
}
#[test]
fn reports_changes_to_http_and_env_files() {
let rt = tokio::runtime::Runtime::new().unwrap();
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::write(root.join("a.http"), "GET /a\n").unwrap();
let (runner, mut rx) = Runner::new(rt.handle().clone(), None, Arc::new(NoClient), None, 4);
runner.run(Effect::Watch(Some(root.clone())));
std::thread::sleep(Duration::from_millis(200));
std::fs::write(root.join("a.http"), "GET /changed\n").unwrap();
std::fs::write(root.join("ignored.txt"), "x").unwrap();
std::fs::create_dir(root.join("sub")).unwrap();
std::fs::write(root.join("sub/new.http"), "GET /new\n").unwrap();
std::fs::write(root.join("http-client.env.json"), "{}").unwrap();
let mut seen = std::collections::HashMap::new();
let mut rescan = false;
rt.block_on(async {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while seen.len() < 2 || !rescan {
match tokio::time::timeout_at(deadline, rx.recv()).await {
Ok(Some(Action::FileChangedOnDisk { path, text })) => {
seen.insert(path, text);
}
Ok(Some(Action::Rescan)) => rescan = true,
Ok(Some(_)) => {}
_ => break,
}
}
});
assert_eq!(
seen.get(&root.join("a.http")),
Some(&Some("GET /changed\n".to_string()))
);
// A new folder triggers a rescan (its files may race the new watch).
assert!(rescan);
assert!(seen.contains_key(&root.join("http-client.env.json")));
assert!(!seen.contains_key(&root.join("ignored.txt")));
std::fs::remove_file(root.join("a.http")).unwrap();
let deleted = rt.block_on(async {
loop {
match tokio::time::timeout(Duration::from_secs(5), rx.recv()).await {
Ok(Some(Action::FileChangedOnDisk { path, text })) if path == root.join("a.http") => break text,
Ok(Some(_)) => {}
_ => panic!("no delete event"),
}
}
});
assert_eq!(deleted, None);
// Stopping the watch stops the events.
runner.run(Effect::Watch(None));
std::thread::sleep(Duration::from_millis(100));
while rx.try_recv().is_ok() {}
std::fs::write(root.join("b.http"), "GET /b\n").unwrap();
std::thread::sleep(Duration::from_millis(400));
assert!(rx.try_recv().is_err());
}