//! 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>, } impl HttpClient for FakeClient { fn send( &self, req: ResolvedRequest, cancel: CancelToken, ) -> impl std::future::Future> + 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) -> 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); // Ctrl+Shift+W closes them all (and is not taken as Ctrl+W). for _ in 0..3 { h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T); h.step(); } assert_eq!(h.state().state.tabs.len(), 4); h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::W); h.step(); assert!(h.state().state.tabs.is_empty()); } #[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 .collections .first() .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"); }