Testing without a window
With the testing feature, FakeOs stands in for the system, so cargo test calls the handlers and clicks through the pages without a window.
A fake system for the handlers
hypersig_desktop::testing exists only with the testing feature. Turn it on under [dev-dependencies], as examples/notes does, so that cargo test builds it and the application's own build does not:
[dependencies]
hypersig_desktop = "0.18"
[dev-dependencies]
hypersig_desktop = { version = "0.18", features = ["testing"] }impl FakeOs {
pub fn new() -> Self;
pub fn os(&self) -> Os;
}FakeOs::new makes a fake system with no answers, no clipboard text, and no windows. os() returns an Os to put in the router's state where App::run would give the real one, so the handlers are the same functions in the application and in the test. Every Os from one FakeOs, and every clone of either, shares the same answers and records. Nothing on screen changes: no dialog, window, or browser opens, and the system clipboard is left alone.
Answering the dialogs
impl FakeOs {
pub fn answer_dialog(&self, paths: impl IntoIterator<Item = PathBuf>);
pub fn cancel_dialog(&self);
pub fn dialogs(&self) -> Vec<ShownDialog>;
}A test gives the answers before the handler shows its dialogs. answer_dialog answers the next dialog as if the person chose paths, and cancel_dialog as if they cancelled it. The dialogs take the answers in the order they were given, whichever of the four methods shows them:
| Method | After answer_dialog(paths) | After cancel_dialog() |
|---|---|---|
open_file | The one path of paths | None |
open_files | All of paths, which may be none | None |
pick_folder | The one path of paths | None |
save_file | The one path of paths | None |
Two mistakes in the answers panic, so the test fails where the mistake is. A dialog shown with no answer left panics with a message that names it by its number, as in dialog 1 was shown, and the test gave FakeOs no answer for it with answer_dialog or cancel_dialog. A dialog other than open_files answered with no path or with several panics too, since the person chooses exactly one there:
let fake = FakeOs::new();
let os = fake.os();
// No `answer_dialog` or `cancel_dialog` came first, so this panics.
let _ = os.dialog().open_file().await;dialogs returns a ShownDialog for each dialog the handlers showed and the test answered, in order. Its kind is the method that showed it, as a DialogKind, and its title, filters, directory, and file_name are what the handler gave, so a test can check that a handler asked for .md files or proposed a file name. An empty Vec means the handler showed none:
let fake = FakeOs::new();
let os = fake.os();
fake.answer_dialog([PathBuf::from("/notes/today.md")]);
// The handler's code: a dialog that saves a Markdown file.
let path = os.dialog().filter("Markdown", &["md"]).file_name("today.md").save_file().await;
assert_eq!(path, Some(PathBuf::from("/notes/today.md")));
let [shown] = &fake.dialogs()[..] else { panic!("one dialog was shown") };
assert_eq!(shown.kind, DialogKind::SaveFile);
assert_eq!(shown.filters, [("Markdown".to_owned(), vec!["md".to_owned()])]);
assert_eq!(shown.file_name.as_deref(), Some("today.md"));Reading what the handlers did
impl FakeOs {
pub fn clipboard_text(&self) -> Option<String>;
pub fn set_clipboard_text(&self, text: impl Into<String>);
pub fn open_windows(&self) -> Vec<Url>;
pub fn focused_window(&self) -> Option<Url>;
pub fn opened_externally(&self) -> Vec<SafeUrl>;
pub fn updater(&self) -> Updater;
}| Method | What it gives or does |
|---|---|
clipboard_text | The text on the fake clipboard: the last write_text, or None before any |
set_clipboard_text | Puts text on the fake clipboard, as another program would, for read_text to return |
open_windows | The Url of each window Windows::open opened and Window::close has not closed, in the order they opened |
focused_window | The Url of the window Windows::open opened or Window::focus focused last, or None once it is closed, as a system window comes to the front when it is shown |
opened_externally | Each SafeUrl passed to Os::open_external, in order. A URL without a scheme still fails with ErrorKind::NotExternal and is not listed |
With the updater feature as well, FakeOs::updater returns an Updater for the handlers' state whose check returns Ok(None): it finds no newer version and makes no request. The test below goes through each of these:
let fake = FakeOs::new();
let os = fake.os();
let window = os.windows().open(&NOTE.url(7)).await?;
assert_eq!(fake.open_windows(), [NOTE.url(7)]);
assert_eq!(fake.focused_window(), Some(NOTE.url(7)));
window.close()?;
assert_eq!(fake.open_windows(), []);
fake.set_clipboard_text("from another program");
assert_eq!(os.clipboard().read_text().await?.as_deref(), Some("from another program"));
os.open_external(&SOURCE)?;
assert_eq!(fake.opened_externally(), [SOURCE]);
// With the `updater` feature: the fake updater finds no newer version.
assert!(fake.updater().check().await?.is_none());Clicking through a page
The handlers take the fake Os from the state, and the framework's page testing does the rest. Page::simulate starts the page from its initial values, a click returns Effects whose calls lists the arguments of each action it sent, and Simulation::apply applies the Patches the handler returned, as the page would apply its reply. The test below drives the viewer of File dialogs: the page with its button marked by a NodeRef, and the open handler unchanged.
hypersig::node_ref!(const OPEN_BUTTON: NodeRef<Viewer>);
async fn index(_: AppState, (): ()) -> Page<Viewer> {
let initial = Viewer { text: String::new(), status: String::new() };
Page::new("Viewer", initial).child(
div()
.child(button().node_ref(OPEN_BUTTON).on_click(OPEN.call()).text("Open…"))
.child(p().bind_text(Viewer::status()))
.child(pre().bind_text(Viewer::text())),
)
}
// The body of a `#[tokio::test] async fn`, with `note` a file the test wrote.
let fake = FakeOs::new();
fake.answer_dialog([note.clone()]);
let state = AppState { os: fake.os() };
let page = index(state.clone(), ()).await;
let mut browser = page.simulate();
let effects = browser.click(OPEN_BUTTON);
assert_eq!(effects.calls(&OPEN), [()]);
browser.apply(open(state.clone(), ()).await);
assert_eq!(browser.value_of(Viewer::text()), "# Today\n");
// A second click, and the person cancels: the text stays.
fake.cancel_dialog();
browser.click(OPEN_BUTTON);
browser.apply(open(state, ()).await);
assert_eq!(browser.value_of(Viewer::text()), "# Today\n");
assert_eq!(fake.dialogs().len(), 2);In a test file, the body sits in a #[tokio::test] async fn, since the handlers are async. examples/notes tests its handlers this way: opening a file in a window of its own, a cancelled dialog, a save that reaches the list window over a stream, Save as, and Copy.
What the fake does not check
- One queue of answers serves the four dialog methods, so an answer is not tied to a kind of dialog. A test checks the kind afterwards with
dialogs. - Which window is in front once the focused one closes. The system brings another forward, and
focused_windowreturnsNone. - The window, the web view, and the HTTP between them are not involved. Smoke runs in CI start the real window for that.
Next
- Testing handlers: calling a handler and the router from a test.
- Testing a page without a browser: every event and read of
Page::simulate. - Smoke runs in CI: the real window, started by CI.