diff --git a/.claude/skills/add-feature/SKILL.md b/.claude/skills/add-feature/SKILL.md index d8fa9f96c..56158e060 100644 --- a/.claude/skills/add-feature/SKILL.md +++ b/.claude/skills/add-feature/SKILL.md @@ -12,6 +12,6 @@ description: Use when adding or changing a DevNotes feature end to end (core ser 5. The screen: run `egui-ui`. State in `AppState`, actions applied in `apply`, keys through `keys::dispatch`, widgets from `widgets/`, colours and gaps from `theme::tokens`, every string a key in both locales. 6. Something asked of the OS (a dialog, the clipboard, the tray)? Run `platform-integration`. 7. Sealed data (titles, bodies, names, attachments) touched? Run `devnotes-security-review`. -8. Tests with the code: Rust inline or `crates/engine/tests/`; kittest over a real core (`testing::backend`/`unlocked`); an e2e scenario if a user journey changes (`desktop-e2e-testing`). +8. Tests with the code: Rust inline or `crates/engine/tests/`; kittest over a real core (`testing::backend`/`unlocked`); a step of an e2e journey if a nominal path changes (`desktop-e2e-testing`). 9. Update `docs/architecture.md` and, only if a new trap exists, one line of `CLAUDE.md`. What the user sees: `docs/content/fr` and `docs/content/en` (`docs/content/README.md` says how), and, when they show the screen that changed, the README's GIFs (`docs/gifs/`, by `app::screens` then `--example tours`) and the site's scenes (`website/`, skill `marketing-site`). Publishing them is automatic. 10. Finish with `verify-change`, including a look at the window. Report what ran and what did not. diff --git a/.claude/skills/bug-investigation/SKILL.md b/.claude/skills/bug-investigation/SKILL.md index bdb7e1136..824d90647 100644 --- a/.claude/skills/bug-investigation/SKILL.md +++ b/.claude/skills/bug-investigation/SKILL.md @@ -5,7 +5,7 @@ description: Use when a DevNotes bug, crash, wrong result or flaky test must be # Bug investigation -1. Reproduce first, with the smallest input: a failing Rust test, a kittest test or an e2e scenario. No repro → say so and list what is missing. +1. Reproduce first, with the smallest input: a failing Rust test, a kittest test or a step of an e2e journey. No repro → say so and list what is missing. 2. Locate the owner: rules and data are the core (`crates/engine`), display is `crates/ui`. Check `CLAUDE.md` "Things that will bite you" for the matching trap before theorising (the db queue and the lock, `updated_at`, previews vs full body, `Engine::write` and the index, state vs view, the keyboard order, `LibraryCaches`, e2e waits). 3. State the root cause with evidence (file:line, log, failing assertion). Do not fix symptoms or add retries/sleeps. 4. Smallest fix at the owning layer; no unrelated refactors or dependency bumps. diff --git a/.claude/skills/desktop-e2e-testing/SKILL.md b/.claude/skills/desktop-e2e-testing/SKILL.md index b022b6af8..980c3f78e 100644 --- a/.claude/skills/desktop-e2e-testing/SKILL.md +++ b/.claude/skills/desktop-e2e-testing/SKILL.md @@ -1,16 +1,19 @@ --- name: desktop-e2e-testing -description: Use when writing, running or debugging an end-to-end scenario of the assembled egui app (e2e/, driven through egui_inspection). Not for screen or widget tests (kittest, egui-ui), nor the website. +description: Use when writing, running or debugging an end-to-end journey of the assembled egui app (e2e/, driven through egui_inspection). Not for screen or widget tests (kittest, egui-ui), nor the website. --- # Desktop e2e -- Build the flavour first, every time `crates/` changed: `cargo build -p app --features e2e --target-dir target/e2e` (its own target directory: no other build overwrites it). Then `cargo test -p e2e --test NN_name` for one scenario, `cargo test -p e2e` for all of them, one file after the other — what CI runs on each OS, from the start of the run. `cargo test --workspace` runs with `--exclude e2e`. -- A scenario is `e2e/tests/NN_name.rs`, one `#[test]` of named `step`s. It launches its own application on its own `tempfile` profile, seeds its own state, and must pass alone. There are no groups to keep (D31): a new file is picked up by its name. -- Drive it through `e2e::App`: `wait_for`, `has`, `click`, `fill`, `type_text`, `press` (a physical key: the area keys read the position), `eventually`, `capture`, `relaunch` (a real restart through `--action quit`), `quit`. Add a method there before reaching for the protocol in a scenario. -- Wait on conditions (`eventually`), never a duration: `std::thread::sleep` is refused by `e2e/clippy.toml`; the one exception, asserting that **nothing** happens, carries an `#[expect]` saying so. `Settle` waits for egui, not for the core: its answer comes frames later, which is why `eventually` reads again. -- Address controls by `author_id` (the old `data-testid` names), never by text: the language is the machine's. Missing one? Give the widget its id through `widgets::address` / `widgets::interact`. -- What the protocol cannot reach goes through the flavour's two doors: a global action is `--action ` from a second launch; a file dialog answers `DEVNOTES_E2E_DIALOG` (`platform::dialog::from_scenario`). A file dropped from the explorer is not injectable: go through « Joindre ». -- A failure leaves `failure.png` and the application's log in `target/e2e/scenarios//`: read them before changing the scenario, and decide whether the app or the test is wrong. CI uploads the same folder per platform. -- Never point a scenario at a real profile: `--profile` is always a temporary directory. The inspection port has no authentication; the flavour never becomes a release. +`CONTRIBUTING.md` → "The end-to-end journeys" says how to run, watch, mend and extend them; `docs/architecture.md` → "The journeys, on the assembled window" lists the thirteen and what the driver does. What is worth knowing before touching one: + +- Build the flavour first, every time `crates/` changed: `cargo build -p app --features e2e --target-dir target/e2e` (its own target directory: no other build overwrites it). Then `cargo test -p e2e --test NN_name` for one journey, `cargo test -p e2e` for all — what CI runs on each OS. `cargo test --workspace` runs with `--exclude e2e`. +- A journey is `e2e/tests/NN_name.rs`: one `#[test]` of named `step`s, what the person does then what they see. A nominal path goes into the journey it belongs to, as a step; a new file only for a new goal (15 at most). Branches, edge cases and error codes are unit tests'. +- It is written on the SDK (`e2e/src/sdk/`, one file per area) alone: no `author_id`, coordinate or duration. An act it lacks is a method of its area, with a line of doc; an expectation carries the sentence of what the person would see. +- Inside the SDK: `expect` (reads the tree until it holds), `click`, `fill`, `fill_nth` and `replace` (wait for the keyboard), `click_until` (a click the screen can lose), `place` (waits for a control to hold still), `reach` and `scroll_to`. Wait on what the act changes, not on what was already there: the last answer, a toast, a row of the same name. `std::thread::sleep` is refused by `e2e/clippy.toml`. +- Controls are addressed by `author_id`, never by a translated text: the language is the machine's (CI runs in English). A journey that must read a word chooses its language first (`prefs().choose_language`). Missing an id? Give the widget one through `widgets::address` / `widgets::interact`. +- The window is 1440 × 900 at most (`window().widen()`), 1280 wide under CI's Xvfb, 1024 × 768 on Windows after a full screen: call `widen()` again after a presentation, and click what is in view. +- What the protocol cannot reach goes through the flavour's doors: a global action is `--action ` from a second launch; a file dialog answers the path `files().answer` wrote; updates come from `App::open_before_an_update`'s server. A file dropped from the explorer is not injectable: go through *Attach*. +- A failure leaves `failure.png` and the application's log in `target/e2e/scenarios//`: read them before changing the step, and decide whether the application or the journey is wrong. CI uploads the same folder per platform. +- Never point a journey at a real profile. The inspection port has no authentication; the flavour never becomes a release. - Lint: `cargo clippy --workspace --all-targets --all-features -- -D warnings`. diff --git a/.claude/skills/verify-change/SKILL.md b/.claude/skills/verify-change/SKILL.md index 2521980e1..d1300b06f 100644 --- a/.claude/skills/verify-change/SKILL.md +++ b/.claude/skills/verify-change/SKILL.md @@ -14,7 +14,7 @@ Run from the repo root; pick by what changed, and report only what actually ran. | `scripts/**`, `.github/**` | `node --test "scripts/*.test.mjs"` | | `docs/content/**` | `npm run docs` from `website/`, `cargo test -p engine docs`, `cargo test -p ui docs_quotes` | | `website/**` | from `website/`: `npm run lint`, `npm run test:scripts`, `npm test`, `npm run build`, and a look at the built page | -| A user journey, anything the assembled app does | `cargo build -p app --features e2e --target-dir target/e2e`, then `cargo test -p e2e` (or `--test NN_name` for the scenario it touches) (`desktop-e2e-testing`) | +| A user journey, anything the assembled app does | `cargo build -p app --features e2e --target-dir target/e2e`, then `cargo test -p e2e` (or `--test NN_name` for the journey it touches) (`desktop-e2e-testing`) | | Anything visible | `cargo run -p app -- --profile ` and a screenshot, both themes; or the kittest captures: `DEVNOTES_CAPTURES= cargo test -p ui app::captures` | | Dependencies | `dependency-audit`; the licence must be in `deny.toml` | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 179f24486..95980c8ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -322,7 +322,7 @@ jobs: save-if: 'true' # The capture needs a rendered window, which xvfb gives; maximising one is a window - # manager's answer (`44_window_controls`), which openbox gives. + # manager's answer (journey 13), which openbox gives. - name: X server if: runner.os == 'Linux' run: sudo apt-get install -y --no-install-recommends xvfb openbox diff --git a/CLAUDE.md b/CLAUDE.md index 713c4908d..ba8ee6f11 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -23,7 +23,7 @@ Principles: - Cargo workspace: `cargo check|build|test --workspace`, `cargo clippy --workspace --all-targets --all-features -- -D warnings` (⚠️ `--all-features` is what compiles the `e2e` flavour), `cargo fmt --all --check`, `cargo bench -p engine` (not in CI; `autobenches = false` is load-bearing; → "Benchmarks"). Every external dependency is declared once, in the root `[workspace.dependencies]`; a crate takes it with `dep.workspace = true` and adds only its own features (D33). Toolchain pinned in `rust-toolchain.toml`; `unsafe_code` forbidden in every crate (D7), `clippy::pedantic` denied. - No Node project at the root: the release scripts have no dependency. `node --test "scripts/*.test.mjs"` · `cargo run -p app --example icons` (writes `crates/app/icons/`; ⚠️ small `.ico` sizes come from `icons/source/`) · `node scripts/prettier.mjs` (copies the Prettier it pins into `crates/text/prettier/`, the formatter compiled in). Markdown, JSON and YAML have no formatter. The request-script libraries are bundled by `crates/engine/sandbox/build.mjs`, from that folder's own `package.json`. - Website (`website/`, Angular, devnotes.fr; its own `package.json`, outside the Cargo workspace): from `website/`, `npm ci` · `npm start` (port 4300) · `npm run build` (fetches the latest release, prerenders to `website/dist/`, checks every page and its download links) · `npm test` · `npm run lint` · `npm run test:scripts`. `website.yml` publishes it when `website/` or `docs/content/` changes on `main`, and after each release. → "The website". -- E2E: `cargo build -p app --features e2e --target-dir target/e2e`, then `cargo test -p e2e` (the driver is `e2e/` at the root; all scenarios, one after the other; `--test 01_first_launch` for one; `cargo test --workspace --exclude e2e` otherwise). `01`–`35` are the WebdriverIO scenarios ported, the rest are this application's own. → "The scenarios, on the assembled window". +- E2E: `cargo build -p app --features e2e --target-dir target/e2e`, then `cargo test -p e2e` (thirteen journeys in `e2e/tests/`, one after the other; `--test 01_first_day` for one; `cargo test --workspace --exclude e2e` otherwise). A journey is written on the SDK (`e2e/src/sdk/`) alone, with no `author_id`, coordinate or duration of its own (`CONTRIBUTING.md`). → "The journeys, on the assembled window". - Release is a `workflow_dispatch` after a version bump; the version is `[workspace.package] version` in `Cargo.toml` alone (D27), so a bump touches `Cargo.toml` and `Cargo.lock` (`cargo update --workspace`); `scripts/version.mjs` refuses a release where they disagree. `release.yml` runs `prepare` (checks, changelog written, nothing pushed) → `package` (`package.yml`: a job a system, one action a format under `.github/actions/package/`, signed and checked) → `finalize` (commit, tag, atomic push, release page): ⚠️ the irreversible last, so a failed release leaves nothing to undo. `packages.yml` calls `package.yml` on pull requests, then installs and updates. ⚠️ A version branch (`dev/x.y.z`) reaches `main` by a merge commit, never a squash: the release notes read what the merge brings. → "Releasing", `docs/releasing.md`. ## Things that will bite you @@ -96,13 +96,13 @@ Read at the `angular-reference` tag; the egui mechanism is in `docs/architecture ### Tests - State is tested against the real core on a temporary library; only the platform (dialogs, window, clipboard, notifications, clock) is faked, and no fake reimplements a core rule. → "Testing". -- ⚠️ An e2e scenario runs alone on a virgin profile, seeds its own state, waits on conditions (`eventually`), never durations, and addresses controls by `author_id` (the old `data-testid` names). → "One application per run, one run per scenario". +- ⚠️ An e2e journey runs alone on a virgin profile and acts through the SDK, which waits on conditions, never durations, and addresses controls by `author_id` (the old `data-testid` names). → "The journeys, on the assembled window". ## Tickets and pull requests - **A pull request's title is its changelog entry** (`scripts/release-notes.mjs`), and a ticket's title is where it comes from: both say **what changes, factually and briefly** — `: `, the area in one or two words (a head of three words or more before `: ` is all the notes keep; ⚠️ never a commit kind — `CI`, `Docs`, `Test`, `Build`, `Fix`, `Security`… is read as a prefix and dropped), then the control, the action, the result; ≤ 70 characters. No figure of speech, no implementation detail, no « of our own ». ✗ « Search the code through a bar of our own » → ✓ « Code editor: new find-and-replace bar with match count and options ». - **A ticket wears one section label**: `enhancement`, `change`, `bug` or `removal` for what someone using the application sees (the update prompt shows them), `security`, `documentation` for the guides and the README, `website` for the site and its pages (both on the release page alone, never in the application), or `refactor`/`test` for the rest, a fix to the CI or the tests included; a pull request that closes no ticket wears it itself. ⚠️ Without one, the release notes file it under « Under the hood » without a word. -- **A ticket's body opens on its context, then its change**: `**Context** —` what the application does today and where it was seen or who asked; `**Change** —` what will be different, in a sentence or two; then `**To do**` and `**Tests**` (naming the e2e scenario). A milestone's description lists what it changes, plainly. +- **A ticket's body opens on its context, then its change**: `**Context** —` what the application does today and where it was seen or who asked; `**Change** —` what will be different, in a sentence or two; then `**To do**` and `**Tests**` (naming the e2e journey and its step). A milestone's description lists what it changes, plainly. - **No other software in a title, a description or a milestone**, unless the feature reads, writes or plugs into it (an import format, an extension's host): never a comparison with another product. ## Security and verification @@ -113,4 +113,4 @@ Read at the `angular-reference` tag; the egui mechanism is in `docs/architecture ## Claude Code setup -- `.claude/skills/` is versioned. Local: `add-feature`, `egui-ui`, `platform-integration`, `database-migration`, `devnotes-security-review`, `verify-change`, `desktop-e2e-testing` (the `e2e/` driver), `backup-restore`, `bug-investigation`, `release-packaging`, `marketing-site`, `performance-profiling`, `dependency-audit`. Vendored, unmodified and pinned in `.claude/skills/PROVENANCE.md`: `frontend-design`, `webapp-testing` (`anthropics/skills`); `seo`, `core-web-vitals`, `accessibility` (`addyosmani/web-quality-skills`); `rust-guidelines` (`microsoft/rust-guidelines`, its `SKILL.md` ours). A vendored skill is generic: where it disagrees with this file or a local skill, the project wins. `frontend-design`, `webapp-testing`, `seo`, `core-web-vitals` and `accessibility` are for the website. `.claude/settings.json` holds the permission rules that back `.claude/rules/security.md`; `settings.local.json`, `launch.json` and `.mcp.json` stay local. +- `.claude/skills/` is versioned. Local: `add-feature`, `egui-ui`, `platform-integration`, `database-migration`, `devnotes-security-review`, `verify-change`, `desktop-e2e-testing` (the `e2e/` journeys and their SDK), `backup-restore`, `bug-investigation`, `release-packaging`, `marketing-site`, `performance-profiling`, `dependency-audit`. Vendored, unmodified and pinned in `.claude/skills/PROVENANCE.md`: `frontend-design`, `webapp-testing` (`anthropics/skills`); `seo`, `core-web-vitals`, `accessibility` (`addyosmani/web-quality-skills`); `rust-guidelines` (`microsoft/rust-guidelines`, its `SKILL.md` ours). A vendored skill is generic: where it disagrees with this file or a local skill, the project wins. `frontend-design`, `webapp-testing`, `seo`, `core-web-vitals` and `accessibility` are for the website. `.claude/settings.json` holds the permission rules that back `.claude/rules/security.md`; `settings.local.json`, `launch.json` and `.mcp.json` stay local. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 283247600..7d339129d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,6 +44,51 @@ cargo fmt --all --check && cargo clippy --workspace --all-targets --all-features `--all-features` is not optional: it is what compiles the `e2e` flavour, which nothing else type-checks. +## The end-to-end journeys + +A journey (`e2e/tests/`) is a person with a goal, walking the assembled application from one end to +the other: named steps, each opening on what they want and ending on what they see. The branches, +the edge cases and the error codes are the unit tests'. A journey is written on the SDK +(`e2e/src/sdk/`), the person's acts on the window, area by area: + +```rust +step("a wrong phrase is refused and says so", || { + app.gate().try_phrase("not the phrase"); + app.gate().expect_wrong_phrase("the gate says the phrase is wrong"); +}); +``` + +**Running them.** Build the flavour they drive first, every time `crates/` changed: + +```bash +cargo build -p app --features e2e --target-dir target/e2e +``` + +then the suite with `cargo test -p e2e`, or one journey with +`cargo test -p e2e --test 01_first_day`. Each runs on a profile of its own, gone at its end. The +window takes the keyboard: leave the machine alone meanwhile. + +**Watching one.** The window stays blank while a journey runs: a painted frame costs up to 300 ms on +the software renderer CI has, and what the SDK reads, the accessibility tree, is built without +painting. `DEVNOTES_E2E_PAINT_ALL=1` paints every frame, and `DEVNOTES_E2E_GPU=1` does it on the +machine's graphics card, which is smoother. + +**What it leaves.** Captures go to `target/e2e/scenarios//` (elsewhere with +`DEVNOTES_E2E_OUTPUT`), and a failed journey leaves there its last screen (`failure.png`), the +application's log and what it wrote in its terminal. CI keeps the same folder for each system. + +**When a change breaks a journey**, read the step that failed, then open its last screen and its log. +Run that journey alone and watch it. Then mend the application; or the step, if what the person does +or sees changed on purpose; or the SDK, if only a control's name or place did. A journey never waits +on a duration and is never run again until it passes. + +**Adding to the SDK.** A journey defines no act of its own: one it lacks is a method of the area it +belongs to, with a line of doc. An act is a verb (`create_library`), a read gives what the screen +shows, and `expect_…` waits until the screen shows it, its sentence being what a failure says. A +method acts through the window alone, waits for it before and after, and lets no `author_id`, +coordinate or duration out. A control without an `author_id` gets one through `widgets::interact`. +The catalogue is `cargo doc -p e2e --no-deps --open`. + ## The scripts | Command | What it does | @@ -71,7 +116,7 @@ crates/text/, richtext/, drawing/ The editing cores: code, Notes, drawings crates/platform/ What is asked of the operating system crates/i18n/ The interface's translations -e2e/ The end-to-end driver and its scenarios, on the assembled window +e2e/ The end-to-end suite: journeys on the assembled window, and their SDK golden/ Test data: exact outputs the tests compare with (its README says which) docs/ Architecture notes, the release procedure, the manual checklist, the README's GIFs docs/content/ The user documentation, in French and English: the site and the application diff --git a/crates/app/src/desktop.rs b/crates/app/src/desktop.rs index 4d31588c1..6d06f0f4f 100644 --- a/crates/app/src/desktop.rs +++ b/crates/app/src/desktop.rs @@ -8,7 +8,7 @@ use platform::autostart::Autostart; use platform::dialog::FileDialog; use platform::shortcuts::Shortcuts; use platform::tray::{NoTray, Picture, Tray}; -use platform::updater::Source; +use platform::updater::{Source, Updater}; use ui::{Inbox, Input, Preferences, Settings}; /// Who sends a toast on Windows. @@ -30,12 +30,23 @@ pub(crate) fn start(preferences: &Preferences, inbox: &Inbox) -> ui::Desktop { autostart: autostart(), notifier: platform::notify::system(METADATA.name, IDENTIFIER), dialog: dialog(inbox.clone()), - updater: platform::updater::system(&UPDATES), + updater: updater(), clipboard: platform::clipboard::system(), opener: platform::desktop::system(), } } +#[cfg(not(feature = "e2e"))] +fn updater() -> Arc { + platform::updater::system(&UPDATES) +} + +/// A scenario is asked by nobody but the server it serves itself. +#[cfg(feature = "e2e")] +fn updater() -> Arc { + platform::updater::from_scenario(&UPDATES) +} + fn dialog(inbox: Inbox) -> Arc { platform::dialog::system(move || inbox.post(Input::NoFileDialog)) } diff --git a/crates/platform/src/dialog.rs b/crates/platform/src/dialog.rs index 59c783540..70206f863 100644 --- a/crates/platform/src/dialog.rs +++ b/crates/platform/src/dialog.rs @@ -1,5 +1,5 @@ //! Choosing a file to read, or where to write one. An end-to-end scenario cannot reach the -//! system's dialog, so the `e2e` flavour answers the path the scenario fixed instead. +//! system's dialog, so the `e2e` flavour answers the path the scenario wrote down instead. mod system; @@ -21,8 +21,8 @@ pub trait FileDialog { /// `on_missing` hears a desktop with no dialog to show, which otherwise reads as a cancel. pub fn system(on_missing: impl Fn() + Send + Sync + 'static) -> Arc { #[cfg(feature = "e2e")] - if let Some(fixed) = from_scenario() { - return Arc::new(fixed); + if let Some(written) = from_scenario() { + return Arc::new(written); } system::system(on_missing) } @@ -49,7 +49,7 @@ impl FileDialog for NoDialog { } } -/// Answers one path to whatever is asked: a scenario's file, or a test's. +/// Answers one path to whatever is asked: a test's file. pub struct Fixed(pub PathBuf); impl FileDialog for Fixed { @@ -62,13 +62,30 @@ impl FileDialog for Fixed { } } -/// Where a scenario names the file every dialog answers. +/// Where a scenario names the file it writes a dialog's answer in: a path, and a cancel when it +/// holds none. pub const E2E_DIALOG: &str = "DEVNOTES_E2E_DIALOG"; -/// The `e2e` flavour's dialog, when the scenario fixed a path. +/// Answers the path written in a file, read again at each question. #[cfg(feature = "e2e")] -pub fn from_scenario() -> Option { - std::env::var_os(E2E_DIALOG).map(|path| Fixed(PathBuf::from(path))) +pub struct Written(PathBuf); + +#[cfg(feature = "e2e")] +impl FileDialog for Written { + fn open(&self) -> Option { + let path = std::fs::read_to_string(&self.0).ok()?; + (!path.is_empty()).then(|| PathBuf::from(path)) + } + + fn save(&self, _name: &str) -> Option { + self.open() + } +} + +/// The `e2e` flavour's dialog, when the scenario answers it. +#[cfg(feature = "e2e")] +pub fn from_scenario() -> Option { + std::env::var_os(E2E_DIALOG).map(|file| Written(PathBuf::from(file))) } #[cfg(test)] diff --git a/crates/platform/src/updater.rs b/crates/platform/src/updater.rs index 82506bb43..682cdfaad 100644 --- a/crates/platform/src/updater.rs +++ b/crates/platform/src/updater.rs @@ -2,12 +2,19 @@ //! then installed once the application has finished leaving (D26). Nothing installs //! without an explicit gesture, and deb and rpm packages do not update themselves. +#[cfg(feature = "e2e")] +mod scenario; mod system; #[cfg(test)] mod tests; +#[cfg(feature = "e2e")] +pub use scenario::system as from_scenario; pub use system::{Source, system}; +/// Where a scenario serves the `latest.json` the `e2e` flavour asks for. +pub const E2E_UPDATES: &str = "DEVNOTES_E2E_UPDATES"; + /// A version the updater found. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AvailableUpdate { diff --git a/crates/platform/src/updater/scenario.rs b/crates/platform/src/updater/scenario.rs new file mode 100644 index 000000000..9cae41c5c --- /dev/null +++ b/crates/platform/src/updater/scenario.rs @@ -0,0 +1,15 @@ +//! The `e2e` flavour's updater: the real one, on the server a scenario serves. ⚠️ Without one it +//! asks nobody: a published version would be offered in the middle of a scenario. + +use std::sync::Arc; + +use super::system::{Source, built}; +use super::{E2E_UPDATES, NoUpdater, Updater}; + +pub fn system(source: &Source<'_>) -> Arc { + let Ok(endpoint) = std::env::var(E2E_UPDATES) else { + return Arc::new(NoUpdater); + }; + let served = Source { endpoint: &endpoint, ..*source }; + built(&served, true).map_or_else(|| Arc::new(NoUpdater) as _, |updater| Arc::new(updater) as _) +} diff --git a/crates/platform/src/updater/system.rs b/crates/platform/src/updater/system.rs index 3026b2995..e2ee51180 100644 --- a/crates/platform/src/updater/system.rs +++ b/crates/platform/src/updater/system.rs @@ -12,6 +12,7 @@ use cargo_packager_updater::{Config, Error, Update, UpdaterBuilder}; use super::{AvailableUpdate, DownloadError, NoUpdater, Updater}; /// Where the releases are, and who signs them. +#[derive(Clone, Copy)] pub struct Source<'a> { /// The running version. pub version: &'a str, diff --git a/crates/ui/src/http/request/body.rs b/crates/ui/src/http/request/body.rs index 8dd58f6db..fbfe92a33 100644 --- a/crates/ui/src/http/request/body.rs +++ b/crates/ui/src/http/request/body.rs @@ -205,6 +205,17 @@ pub(super) fn invalid(problem: &JsonError, language: i18n::Language) -> String { ) } +/// A line drawn from its end, the height of its controls: on its own, a layout centres it in all +/// the height left. +fn from_its_end(ui: &mut Ui, content: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = gap::GROUPS; + content(ui); + }); + }); +} + /// Whether the JSON reads, and « Format » once there is something that does. fn status( ui: &mut Ui, @@ -216,8 +227,7 @@ fn status( let p = palette(ui.ctx()); let problem = said.and_then(|said| said.problem.as_ref()); let blank = text.trim().is_empty(); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = gap::GROUPS; + from_its_end(ui, |ui| { let format = i18n::translate(language, keys::http::body::FORMAT, &[]); if Button::new(&format, "http-body-format") .enabled(problem.is_none() && !blank) @@ -244,8 +254,7 @@ fn status( fn file(ui: &mut Ui, tab: &Tab, path: &str, language: i18n::Language, actions: &mut Actions) { let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.spacing_mut().item_spacing.x = gap::GROUPS; + from_its_end(ui, |ui| { if Button::new(&tr(keys::http::body::CHOOSE_FILE), "http-body-choose") .show(ui) .clicked() diff --git a/crates/ui/src/http/request/tests.rs b/crates/ui/src/http/request/tests.rs index 382f850dc..dfe222c39 100644 --- a/crates/ui/src/http/request/tests.rs +++ b/crates/ui/src/http/request/tests.rs @@ -134,6 +134,17 @@ fn a_body_is_a_file_by_its_path() { assert_eq!(said_by(&harness, "http-body-path").as_deref(), Some("facture.pdf")); } +#[test] +fn the_line_of_the_file_stands_right_under_the_kinds() { + let harness = body(FILE); + let place = |author_id| { + let node = harness.query_by(|node| node.author_id() == Some(author_id)); + node.expect("it is drawn").rect() + }; + let gap = place("http-body-choose").top() - place(FILE).bottom(); + assert!((0.0..40.0).contains(&gap), "{gap} points under them"); +} + fn parts_of(harness: &Harness<'_, Bench>) -> Vec<(String, String, bool)> { match body_of(harness) { RequestBody::Multipart { parts } => { diff --git a/crates/ui/src/palette/list_tests.rs b/crates/ui/src/palette/list_tests.rs index 97df8b713..94d2da3fe 100644 --- a/crates/ui/src/palette/list_tests.rs +++ b/crates/ui/src/palette/list_tests.rs @@ -178,7 +178,7 @@ fn ctrl_c_copies_the_note_in_hand_and_closes() { let mut harness = palette(); typed(&mut harness, "psql prod"); lists(&mut harness, "the note is found", |names| names.first().is_some_and(|name| name == "psql prod")); - harness.key_press_modifiers(Modifiers::COMMAND, Key::C); + harness.event(egui::Event::Copy); settle(&mut harness); until(&mut harness, "it is copied", |harness| harness.state().state.status.latest().is_some()); diff --git a/crates/ui/src/palette/mod.rs b/crates/ui/src/palette/mod.rs index 5c87f6db3..f8122297b 100644 --- a/crates/ui/src/palette/mod.rs +++ b/crates/ui/src/palette/mod.rs @@ -148,19 +148,26 @@ fn keyboard( ask(actions, Asked::Unchip(palette.chips().len() - 1)); } }); - // `Ctrl+C` and not a bare `c`, which the field types; a selection in the field keeps its own. + // ⚠️ The window delivers Ctrl+C as a copy, never as a key. A selection in the field keeps its own. let selecting = egui::TextEdit::load_state(ctx, field_id()) .and_then(|field| field.cursor.char_range()) .is_some_and(|range| !range.is_empty()); if let Some(Item::Note(note)) = current && note.kind != NoteKind::Drawing && !selecting - && ctx.input_mut(|input| input.consume_key(Modifiers::COMMAND, Key::C)) + && ctx.input_mut(take_copy) { ask(actions, Asked::Copy(note.id.clone())); } } +/// Whether a copy was asked this frame; the field does not hear it. +fn take_copy(input: &mut egui::InputState) -> bool { + let before = input.events.len(); + input.events.retain(|event| *event != egui::Event::Copy); + input.events.len() < before +} + fn panel( ui: &mut Ui, state: &AppState, diff --git a/crates/ui/src/state/board.rs b/crates/ui/src/state/board.rs index 96a1a8983..ab2190a72 100644 --- a/crates/ui/src/state/board.rs +++ b/crates/ui/src/state/board.rs @@ -303,6 +303,10 @@ impl BoardState { /// The board on screen put back in order, as far as `scope` allows. pub fn arrange(&mut self, backend: &Backend, place: &Place, scope: BoardScope, lines: PreviewLines) { + // What the hand moved is not lost with the staged places: the queue writes it first. + if self.staged.due.take().is_some() { + self.saving.push(save(backend, &self.staged)); + } let pending = api::board::arrange(backend, place.space_id.clone(), place.root_id.clone(), scope, lines); self.arranging = Some((place.root_id.clone(), pending)); @@ -514,6 +518,25 @@ mod tests { assert!(state.staged.frames.is_empty() && state.staged.places.is_empty()); } + #[test] + fn aligning_at_once_keeps_the_zone_the_hand_just_moved() { + let (backend, _profile, place, folder) = space_of_one_zone(); + let ctx = egui::Context::default(); + let mut errors = ErrorNotifier::default(); + let mut revision = Revision::default(); + let mut state = BoardState::default(); + read(&mut state, &backend, &place, revision); + let moved = BoardFrame { x: 400, y: 300, width: 300, height: 260 }; + + state.move_zone(&place, folder, moved, 0.0); + state.arrange(&backend, &place, BoardScope::LooseCards, PreviewLines::default()); + backend.settle(); + state.write(&ctx, &backend, &mut revision, &mut errors); + read(&mut state, &backend, &place, revision); + + assert_eq!(state.frame(&state.view().unwrap().zones[0]), moved); + } + #[test] fn an_arrangement_answers_what_it_replaced_and_pans_home() { let (backend, _profile, place, folder) = space_of_one_zone(); diff --git a/crates/ui/src/state/http/area_tests.rs b/crates/ui/src/state/http/area_tests.rs index 9d694a97e..5f2760b35 100644 --- a/crates/ui/src/state/http/area_tests.rs +++ b/crates/ui/src/state/http/area_tests.rs @@ -181,6 +181,17 @@ fn the_rows_typed_are_written_as_the_page_is_left() { assert_eq!(area.held.state.http.environments().globals()[0].value, "abc"); } +/// The rows of the next one take the place of what waits. +#[test] +fn the_rows_typed_are_written_before_an_environment_is_made() { + let mut area = area(); + area.ask(Http::ShowPage(Page::Environments)); + area.env(Env::Rows(vec![row("token", "abc")])); + area.env(Env::Create("Prod".to_owned())); + area.env(Env::Rows(vec![row("host", "x")])); + assert_eq!(area.held.state.http.environments().globals()[0].value, "abc"); +} + // Tabs /// The row it just got would be out of sight. diff --git a/crates/ui/src/state/http/environments.rs b/crates/ui/src/state/http/environments.rs index ffa484e52..0fcf2f2c8 100644 --- a/crates/ui/src/state/http/environments.rs +++ b/crates/ui/src/state/http/environments.rs @@ -166,6 +166,7 @@ impl Environments { self.target = target; } Asked::Create(name) => { + self.flush(backend); let write = api::http::create_environment(backend, name); self.writes.push(write); } diff --git a/crates/ui/src/widgets/badge.rs b/crates/ui/src/widgets/badge.rs index f60a27292..2c389dd64 100644 --- a/crates/ui/src/widgets/badge.rs +++ b/crates/ui/src/widgets/badge.rs @@ -107,11 +107,20 @@ pub fn hue_badge(ui: &mut Ui, label: &str, hue: Color32) -> Response { /// A key cap, as the shortcuts sheet and the search field's hint draw it. pub struct Kbd<'a>(pub &'a str); +/// Around a key's text. +const KBD_PADDING: Vec2 = Vec2::new(12.0, 2.0); + impl Kbd<'_> { + /// What `show` takes across. + pub fn width(&self, ui: &Ui) -> f32 { + let p = palette(ui.ctx()); + text(ui, self.0, font::CAPTION, 400.0, FontFamily::Monospace, p.text_1).size().x + KBD_PADDING.x + } + pub fn show(self, ui: &mut Ui) -> Response { let p = palette(ui.ctx()); let galley = text(ui, self.0, font::CAPTION, 400.0, FontFamily::Monospace, p.text_1); - let (rect, response) = ui.allocate_exact_size(galley.size() + Vec2::new(12.0, 2.0), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(galley.size() + KBD_PADDING, Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, self.0)); ui.painter().rect( rect, diff --git a/crates/ui/src/widgets/field.rs b/crates/ui/src/widgets/field.rs index 1478a0c54..97bb4f251 100644 --- a/crates/ui/src/widgets/field.rs +++ b/crates/ui/src/widgets/field.rs @@ -239,8 +239,7 @@ impl<'a> SearchField<'a> { let edge = if focused { p.amber_edge } else { p.line }; let width = self.width.unwrap_or_else(|| ui.available_width()); // The frame's margins, the magnifier and its gap. - let spaced = ui.spacing().item_spacing.x; - let around = 22.0 + 16.0 + spaced; + let around = 22.0 + 16.0 + gap::CONTROLS; if self.matched.is_none() && width - around - self.trailing_width(ui) < WORDS_KEEP { self.key = None; } @@ -291,17 +290,21 @@ impl<'a> SearchField<'a> { .inner } - /// Room for what follows the field: the cross, then the count or the key. + /// Room for what follows the field, each part after its gap: the cross, then the count or + /// the key, as they are drawn. fn trailing_width(&self, ui: &Ui) -> f32 { - let gap = ui.spacing().item_spacing.x; + let between = gap::CONTROLS; let cross = - if self.clear.is_some() && !self.value.is_empty() { super::MIN_TARGET + gap } else { 0.0 }; - let words = self.matched.or(self.key).unwrap_or_default(); - let family = if self.matched.is_some() { FontFamily::Proportional } else { FontFamily::Monospace }; - let after = if words.is_empty() { - 0.0 + if self.clear.is_some() && !self.value.is_empty() { super::MIN_TARGET + between } else { 0.0 }; + let after = if let Some(matched) = self.matched { + super::text(ui, matched, font::META, 400.0, FontFamily::Proportional, Color32::WHITE) + .size() + .x + + between + } else if let Some(key) = self.key { + super::Kbd(key).width(ui) + between } else { - super::text(ui, words, font::META, 400.0, family, Color32::WHITE).size().x + gap + gap + 0.0 }; cross + after } diff --git a/crates/ui/src/widgets/tests.rs b/crates/ui/src/widgets/tests.rs index ff2c88fec..f0e924eaf 100644 --- a/crates/ui/src/widgets/tests.rs +++ b/crates/ui/src/widgets/tests.rs @@ -294,3 +294,27 @@ fn an_empty_place_says_so_and_offers_its_actions() { assert_eq!(*harness.state(), Some(1)); } } + +/// The header reads what does not narrow off the width drawn: a search wider than asked would +/// hand it back the room it took, and the key would come and go at every frame. +#[test] +fn a_search_field_is_as_wide_as_asked_its_key_shown_or_not() { + let mut harness = crate::testing::harness().build_ui_state( + |ui, (searched, asked, drawn): &mut (String, f32, f32)| { + ui.vertical(|ui| { + SearchField::new(searched, "Rechercher", "search") + .key("Ctrl+K") + .width(*asked) + .show(ui); + *drawn = ui.min_rect().width(); + }); + }, + (String::new(), 200.0, 0.0), + ); + for asked in 200..=360 { + harness.state_mut().1 = f32::from(u16::try_from(asked).unwrap()); + harness.run(); + let (_, asked, drawn) = *harness.state(); + assert!((drawn - asked).abs() < 0.01, "asked {asked} px, drawn {drawn} px"); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 21d5d1517..9989abfbd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -47,7 +47,7 @@ crates/platform/ what is asked of the operating system: paths, window, instan shortcuts, clipboard, dialogs, notifications, autostart, updater crates/ui/ the egui interface: the frame, its state, its screens, its widgets crates/app/ the `devnotes` binary (main), its icons (`--example icons`) and packages -e2e/ the end-to-end driver and its scenarios, on the assembled window +e2e/ the end-to-end driver, its SDK and the journeys, on the assembled window golden/ test data: exact outputs the tests compare with (its README says which) ``` @@ -985,7 +985,7 @@ be corrected without a build; that is given up. 2. `ui/src/api/tools.rs`: one function through `backend.compute`. 3. `ui/src/tools/catalogue/.rs`: a struct implementing `Tool`, its `make()`; `catalogue.rs`: an entry and a `mod`. A reference is `Reference::of(table)` and a line of `REFERENCES`. -4. `tools..*` in both locales, its kittest over a real core, a step in scenario 29, and its +4. `tools..*` in both locales, its kittest over a real core, a row in journey 8's table, and its state in `app::captures` by itself: `the_tools` walks the catalogue. What every tool draws alike is the kit, `tools/ui/`: `columns`, `line`, `section_head`, `text_area`, @@ -1536,8 +1536,8 @@ way — the kind menu names it and offers nothing. and gives back the selection it was taken over, then drops the selection, then leaves), a history of the scene's states, and an export as PNG or SVG (`drawing::export`), written with `tools::write_file` where `FileDialog` says. ⚠️ `rfd`'s dialog blocks until answered, so the whole - export runs on `compute`, never on the window's thread. An e2e scenario answers it through - `DEVNOTES_E2E_DIALOG` (`App::launch_answering`). + export runs on `compute`, never on the window's thread. A journey answers it through + `DEVNOTES_E2E_DIALOG` (`Files::answer`). - **A Note embeds one by its id**: `![title](devnotes:drawing/)`, the Markdown image of TipTap's extension, drawn by a node view that asks `drawing_picture` (`rich-text-drawings.ts`); the Note's body carries no picture. Inserted from the toolbar's « Insérer un dessin », whose @@ -4857,7 +4857,7 @@ first, and a closed tab closes its socket. written at the end of the script, and for a request the order the scripts run in, a level above a click from its settings on the same script. The extractions stand among the scripts after the answer. What runs them is the application relaunched as their host: a kittest bench is not that -binary, so running them is scenario 34's. A script that stopped before the send stands in place +binary, so running them is journey 10's. A script that stopped before the send stands in place of the answer, read back from its error's params (`ScriptStop::of_params`); after it, above the answer that came. « Open the script » goes to the request's own, or to the settings of what holds it, on the phase, the line marked until the next edit (`HttpState::script_focus`). @@ -5565,8 +5565,8 @@ note can be created, and the next open seeds only where there is none. The trigg strip scrolls itself into view, because it replaces a trigger further down a panel that scrolls and would otherwise appear below the fold. -`23-backups.e2e.ts` goes through that gate for real: its final scenario replaces the library, -unlocks the copy, and finds neither a note written after the copy nor Preferences open. +Journey 12 goes through that gate for real: it replaces the library, unlocks the copy, and finds +the note erased and nothing written after the copy. ### Attachments, and the one plaintext copy @@ -6690,7 +6690,7 @@ stress budget holds only if it stops keeping the bodies. ### Rust -`cargo test --workspace --exclude e2e` runs everything but the scenarios. +`cargo test --workspace --exclude e2e` runs everything but the journeys. `cargo clippy --workspace --all-targets --all-features -- -D warnings` (`--all-features` is what compiles the `e2e` flavour) and `cargo fmt --all --check` gate the code; `rustfmt.toml` sets lines of 110 columns, filled before they are cut, a chain of calls past 80 cut at each call. A commit that @@ -6764,57 +6764,76 @@ screens, two seconds each, assembled by `cargo run -p app --example tours -- ` from a second -launch for a global action (any flavour hears it, a desktop's shortcut runs it), and in this -flavour alone `--action close`, the event the close button sends (`ViewportCommand::Close` is -pushed as the same `ViewportEvent::Close`), and `--action tray:`, what the tray's menu -hands over; `platform::dialog::from_scenario`, a file dialog answering the path in -`DEVNOTES_E2E_DIALOG`. Whether the window is out of sight is `window-shown` or `window-hidden` in -the tree (`app::sight`), and `window-put-away` how many times it went, read from the commands the -application sent: the same answer on every system, whatever its window manager does. ⚠️ -macOS minimises a closed window, and a minimised window paints nothing: eframe runs `logic` alone -then, outside any pass, so a wrapper of the application reads the commands after `logic` and -after `ui`, where a plugin would miss the window brought back; a scenario reads nothing while it -is away, `App::act_hiding` takes the « not painting » answer there as the window gone, and the -count is read once it is back. `44_window_controls` clicks the title bar's own controls: -maximised then restored, as the next launch remembers, minimised, closed. `43_close_to_tray` closes, hides and brings the -window back by each way on every system; under Linux it also serves a session bus and a -StatusNotifierWatcher of its own, started after the application, and clicks the item's menu. ⚠️ **Its inspection port has no authentication**: a release -build of the flavour does not compile (`compile_error!`), and `lint-rust` checks that the -default build does not link `egui_inspection`. Its own target directory keeps every other build -from overwriting it. - -`e2e/`, at the root beside the product's crates, is the driver. `App::launch` starts the flavour with `--profile ` and -`EGUI_INSPECTION=127.0.0.1:`, and speaks egui's inspection protocol: it reads the -AccessKit tree, finds a control by its `author_id`, clicks the middle of its box, types, presses -a key at its place (the area keys read the position), captures the window. `eventually` reads -the tree until its condition holds, with no `Settle` between reads: `Settle` waits for egui to -be idle, not for the core, whose answer arrives frames later, and each read already renders a -frame (up to 300 ms on WARP). `relaunch` asks `--action quit`, waits for the process to -end its queue drained, and starts it again on the same profile. A failed scenario leaves its -last screen and the application's log in `target/e2e/scenarios//`, beside its -captures. - -One file per scenario, `e2e/tests/_.rs`, one `#[test]` of named steps -(`e2e::step`): `cargo test -p e2e --test 01_first_launch` runs one, `cargo test -p e2e` all of -them, one file after the other. Each launches its own application on its own profile, so the -files never share a process. `cargo test --workspace` is run with `--exclude e2e`. -`e2e/clippy.toml` refuses `std::thread::sleep`: a scenario waits on conditions, never -durations. +on WARP; `DEVNOTES_E2E_PAINT_ALL` paints every frame, to watch a journey run), and the doors the +protocol has no way through — `--action ` from a second launch for a global action (any +flavour hears it, a desktop's shortcut runs it), and in this flavour alone `--action close`, the +event the close button sends (`ViewportCommand::Close` is pushed as the same +`ViewportEvent::Close`), and `--action tray:`, what the tray's menu hands over; +`platform::dialog::from_scenario`, a file dialog answering the path `DEVNOTES_E2E_DIALOG`'s file +holds; `DEVNOTES_E2E_UPDATES`, where a new version is looked for +(`platform::updater::scenario`). Whether the window is out of sight is `window-shown` or +`window-hidden` in the tree (`app::sight`), and `window-put-away` how many times it went, read +from the commands the application sent: the same answer on every system, whatever its window +manager does. ⚠️ macOS minimises a closed window, and a minimised window paints nothing: eframe +runs `logic` alone then, outside any pass, so a wrapper of the application reads the commands +after `logic` and after `ui`, where a plugin would miss the window brought back; a journey reads +nothing while it is away, `Driver::settle_out_of_sight` takes the « not painting » answer there +as the window gone, and the count is read once it is back. Under Linux, journey 7 serves a session +bus and a StatusNotifierWatcher of its own, and clicks the tray's real menu. ⚠️ **Its inspection +port has no authentication**: a release build of the flavour does not compile +(`compile_error!`), and `lint-rust` checks that the default build does not link +`egui_inspection`. Its own target directory keeps every other build from overwriting it. + +`e2e/`, at the root beside the product's crates, holds the driver (`driver.rs`) and on it the +**SDK of the person's acts** (`sdk/`, one file per area), the only thing a journey is written on: +`CONTRIBUTING.md` → "The end-to-end journeys". The driver starts the flavour with +`--profile ` and `EGUI_INSPECTION=127.0.0.1:`, and speaks egui's inspection +protocol: it reads the AccessKit tree, finds a control by its `author_id`, clicks the middle of its +box, types, presses a key at its place (the area keys read the position), captures the window. +`App::expect` reads the tree until its condition holds, with no `Settle` between reads: `Settle` +waits for egui to be idle, not for the core, whose answer arrives frames later, and each read +already renders a frame (up to 300 ms on WARP). A click is a press and a release in two frames: +in one, a menu opened by it is closed by it. `App::relaunch` asks `--action quit`, waits for the +process to end its queue drained, and starts it again on the same profile. The journeys' requests +go to a server of the suite's own (`server.rs`), never to the network. A failed journey leaves its +last screen and the application's log in `target/e2e/scenarios//`, beside its captures. + +| Journey | What is walked | +| ------------------------------ | -------------------------------------------------------------------------- | +| `01_first_day` | the first launch, the library made, the samples, the documentation | +| `02_snippet_to_paste` | a snippet written, found, filled and copied, a JSON explored | +| `03_keeping_a_note` | attachments, versions, the trash and undo, drafts over a relaunch | +| `04_other_kinds` | a Note, a todo list, a calculation and a drawing | +| `05_finding` | the search, the filters, the selection and the tags | +| `06_spaces_and_board` | spaces, folders and the board | +| `07_reaching_from_anywhere` | a second launch, the palette, the clipboard, the tray, the window put away | +| `08_tools` | the tools' home, the catalogue as one table, what is kept, the files | +| `09_calling_an_api` | collections, requests, answers, environments, code, the history | +| `10_scripts_and_runs` | scripts, tests, what stops a send, a collection run | +| `11_libraries_and_transfer` | several libraries, exports and imports | +| `12_looking_after_the_library` | the phrase, the copies, a damaged file, a forgotten phrase | +| `13_making_it_mine` | the preferences, the keys, the areas, the window, an update | + +One file per journey, one `#[test]` of named steps (`e2e::step`): +`cargo test -p e2e --test 01_first_day` runs one, `cargo test -p e2e` all of them, one file after +the other. Each launches its own application on its own profile, so the files never share a +process. `cargo test --workspace` is run with `--exclude e2e`. `e2e/clippy.toml` refuses +`std::thread::sleep`: a journey waits on conditions, never durations. In CI, the `e2e` job of `ci.yml` runs once per platform from `changes` on, beside the Rust tests: it builds the flavour into its cached `target/`, runs `cargo test -p e2e` — under `xvfb-run` with lavapipe and openbox on Linux (maximising a window is a window manager's answer, -which `44_window_controls` reads), on WARP on Windows — and uploads `scenarios/`. The scenarios are not split into groups -(plan, D31): when the suite grows long, it is split by file name, never by a list kept by hand. +which journey 13 reads), on WARP on Windows — and uploads `scenarios/`. The journeys are not split +into groups (plan, D31): were the suite to grow long, it is split by file name, never by a list +kept by hand. **The first job that fails stops everything**, whichever it is: lint, a Rust leg, Sonar, an e2e leg, an advisory. Its last step, `if: failure()`, dispatches `stop.yml` with the run's id, and @@ -6828,8 +6847,8 @@ across three merges while the run read `success`. A job whose failure reads as a weak signal, it is a false one: a flaky run blocking a merge until it is re-run is the price worth paying. -**What the scenarios do not reach**: the system's file dialog (the flavour answers the path the -scenario fixed), the tray menu, a global accelerator pressed on the machine (a second launch's +**What the journeys do not reach**: the system's file dialog (the flavour answers the path the +journey fixed), the tray's icon outside Linux, a global accelerator pressed on the machine (a second launch's `--action` stands for it), and the packages themselves — installed and updated by `packages.yml` (→ "Releasing"). diff --git a/e2e/Cargo.toml b/e2e/Cargo.toml index 6758baa65..bab67083b 100644 --- a/e2e/Cargo.toml +++ b/e2e/Cargo.toml @@ -17,8 +17,8 @@ serde_json.workspace = true tempfile.workspace = true tungstenite.workspace = true -# The watcher and host a Linux scenario serves on a bus of its own. -[target.'cfg(target_os = "linux")'.dev-dependencies] +# The watcher and host a Linux journey serves on a bus of its own. +[target.'cfg(target_os = "linux")'.dependencies] zbus.workspace = true [lints] diff --git a/e2e/clippy.toml b/e2e/clippy.toml index 99573bd2c..13cd0ac48 100644 --- a/e2e/clippy.toml +++ b/e2e/clippy.toml @@ -1,7 +1,7 @@ # Replaces the root's rather than adding to it: its line is repeated. doc-valid-idents = ["SQLite", "DevNotes", "TextMate", ".."] -# A scenario waits on a condition (`App::eventually`), never on a duration. +# A journey waits on a condition (an `expect_…` of the SDK), never on a duration. disallowed-methods = [ - { path = "std::thread::sleep", reason = "wait on a condition with App::eventually" }, + { path = "std::thread::sleep", reason = "wait on a condition with an expect_… of the SDK" }, ] diff --git a/e2e/examples/footprint.rs b/e2e/examples/footprint.rs index 88bd8d77b..7c68c728a 100644 --- a/e2e/examples/footprint.rs +++ b/e2e/examples/footprint.rs @@ -15,7 +15,7 @@ use std::path::PathBuf; use std::process::Command; use std::time::{Duration, Instant}; -use e2e::{App, PASSPHRASE}; +use e2e::{App, Area, PASSPHRASE}; /// Long enough for the window's last repaints and the backup of the day to end. const REST: Duration = Duration::from_secs(10); @@ -99,7 +99,7 @@ fn video(_id: u32) -> Option { /// A line of the table, after the rest and the idle average. #[expect(clippy::disallowed_methods, reason = "an average over a duration, not a wait for a condition")] fn report(app: &App, stage: &str) { - let id = app.id(); + let id = app.process(); std::thread::sleep(REST); let before = read(id); std::thread::sleep(IDLE); @@ -111,16 +111,13 @@ fn report(app: &App, stage: &str) { fn browse(app: &mut App) { for _ in 0..5 { - app.click_nth("note-card-open", 0); - app.wait_for("editor-close"); - app.click("editor-close"); - app.eventually("the editor closes", |tree| !tree.has("editor-close")); + app.notes().open_first(); + app.editor().close(); + } + for area in [Area::Http, Area::Tools, Area::Notes] { + app.window().go_to(area); + app.window().expect_area(area, "the area is on the screen"); } - app.click("area-option-http"); - app.wait_for("http-rail-title"); - app.click("area-option-tools"); - app.click("area-option-notes"); - app.wait_for("note-card-open"); } fn main() { @@ -129,8 +126,12 @@ fn main() { let new = arguments.next().is_some(); let started = Instant::now(); - let mut app = App::launch("footprint", &profile); - app.wait_for("vault-passphrase"); + let mut app = App::launch_on(&profile); + if new { + app.gate().expect_new_phrase_asked("the gate asks for a phrase"); + } else { + app.gate().expect_phrase_asked("the gate asks for the phrase"); + } println!("launch → gate: {} ms", started.elapsed().as_millis()); println!("| Stage | Working set MiB | Private MiB | Dedicated GPU MiB | Idle CPU |"); println!("| --- | --- | --- | --- | --- |"); @@ -138,12 +139,11 @@ fn main() { let started = Instant::now(); if new { - app.create_library(); + app.gate().create_library(PASSPHRASE); } else { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); + app.gate().unlock(PASSPHRASE); } - app.wait_for("note-card-open"); + app.notes().expect_some_card("the cards are on the screen"); println!("unlock → first cards: {} ms", started.elapsed().as_millis()); report(&app, "unlocked, nothing touched"); @@ -151,7 +151,7 @@ fn main() { report(&app, "after opening notes and every area"); for _ in 0..NOTCHES { - app.wheel("canvas"); + app.notes().scroll_down(); } report(&app, "after scrolling the canvas"); app.quit(); diff --git a/e2e/src/driver.rs b/e2e/src/driver.rs new file mode 100644 index 000000000..57369dfa0 --- /dev/null +++ b/e2e/src/driver.rs @@ -0,0 +1,385 @@ +//! The driver under the SDK: launches the `e2e` flavour of `devnotes` and speaks egui's inspection +//! protocol to it. It knows of the application only what its `AccessKit` tree shows, and finds a +//! control by its `author_id`. + +use std::ffi::OsString; +use std::net::{Ipv4Addr, TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use egui::accesskit::{Node, NodeId, Rect, Role, Toggled, TreeUpdate}; +use egui::{Event, Pos2}; +use egui_inspection::protocol::{self, Request, Response}; + +/// How long a condition may take to come true. +pub(crate) const PATIENCE: Duration = Duration::from_secs(30); + +/// Where the flavour is, unless `DEVNOTES_E2E_BIN` says otherwise. +fn binary() -> PathBuf { + if let Some(path) = std::env::var_os("DEVNOTES_E2E_BIN") { + return PathBuf::from(path); + } + let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let binary = workspace.join(format!("target/e2e/debug/devnotes{}", std::env::consts::EXE_SUFFIX)); + assert!( + binary.exists(), + "no e2e flavour at {}: cargo build -p app --features e2e --target-dir target/e2e", + binary.display() + ); + binary +} + +/// Captures and what a failed journey leaves behind, unless `DEVNOTES_E2E_OUTPUT` says otherwise. +fn output() -> PathBuf { + std::env::var_os("DEVNOTES_E2E_OUTPUT") + .map_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../target/e2e/scenarios"), PathBuf::from) +} + +/// What the window shows at one frame. +pub(crate) struct Tree { + nodes: Vec<(NodeId, Node)>, + focus: Option, +} + +impl Tree { + pub(crate) fn find(&self, id: &str) -> Option<&Node> { + self.nodes + .iter() + .map(|(_, node)| node) + .find(|node| node.author_id() == Some(id)) + } + + pub(crate) fn has(&self, id: &str) -> bool { + self.find(id).is_some() + } + + /// Every node wearing `id`, in reading order: top to bottom, then left to right. The tree is in + /// no order of its own. + pub(crate) fn all(&self, id: &str) -> Vec<&Node> { + let mut found: Vec<&Node> = self + .nodes + .iter() + .map(|(_, node)| node) + .filter(|node| node.author_id() == Some(id)) + .collect(); + found.sort_by(|a, b| top(a).total_cmp(&top(b)).then(left(a).total_cmp(&left(b)))); + found + } + + /// The ids on the screen that begin so: a list's rows, each wearing its own. + pub(crate) fn all_starting(&self, start: &str) -> Vec<&str> { + let ids = self.nodes.iter().filter_map(|(_, node)| node.author_id()); + ids.filter(|id| id.starts_with(start)).collect() + } + + /// The node whose id begins so and that says `name`. + pub(crate) fn named(&self, start: &str, name: &str) -> Option<&Node> { + let mut nodes = self.nodes.iter().map(|(_, node)| node); + nodes.find(|node| node.author_id().is_some_and(|id| id.starts_with(start)) && said(node) == name) + } + + /// What each node wearing `id` says, in reading order. + pub(crate) fn texts(&self, id: &str) -> Vec { + self.all(id).into_iter().map(said).collect() + } + + pub(crate) fn count(&self, id: &str) -> usize { + self.all(id).len() + } + + /// Whether anything on the screen says `words`. + pub(crate) fn mentions(&self, words: &str) -> bool { + let said = self.nodes.iter().flat_map(|(_, node)| [node.label(), node.value()]); + said.flatten().any(|text| text.contains(words)) + } + + /// What says exactly `words`. + pub(crate) fn saying(&self, words: &str) -> Option<&Node> { + self.nodes.iter().map(|(_, node)| node).find(|node| said(node) == words) + } + + /// Whether anything inside a place says `words`. + pub(crate) fn says_within(&self, place: Rect, words: &str) -> bool { + self.nodes.iter().any(|(_, node)| { + within(node, place) + && [node.label(), node.value()] + .into_iter() + .flatten() + .any(|text| text.contains(words)) + }) + } + + /// What a node says: its name, or its value when it has no name. + pub(crate) fn text(&self, id: &str) -> Option { + self.find(id).map(said) + } + + /// Whether the middle of a place is inside the window, where it can be clicked. + pub(crate) fn in_window(&self, place: Rect) -> bool { + let window = self.nodes.iter().find(|(_, node)| node.role() == Role::Window); + let Some(window) = window.and_then(|(_, node)| node.bounds()) else { + return true; + }; + let at = middle(place); + let inside = |x: f32, from: f64, to: f64| (from..to).contains(&f64::from(x)); + inside(at.x, window.x0, window.x1) && inside(at.y, window.y0, window.y1) + } + + pub(crate) fn is_disabled(&self, id: &str) -> bool { + self.find(id).is_some_and(Node::is_disabled) + } + + pub(crate) fn is_on(&self, id: &str) -> bool { + self.find(id).is_some_and(is_on) + } + + pub(crate) fn has_focus(&self, id: &str) -> bool { + self.focused().is_some_and(|node| node.author_id() == Some(id)) + } + + /// Whether the `n`th control wearing `id` has the keyboard, in reading order. + pub(crate) fn nth_has_focus(&self, id: &str, n: usize) -> bool { + let nth = self.all(id).get(n).copied(); + nth.zip(self.focused()).is_some_and(|(nth, focused)| std::ptr::eq(nth, focused)) + } + + /// What the control that has the keyboard says. + pub(crate) fn focused_says(&self) -> String { + self.focused().map(said).unwrap_or_default() + } + + /// Where the keyboard is, as a failure says it. + pub(crate) fn keyboard(&self) -> String { + match self.focused() { + Some(node) => format!("on « {} » ({:?})", said(node), node.role()), + None => "nowhere".to_owned(), + } + } + + fn focused(&self) -> Option<&Node> { + self.nodes.iter().find(|(id, _)| Some(*id) == self.focus).map(|(_, node)| node) + } +} + +pub(crate) fn said(node: &Node) -> String { + node.label().or(node.value()).unwrap_or_default().to_owned() +} + +/// Whether a node stands inside a place: a control of a card, a card of a zone. +pub(crate) fn within(node: &Node, place: Rect) -> bool { + node.bounds().is_some_and(|bounds| { + bounds.x0 >= place.x0 - 1.0 + && bounds.x1 <= place.x1 + 1.0 + && bounds.y0 >= place.y0 - 1.0 + && bounds.y1 <= place.y1 + 1.0 + }) +} + +pub(crate) fn is_on(node: &Node) -> bool { + node.toggled() == Some(Toggled::True) +} + +pub(crate) fn top(node: &Node) -> f64 { + node.bounds().map_or(f64::INFINITY, |bounds| bounds.y0) +} + +pub(crate) fn left(node: &Node) -> f64 { + node.bounds().map_or(f64::INFINITY, |bounds| bounds.x0) +} + +/// The middle of a control, in points on the window. +pub(crate) fn middle(bounds: Rect) -> Pos2 { + #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] + Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32) +} + +/// The application, running: a real process, a real window. +pub(crate) struct Driver { + journey: &'static str, + profile: PathBuf, + terminal: PathBuf, + set: Vec<(&'static str, OsString)>, + child: Child, + stream: TcpStream, +} + +impl Driver { + /// Launches the flavour on `profile` and waits until it answers. What it writes on stderr — a + /// terminal's — goes to `terminal`: a file and not a pipe, where what was written before a + /// frame is once the frame is. + pub(crate) fn launch( + journey: &'static str, + profile: PathBuf, + terminal: PathBuf, + set: Vec<(&'static str, OsString)>, + ) -> Self { + let (child, stream) = start(&profile, &terminal, &set); + Driver { journey, profile, terminal, set, child, stream } + } + + /// Launches it again, on the same profile, once it has ended. + pub(crate) fn start_again(&mut self) { + (self.child, self.stream) = start(&self.profile, &self.terminal, &self.set); + } + + /// Waits for the process to end by itself, its queue drained. + pub(crate) fn ended(&mut self) { + let ended = self.child.wait().expect("the application ends"); + assert!(ended.success(), "the application ended with {ended}"); + } + + /// A second launch on the same profile, asking for `action`: it hands it over and exits. + pub(crate) fn hand_over(&self, action: Option<&str>) { + let mut command = Command::new(binary()); + command.arg("--profile").arg(&self.profile); + if let Some(action) = action { + command.arg("--action").arg(action); + } + let status = command.stdout(Stdio::null()).status().expect("the second launch runs"); + assert!(status.success(), "the second launch could not hand over {action:?}"); + } + + pub(crate) fn process(&self) -> u32 { + self.child.id() + } + + pub(crate) fn tree(&mut self) -> Tree { + match self.ask(&Request::GetTree) { + Response::Tree { accesskit: Some(TreeUpdate { nodes, focus, .. }), .. } => { + Tree { nodes, focus: Some(focus) } + } + Response::Tree { .. } => Tree { nodes: Vec::new(), focus: None }, + other => panic!("a tree was asked, {other:?} came back"), + } + } + + /// Until egui has nothing left to draw: not until the core has answered. + pub(crate) fn settle(&mut self) { + self.ask(&Request::Settle { max_steps: 10 }); + } + + /// Until what puts the window out of sight is done. A minimised window paints nothing, as one + /// closed to the tray on macOS: the frame waited for is answered « not painting », which says + /// the window is away and its process alive. + pub(crate) fn settle_out_of_sight(&mut self) { + match exchange(&mut self.stream, &Request::Settle { max_steps: 10 }) { + Ok(Response::Error { message }) if message.contains("not painting") => {} + Ok(Response::Error { message }) => panic!("the application refused to wait: {message}"), + Ok(_) => {} + Err(error) => panic!("the application stopped answering: {error}"), + } + } + + pub(crate) fn apply(&mut self, events: Vec) { + self.ask(&Request::ApplyEvents { events }); + } + + /// The window's inside, in points. + pub(crate) fn resize(&mut self, width: u32, height: u32) { + self.ask(&Request::Resize { width, height }); + self.settle(); + } + + /// The directory of the profile the application runs on. + pub(crate) fn profile(&self) -> &Path { + &self.profile + } + + /// The window as it stands, as `//.png`. + pub(crate) fn capture(&mut self, name: &str) { + match self.ask(&Request::GetScreenshot { pixels_per_point: Some(1.0) }) { + Response::Screenshot(png) => self.leave(&format!("{name}.png"), &png.bytes), + other => panic!("a capture was asked, {other:?} came back"), + } + } + + fn leave(&self, name: &str, bytes: &[u8]) { + let directory = output().join(self.journey); + std::fs::create_dir_all(&directory).expect("the output directory is made"); + std::fs::write(directory.join(name), bytes).expect("the file is written"); + } + + fn ask(&mut self, request: &Request) -> Response { + match exchange(&mut self.stream, request) { + Ok(Response::Error { message }) => { + panic!("the application refused {request:?}: {message}") + } + Ok(response) => response, + Err(error) => { + panic!("the application stopped answering {request:?} (waited up to {PATIENCE:?}): {error}") + } + } + } +} + +/// A failed journey leaves its last screen, the application's log and its terminal's lines. +impl Drop for Driver { + fn drop(&mut self) { + if std::thread::panicking() { + let screen = Request::GetScreenshot { pixels_per_point: Some(1.0) }; + if let Ok(Response::Screenshot(png)) = exchange(&mut self.stream, &screen) { + self.leave("failure.png", &png.bytes); + } + let logs = std::fs::read_dir(self.profile.join("logs")); + let kept = logs.into_iter().flatten().flatten().map(|entry| entry.path()); + for file in kept.chain([self.terminal.clone()]) { + let name = file.file_name().unwrap_or_default().to_string_lossy().into_owned(); + if let Ok(bytes) = std::fs::read(&file) { + self.leave(&name, &bytes); + } + } + } + if let Ok(None) = self.child.try_wait() { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } +} + +fn start(profile: &Path, terminal: &Path, set: &[(&'static str, OsString)]) -> (Child, TcpStream) { + let port = free_port(); + let said = std::fs::File::create(terminal).expect("the terminal's file is created"); + let mut child = Command::new(binary()) + .arg("--profile") + .arg(profile) + .env(egui_inspection::INSPECTION_ENV_VAR, format!("127.0.0.1:{port}")) + .envs(set.iter().map(|(name, value)| (name, value))) + .stdout(Stdio::null()) + .stderr(said) + .spawn() + .expect("the e2e flavour starts"); + let stream = connect(port, &mut child); + (child, stream) +} + +/// The port opens once the window and its adapter exist, half a second on Windows. +fn connect(port: u16, child: &mut Child) -> TcpStream { + let until = Instant::now() + PATIENCE; + loop { + if let Some(status) = child.try_wait().expect("the application is there") { + panic!("the application ended before it answered: {status}"); + } + if let Ok(mut stream) = TcpStream::connect((Ipv4Addr::LOCALHOST, port)) { + // A window that stops drawing answers nothing: without this, the journey waits until + // the job is cancelled, and leaves neither its screen nor its log. + stream.set_read_timeout(Some(PATIENCE)).expect("the socket takes a timeout"); + let version = protocol::read_handshake(&mut stream).expect("an inspection handshake"); + assert_eq!(version, protocol::PROTOCOL_VERSION, "another protocol"); + return stream; + } + assert!(Instant::now() < until, "the application never opened its port"); + std::thread::yield_now(); + } +} + +/// A port nobody listens on now: the system's choice, given back for the application to take. +fn free_port() -> u16 { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("a local port is free"); + listener.local_addr().expect("the port is known").port() +} + +fn exchange(stream: &mut TcpStream, request: &Request) -> std::io::Result { + protocol::write_message(&mut *stream, request)?; + protocol::read_message(&mut *stream) +} diff --git a/e2e/src/lib.rs b/e2e/src/lib.rs index aee35e7d1..e2bf1c491 100644 --- a/e2e/src/lib.rs +++ b/e2e/src/lib.rs @@ -1,743 +1,34 @@ -//! The end-to-end driver: launches the `e2e` flavour of `devnotes` on a profile of -//! its own and drives it like a person, through egui's inspection protocol. It knows of the -//! application only what its AccessKit tree shows, and finds a control by its `author_id`. +//! The end-to-end suite's SDK: what a person does with DevNotes' window, and what they see on it. +//! A journey (`e2e/tests/`) launches an [`App`], acts through its areas (`app.notes()`, +//! `app.editor()`…) and expects what the screen shows; how an act is carried out on the window +//! stays in here. `CONTRIBUTING.md` says how to run and mend them. //! //! The flavour is built apart, so that no other build overwrites it: //! `cargo build -p app --features e2e --target-dir target/e2e`. +mod driver; +mod sdk; mod server; -pub use server::{serve, serve_socket}; +pub use sdk::*; -use std::net::{Ipv4Addr, TcpListener, TcpStream}; -use std::path::{Path, PathBuf}; -use std::process::{Child, Command, Stdio}; -use std::sync::{Mutex, MutexGuard}; -use std::time::{Duration, Instant}; - -use egui::accesskit::{Node, NodeId, TreeUpdate}; -use egui::{Event, Key, Modifiers, PointerButton, Pos2}; -use egui_inspection::protocol::{self, Request, Response}; - -/// How long a condition may take to come true. -const PATIENCE: Duration = Duration::from_secs(30); - -/// One window at a time: the tests of a file run side by side, and a window another covers stops -/// painting under xvfb. -static ONE_WINDOW: Mutex<()> = Mutex::new(()); +use std::cell::RefCell; /// A test value, never anyone's phrase. pub const PASSPHRASE: &str = "correct horse battery staple"; -/// Where the flavour is, unless `DEVNOTES_E2E_BIN` says otherwise. -fn binary() -> PathBuf { - if let Some(path) = std::env::var_os("DEVNOTES_E2E_BIN") { - return PathBuf::from(path); - } - let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); - let binary = workspace.join(format!("target/e2e/debug/devnotes{}", std::env::consts::EXE_SUFFIX)); - assert!( - binary.exists(), - "no e2e flavour at {}: cargo build -p app --features e2e --target-dir target/e2e", - binary.display() - ); - binary -} - -/// Captures and what a failed scenario leaves behind, unless `DEVNOTES_E2E_OUTPUT` says -/// otherwise. -fn output() -> PathBuf { - std::env::var_os("DEVNOTES_E2E_OUTPUT") - .map_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../target/e2e/scenarios"), PathBuf::from) +thread_local! { + static STEP: RefCell = const { RefCell::new(String::new()) }; } -/// One step of a scenario, named in the output so that a failure says where it stopped. +/// One step of a journey, named after what the person wants or sees: a failure says it. pub fn step(name: &str, run: impl FnOnce()) { eprintln!("▶ {name}"); + STEP.with_borrow_mut(|step| name.clone_into(step)); run(); } -/// What the window shows at one frame. -pub struct Tree { - nodes: Vec<(NodeId, Node)>, - focus: Option, -} - -impl Tree { - pub fn find(&self, author_id: &str) -> Option<&Node> { - self.nodes - .iter() - .map(|(_, node)| node) - .find(|node| node.author_id() == Some(author_id)) - } - - /// The control that has the focus, as a failure names it. - pub fn focused(&self) -> String { - let node = self.nodes.iter().find(|(id, _)| Some(*id) == self.focus).map(|(_, node)| node); - match node { - Some(node) => format!( - "{} ({:?} {:?})", - node.author_id().unwrap_or("no author_id"), - node.role(), - node.label().unwrap_or_default() - ), - None => "nothing".to_owned(), - } - } - - pub fn has(&self, author_id: &str) -> bool { - self.find(author_id).is_some() - } - - pub fn count(&self, author_id: &str) -> usize { - self.all(author_id).len() - } - - /// Every node wearing `author_id`, in reading order: top to bottom, then left to right. - pub fn all(&self, author_id: &str) -> Vec<&Node> { - let mut found: Vec<&Node> = self - .nodes - .iter() - .map(|(_, node)| node) - .filter(|node| node.author_id() == Some(author_id)) - .collect(); - // The tree is in no order of its own. - found.sort_by(|a, b| top(a).total_cmp(&top(b)).then(left(a).total_cmp(&left(b)))); - found - } - - /// What each of them says, as [`Self::text`] does. - pub fn texts(&self, author_id: &str) -> Vec { - self.all(author_id) - .into_iter() - .map(|node| node.label().or(node.value()).unwrap_or_default().to_owned()) - .collect() - } - - /// Whether any node says `words`, read with plain spaces: a tool's answer is one of many. - pub fn mentions(&self, words: &str) -> bool { - let plain = |text: &str| text.replace([' ', ' '], " "); - self.nodes.iter().any(|(_, node)| { - [node.label(), node.value()] - .into_iter() - .flatten() - .any(|text| plain(text).contains(words)) - }) - } - - /// What a node says: its name, or its value for a node that has no name. - pub fn text(&self, author_id: &str) -> Option { - let node = self.find(author_id)?; - node.label().or(node.value()).map(str::to_owned) - } -} - -fn top(node: &Node) -> f64 { - node.bounds().map_or(f64::INFINITY, |bounds| bounds.y0) -} - -fn left(node: &Node) -> f64 { - node.bounds().map_or(f64::INFINITY, |bounds| bounds.x0) -} - -/// The application, running on `profile`: a real process, a real window. -pub struct App { - scenario: &'static str, - profile: PathBuf, - child: Child, - stream: TcpStream, - _alone: MutexGuard<'static, ()>, -} - -impl App { - /// Launches the flavour on `profile` and waits until it answers. - pub fn launch(scenario: &'static str, profile: &Path) -> Self { - Self::start(scenario, profile, Command::new(binary())) - } - - /// As `launch`, every file dialog answering `dialog`: no driver reaches the system's. - pub fn launch_answering(scenario: &'static str, profile: &Path, dialog: &Path) -> Self { - let mut command = Command::new(binary()); - command.env(platform::dialog::E2E_DIALOG, dialog); - Self::start(scenario, profile, command) - } - - /// As `launch`, on the session bus at `address`: the one a scenario serves itself. - pub fn launch_on_bus(scenario: &'static str, profile: &Path, address: &str) -> Self { - let mut command = Command::new(binary()); - command.env("DBUS_SESSION_BUS_ADDRESS", address); - Self::start(scenario, profile, command) - } - - /// As `launch`, what the process writes on stderr — a terminal's — kept in `terminal`. A - /// file and not a pipe: what was written before a frame is there once the frame is. - pub fn launch_writing_to(scenario: &'static str, profile: &Path, terminal: &Path) -> Self { - let mut command = Command::new(binary()); - command.stderr(std::fs::File::create(terminal).expect("the terminal's file is created")); - Self::start(scenario, profile, command) - } - - fn start(scenario: &'static str, profile: &Path, mut command: Command) -> Self { - let alone = ONE_WINDOW.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let port = free_port(); - let mut child = command - .arg("--profile") - .arg(profile) - .env(egui_inspection::INSPECTION_ENV_VAR, format!("127.0.0.1:{port}")) - .stdout(Stdio::null()) - .spawn() - .expect("the e2e flavour starts"); - let stream = connect(port, &mut child); - App { scenario, profile: profile.to_path_buf(), child, stream, _alone: alone } - } - - /// The process, for what is read from outside it. - pub fn id(&self) -> u32 { - self.child.id() - } - - /// A second launch on the same profile asking for `action`: it hands it to this one and - /// exits, as the global shortcut's will. - pub fn act(&mut self, action: &str) { - self.hand_over(Some(action)); - self.ask(&Request::Settle { max_steps: 10 }); - } - - /// As `act`, for an action that puts the window out of sight. macOS minimises it, and a - /// minimised window paints nothing: the frame waited for is answered « not painting » there, - /// which says the action was done, the window away and its process alive. - pub fn act_hiding(&mut self, action: &str) { - self.hand_over(Some(action)); - let request = Request::Settle { max_steps: 10 }; - match exchange(&mut self.stream, &request) { - Ok(Response::Error { message }) - if cfg!(target_os = "macos") && message.contains("not painting") => {} - Ok(Response::Error { message }) => { - panic!("the application refused {request:?}: {message}") - } - Ok(_) => {} - Err(error) => panic!("the application stopped answering {request:?}: {error}"), - } - } - - /// A second launch asking for nothing, as the menu's entry starts one: the window comes back. - pub fn launch_again(&mut self) { - self.hand_over(None); - self.ask(&Request::Settle { max_steps: 10 }); - } - - /// A second launch asking for `action`, after which the process ends by itself. - pub fn ends_on(self, action: &str) { - self.hand_over(Some(action)); - self.ended(); - } - - /// Whether the process still runs: a window out of sight is not an application gone. - pub fn running(&mut self) -> bool { - self.child.try_wait().ok().flatten().is_none() - } - - fn hand_over(&self, action: Option<&str>) { - let mut command = Command::new(binary()); - command.arg("--profile").arg(&self.profile); - if let Some(action) = action { - command.arg("--action").arg(action); - } - let status = command.stdout(Stdio::null()).status().expect("the second launch runs"); - assert!(status.success(), "the second launch could not hand over {action:?}"); - } - - /// Closes the window as `Quit` does, waits for the process to end, and launches it again on - /// the same profile: what a person closing and reopening the application sees. - #[must_use] - pub fn relaunch(self) -> Self { - let scenario = self.scenario; - let profile = self.profile.clone(); - self.quit(); - App::launch(scenario, &profile) - } - - /// `Quit` with requests left with changes, the question answered without saving them. - pub fn quit_discarding(mut self) { - self.act("quit"); - self.click("http-leave-discard"); - self.ended(); - } - - /// As `relaunch`, for a scenario that leaves requests with changes. - #[must_use] - pub fn relaunch_discarding(self) -> Self { - let scenario = self.scenario; - let profile = self.profile.clone(); - self.quit_discarding(); - App::launch(scenario, &profile) - } - - /// Waits for the process to end by itself, its queue drained: a quit answered in the window. - pub fn ended(mut self) { - let ended = self.child.wait().expect("the application ends"); - assert!(ended.success(), "the application ended with {ended}"); - } - - /// Asks for `Quit` from a second launch, the way a global shortcut would, and waits for the - /// process to end, its queue drained. - pub fn quit(mut self) { - let asked = Command::new(binary()) - .arg("--profile") - .arg(&self.profile) - .args(["--action", "quit"]) - .status() - .expect("a second launch starts"); - assert!(asked.success(), "the running instance heard no quit"); - let ended = self.child.wait().expect("the application ends"); - assert!(ended.success(), "the application ended with {ended}"); - } - - pub fn tree(&mut self) -> Tree { - match self.ask(&Request::GetTree) { - Response::Tree { accesskit, .. } => match accesskit { - Some(TreeUpdate { nodes, focus, .. }) => Tree { nodes, focus: Some(focus) }, - None => Tree { nodes: Vec::new(), focus: None }, - }, - other => panic!("a tree was asked, {other:?} came back"), - } - } - - /// Reads the tree until `holds` is true of it: answers arrive from the core frames later. - /// No `Settle` between reads: each read renders a frame, and a frame costs up to 300 ms on - /// WARP. - pub fn eventually(&mut self, what: &str, holds: impl Fn(&Tree) -> bool) { - let until = Instant::now() + PATIENCE; - loop { - let tree = self.tree(); - if holds(&tree) { - return; - } - assert!( - Instant::now() < until, - "{what}: still not true after {PATIENCE:?}; the focus is on {}", - tree.focused() - ); - } - } - - pub fn wait_for(&mut self, author_id: &str) { - self.eventually(&format!("{author_id} is shown"), |tree| tree.has(author_id)); - } - - pub fn has(&mut self, author_id: &str) -> bool { - self.ask(&Request::Settle { max_steps: 10 }); - self.tree().has(author_id) - } - - /// Clicks the middle of a control, once it is shown. - pub fn click(&mut self, author_id: &str) { - self.click_where(author_id, |_| true); - } - - /// Clicks the first `author_id` that `which` picks, once it is shown: a row of a list, by - /// what the user named it. ⚠️ Shown means placed, and still: a node joins the tree a frame - /// before it has bounds, and a card just written was clicked in that frame; one still moving - /// (a menu opening, a list settling) was clicked where it no longer was. So the place is the - /// same in two reads in a row. - pub fn click_where(&mut self, author_id: &str, which: impl Fn(&Node) -> bool) { - self.click_with(author_id, PointerButton::Primary, which); - } - - /// As `click_where`, with another button: the middle one closes a tab. - pub fn click_with(&mut self, author_id: &str, button: PointerButton, which: impl Fn(&Node) -> bool) { - let until = Instant::now() + PATIENCE; - let mut last = None; - let bounds = loop { - let tree = self.tree(); - let placed = tree - .all(author_id) - .into_iter() - .find_map(|node| node.bounds().filter(|_| which(node))); - if let Some(bounds) = placed - && last == Some(bounds) - { - break bounds; - } - last = placed; - assert!( - Instant::now() < until, - "{author_id} is shown: still not true after {PATIENCE:?}; the focus is on {}", - tree.focused() - ); - }; - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = - Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); - let press = |pressed| Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }; - self.apply(vec![Event::PointerMoved(pos)]); - self.apply(vec![press(true)]); - self.apply(vec![press(false)]); - } - - /// Two clicks at `at`, in points from the control's corner, sent together: one double click - /// however slowly the window paints. - pub fn double_click_in(&mut self, author_id: &str, at: (f32, f32)) { - self.wait_for(author_id); - let bounds = self - .tree() - .find(author_id) - .and_then(Node::bounds) - .unwrap_or_else(|| panic!("{author_id} has no place on screen")); - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = Pos2::new(bounds.x0 as f32, bounds.y0 as f32) + at.into(); - let press = |pressed| Event::PointerButton { - pos, - button: PointerButton::Primary, - pressed, - modifiers: Modifiers::NONE, - }; - self.apply(vec![Event::PointerMoved(pos)]); - self.apply(vec![press(true), press(false), press(true), press(false)]); - } - - /// Ctrl+C as the window delivers it: a copy, not a key. - pub fn copy(&mut self) { - self.apply(vec![Event::Copy]); - } - - /// Until the system's clipboard holds text that `holds` accepts. - pub fn clipboard_holds(&mut self, what: &str, holds: impl Fn(&str) -> bool) { - use platform::clipboard::Clipboard; - let until = Instant::now() + PATIENCE; - loop { - let held = platform::clipboard::System.text().unwrap_or_default(); - if holds(&held) { - return; - } - assert!( - Instant::now() < until, - "{what}: still not true after {PATIENCE:?}; the clipboard holds {held:?}" - ); - // A frame between two reads. - let _ = self.tree(); - } - } - - /// A press at `from` and a release at `to`, in points from the control's corner. - pub fn drag_in(&mut self, author_id: &str, from: (f32, f32), to: (f32, f32)) { - self.wait_for(author_id); - let bounds = self - .tree() - .find(author_id) - .and_then(Node::bounds) - .unwrap_or_else(|| panic!("{author_id} has no place on screen")); - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let corner = Pos2::new(bounds.x0 as f32, bounds.y0 as f32); - let (from, to) = (corner + from.into(), corner + to.into()); - self.drag(from, to, PointerButton::Primary); - } - - /// A press at `from` and a release at `to`, in points on the window, the pointer moved - /// half way between: what a gesture needs to tell a drag from a click. - pub fn drag(&mut self, from: Pos2, to: Pos2, button: PointerButton) { - let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }; - self.apply(vec![Event::PointerMoved(from)]); - self.apply(vec![press(from, true)]); - self.apply(vec![Event::PointerMoved(from + (to - from) / 2.0)]); - self.apply(vec![Event::PointerMoved(to)]); - self.apply(vec![press(to, false)]); - } - - /// The pointer over the first `author_id` in reading order, once it is shown: what a card - /// shows on hover. - pub fn hover(&mut self, author_id: &str) { - self.hover_nth(author_id, 0); - } - - /// The pointer over the `n`th `author_id` in reading order, counting from 0. - pub fn hover_nth(&mut self, author_id: &str, n: usize) { - self.eventually(&format!("{author_id} #{n} is shown"), |tree| tree.count(author_id) > n); - let tree = self.tree(); - let bounds = tree - .all(author_id) - .get(n) - .and_then(|node| node.bounds()) - .unwrap_or_else(|| panic!("{author_id} has no place on screen")); - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = - Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); - self.apply(vec![Event::PointerMoved(pos)]); - } - - /// Clicks the `n`th `author_id` from the top, counting from 0: a choice among several whose - /// words are the system's language. - pub fn click_nth(&mut self, author_id: &str, n: usize) { - self.eventually(&format!("{author_id} #{n} is shown"), |tree| tree.count(author_id) > n); - let tree = self.tree(); - let target = tree.all(author_id)[n]; - let label = target.label().map(str::to_owned); - let at = top(target); - self.click_where(author_id, |node| { - node.label().map(str::to_owned) == label && (top(node) - at).abs() < 0.5 - }); - } - - /// Through the gate of a blank profile: the phrase twice, and the library opens. - pub fn create_library(&mut self) { - self.fill("vault-passphrase", PASSPHRASE); - self.fill("vault-confirmation", PASSPHRASE); - self.click("vault-submit"); - self.wait_for("area-notes"); - } - - /// Scrolls `within` down until `author_id` is drawn: a list draws only what is in view. - pub fn scroll_to(&mut self, within: &str, author_id: &str) { - self.wait_for(within); - for _ in 0..40 { - if self.has(author_id) { - return; - } - if !self.wheel(within) { - break; - } - } - self.wait_for(author_id); - } - - /// One notch down over `within`; `false` when nothing of that name is drawn. - pub fn wheel(&mut self, within: &str) -> bool { - let Some(bounds) = self.tree().find(within).and_then(Node::bounds) else { - return false; - }; - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = - Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); - self.apply(vec![ - Event::PointerMoved(pos), - Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -240.0), - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Wheel, - modifiers: Modifiers::NONE, - }, - ]); - true - } - - /// Scrolls `within` down until `author_id` stands above `under`: a panel draws what lies past - /// its edge too, clipped, where no click reaches it. - pub fn scroll_above(&mut self, within: &str, author_id: &str, under: &str) { - self.wait_for(author_id); - for _ in 0..40 { - let tree = self.tree(); - let place = |id| tree.find(id).and_then(Node::bounds); - let (Some(target), Some(limit)) = (place(author_id), place(under)) else { - break; - }; - if target.y1 < limit.y0 { - return; - } - let Some(bounds) = place(within) else { - break; - }; - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = Pos2::new( - f64::midpoint(bounds.x0, bounds.x1) as f32, - f64::midpoint(bounds.y0, bounds.y1) as f32, - ); - self.apply(vec![ - Event::PointerMoved(pos), - Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -120.0), - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Wheel, - modifiers: Modifiers::NONE, - }, - ]); - self.ask(&Request::Settle { max_steps: 10 }); - } - panic!("{author_id} never came above {under}"); - } - - /// Until `author_id` stands in the same place on two frames: a wheel's scroll glides, and a - /// click aimed at where it was lands on something else. - pub fn at_rest(&mut self, author_id: &str) { - let place = |app: &mut Self| { - let tree = app.tree(); - tree.find(author_id).and_then(Node::bounds).map(|bounds| (bounds.x0, bounds.y0)) - }; - let until = Instant::now() + PATIENCE; - let mut last = place(self); - loop { - self.ask(&Request::Settle { max_steps: 10 }); - let now = place(self); - if now.is_some() && now == last { - return; - } - assert!(Instant::now() < until, "{author_id} never came to rest"); - last = now; - } - } - - /// Back to the top of `within`: rows out of view are not drawn, so not counted. - pub fn scroll_top(&mut self, within: &str) { - self.wait_for(within); - let Some(bounds) = self.tree().find(within).and_then(Node::bounds) else { - return; - }; - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = - Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); - self.apply(vec![ - Event::PointerMoved(pos), - Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, 100_000.0), - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Wheel, - modifiers: Modifiers::NONE, - }, - ]); - self.ask(&Request::Settle { max_steps: 10 }); - } - - /// Types into the control that has the focus. - pub fn type_text(&mut self, text: &str) { - self.apply(vec![Event::Text(text.to_owned())]); - } - - /// What the clipboard would hand the control that has the focus, as the window delivers it. - pub fn paste(&mut self, text: &str) { - self.apply(vec![Event::Paste(text.to_owned())]); - } - - /// Clicks a field, then types into it once it holds the focus: text typed a frame early - /// goes nowhere, as a passphrase lost on a slow first launch. - /// ⚠️ A click can land in a frame that drops it: clicked again until the focus moves. The gate - /// moves down when its libraries are listed: a click aimed before lands beside the field, - /// whose focus comes back by itself, and the phrase is typed into nothing. - pub fn fill(&mut self, author_id: &str, text: &str) { - if author_id == "vault-passphrase" { - self.wait_for("vault-library"); - self.at_rest(author_id); - } - let until = Instant::now() + PATIENCE; - 'clicked: loop { - self.click(author_id); - // A few frames, each read renders one: a second click at once would be a double. - for _ in 0..5 { - let tree = self.tree(); - if tree.focused().starts_with(author_id) { - break 'clicked; - } - assert!( - Instant::now() < until, - "{author_id} never took the focus; it is on {}", - tree.focused() - ); - } - } - self.type_text(text); - } - - /// A key pressed and released at its place: the area keys read the position, not the letter. - pub fn press(&mut self, key: Key, modifiers: Modifiers) { - self.press_laid_out(key, key, modifiers); - } - - /// A key of another layout than QWERTY: `typed` printed on it, standing where `at` does on - /// QWERTY (AZERTY's Q is at A). - pub fn press_laid_out(&mut self, typed: Key, at: Key, modifiers: Modifiers) { - let event = - |pressed| Event::Key { key: typed, physical_key: Some(at), pressed, repeat: false, modifiers }; - self.apply(vec![event(true)]); - self.apply(vec![event(false)]); - } - - /// The window's inside, in points. - pub fn resize(&mut self, width: u32, height: u32) { - self.ask(&Request::Resize { width, height }); - self.ask(&Request::Settle { max_steps: 10 }); - } - - /// The window as it stands, as `//.png`. - pub fn capture(&mut self, name: &str) -> PathBuf { - let png = match self.ask(&Request::GetScreenshot { pixels_per_point: Some(1.0) }) { - Response::Screenshot(png) => png, - other => panic!("a capture was asked, {other:?} came back"), - }; - let directory = output().join(self.scenario); - std::fs::create_dir_all(&directory).expect("the capture directory is made"); - let path = directory.join(format!("{name}.png")); - std::fs::write(&path, png.bytes).expect("the capture is written"); - path - } - - fn apply(&mut self, events: Vec) { - self.ask(&Request::ApplyEvents { events }); - } - - fn ask(&mut self, request: &Request) -> Response { - match exchange(&mut self.stream, request) { - Ok(Response::Error { message }) => { - panic!("the application refused {request:?}: {message}") - } - Ok(response) => response, - Err(error) => panic!("the application stopped answering {request:?}: {error}"), - } - } -} - -/// A failed scenario leaves its last screen and the application's log beside its captures. -impl Drop for App { - fn drop(&mut self) { - if std::thread::panicking() { - let directory = output().join(self.scenario); - let _ = std::fs::create_dir_all(&directory); - let screen = Request::GetScreenshot { pixels_per_point: Some(1.0) }; - if let Ok(Response::Screenshot(png)) = exchange(&mut self.stream, &screen) { - let _ = std::fs::write(directory.join("failure.png"), png.bytes); - } - keep_logs(&self.profile.join("logs"), &directory); - } - if let Ok(None) = self.child.try_wait() { - let _ = self.child.kill(); - let _ = self.child.wait(); - } - } -} - -fn exchange(stream: &mut TcpStream, request: &Request) -> std::io::Result { - protocol::write_message(&mut *stream, request)?; - protocol::read_message(&mut *stream) -} - -fn keep_logs(logs: &Path, into: &Path) { - let Ok(entries) = std::fs::read_dir(logs) else { - return; - }; - for entry in entries.flatten() { - let _ = std::fs::copy(entry.path(), into.join(entry.file_name())); - } -} - -/// A port nobody listens on now: the system's choice, given back for the application to take. -fn free_port() -> u16 { - let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("a local port is free"); - listener.local_addr().expect("the port is known").port() -} - -/// The port opens once the window and its adapter exist, half a second on Windows. -fn connect(port: u16, child: &mut Child) -> TcpStream { - let until = Instant::now() + PATIENCE; - loop { - if let Some(status) = child.try_wait().expect("the application is there") { - panic!("the application ended before it answered: {status}"); - } - if let Ok(mut stream) = TcpStream::connect((Ipv4Addr::LOCALHOST, port)) { - let version = protocol::read_handshake(&mut stream).expect("an inspection handshake"); - assert_eq!(version, protocol::PROTOCOL_VERSION, "another protocol"); - return stream; - } - assert!(Instant::now() < until, "the application never opened its port"); - std::thread::yield_now(); - } +/// The step being walked, as a failure quotes it. +fn current_step() -> String { + STEP.with_borrow(Clone::clone) } diff --git a/e2e/src/sdk/act.rs b/e2e/src/sdk/act.rs new file mode 100644 index 000000000..cc9d1e244 --- /dev/null +++ b/e2e/src/sdk/act.rs @@ -0,0 +1,339 @@ +//! What the areas are made of: a control found by its id, waited for, acted on. A failure says, in +//! the step it stops, what the person would have seen: each act takes the control's name for it. + +use std::time::{Duration, Instant}; + +use egui::accesskit::{Node, Rect}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2}; + +use super::{App, Shortcut}; +use crate::current_step; +use crate::driver::{PATIENCE, Tree, middle}; + +/// A toast's cross. +const DISMISS: &str = "status-dismiss"; +/// How far down a card the middle of its title's band is, in points. +const CARD_BAND: f32 = 14.0; +/// Clicks closer than this are one gesture to egui. +const DOUBLE_CLICK: Duration = Duration::from_millis(300); + +impl App { + pub(super) fn tree(&mut self) -> Tree { + self.driver.tree() + } + + /// Reads the screen until `holds` is true of it: answers arrive from the core frames later. + pub(super) fn expect(&mut self, says: &str, holds: impl Fn(&Tree) -> bool) { + self.seen(says, |tree| holds(tree).then_some(())); + } + + /// What the screen shows once egui has nothing left to draw: for what must not be there. + pub(super) fn expect_at_rest(&mut self, says: &str, holds: impl Fn(&Tree) -> bool) { + self.driver.settle(); + assert!(holds(&self.tree()), "« {} »: {says}", current_step()); + } + + /// What `find` finds on the screen, once it does. No pause between reads: each one renders a + /// frame. + pub(super) fn seen(&mut self, says: &str, find: impl Fn(&Tree) -> Option) -> T { + let until = Instant::now() + PATIENCE; + loop { + let tree = self.tree(); + if let Some(found) = find(&tree) { + return found; + } + assert!( + Instant::now() < until, + "« {} »: {says} — still not so after {PATIENCE:?}; the keyboard is {}", + current_step(), + tree.keyboard() + ); + } + } + + /// Where a control stands, once it holds still: a node joins the tree a frame before it has a + /// place, and one still moving would be clicked where it no longer is. + pub(super) fn place(&mut self, name: &str, find: impl Fn(&Tree) -> Option) -> Rect { + let says = format!("{name} is on the screen"); + let until = Instant::now() + PATIENCE; + loop { + let first = self.seen(&says, &find); + if find(&self.tree()) == Some(first) { + return first; + } + assert!(Instant::now() < until, "« {} »: {name} never holds still", current_step()); + } + } + + pub(super) fn click(&mut self, id: &str, name: &str) { + self.click_where(id, name, |_| true); + } + + /// The first `id` that `which` picks, in reading order. + pub(super) fn click_where(&mut self, id: &str, name: &str, which: impl Fn(&Node) -> bool) { + self.click_nth_where(id, 0, name, which); + } + + /// The `n`th `id` in reading order, counting from 0. + pub(super) fn click_nth(&mut self, id: &str, n: usize, name: &str) { + self.click_nth_where(id, n, name, |_| true); + } + + /// The `n`th `id` that `which` picks, in reading order, counting from 0. + pub(super) fn click_nth_where(&mut self, id: &str, n: usize, name: &str, which: impl Fn(&Node) -> bool) { + let bounds = self.place(name, |tree| { + let picked = tree.all(id).into_iter().filter(|node| which(node)).nth(n); + picked.and_then(Node::bounds).filter(|bounds| tree.in_window(*bounds)) + }); + if id != DISMISS && self.uncover(bounds) { + return self.click_nth_where(id, n, name, which); + } + self.click_at(middle(bounds), PointerButton::Primary); + } + + /// Clicks a control until it answers: a click is lost when the machine's own pointer moves, or + /// the screen does, between its press and its release. + pub(super) fn click_until( + &mut self, + name: &str, + click: impl Fn(&mut Self), + answered: impl Fn(&Tree) -> bool, + ) { + let until = Instant::now() + PATIENCE; + loop { + click(self); + if (0..20).any(|_| answered(&self.tree())) { + return; + } + assert!(Instant::now() < until, "« {} »: {name} answers a click", current_step()); + } + } + + /// Takes a toast standing over a place off the screen: whether one was. + fn uncover(&mut self, place: Rect) -> bool { + let tree = self.tree(); + let bounds = |id| tree.all(id).into_iter().filter_map(Node::bounds); + let mut toasts = bounds("status-toast").zip(bounds(DISMISS)); + let Some(at) = toasts.position(|(words, cross)| covers(words, cross, middle(place))) else { + return false; + }; + let shown = tree.count(DISMISS); + self.click_nth(DISMISS, at, "the toast's cross"); + self.expect("the toast goes", |tree| tree.count(DISMISS) < shown); + true + } + + /// A place by its top: a todo list's card is mostly the boxes of its items, and a drawing can end + /// under the view. + pub(super) fn click_top(&mut self, place: Rect) { + #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] + let band = Pos2::new(middle(place).x, place.y0 as f32 + CARD_BAND); + self.click_at(band, PointerButton::Primary); + } + + fn click_at(&mut self, pos: Pos2, button: PointerButton) { + self.driver.apply(vec![Event::PointerMoved(pos)]); + self.driver.apply(vec![press(pos, button, true)]); + self.driver.apply(vec![press(pos, button, false)]); + self.clicked = Some(Instant::now()); + } + + /// The `n`th `id` clicked with a key held, Ctrl or Shift. + pub(super) fn click_holding(&mut self, held: Modifiers, id: &str, n: usize, name: &str) { + self.hold(held); + self.click_nth(id, n, name); + self.hold(Modifiers::NONE); + } + + /// Holds a key down, or lets it go. + pub(super) fn hold(&mut self, held: Modifiers) { + self.driver.apply(vec![Event::ModifiersChanged(held)]); + } + + /// The right button, on a control. + pub(super) fn right_click(&mut self, id: &str, name: &str) { + let bounds = self.place(name, |tree| tree.find(id).and_then(Node::bounds)); + self.click_at(middle(bounds), PointerButton::Secondary); + } + + /// The middle button, on the `n`th `id` in reading order, counting from 0. + pub(super) fn middle_click_nth(&mut self, id: &str, n: usize, name: &str) { + let bounds = self.place(name, |tree| tree.all(id).get(n).and_then(|node| node.bounds())); + self.click_at(middle(bounds), PointerButton::Middle); + } + + /// A press and a release elsewhere, the pointer moved half way between: what a gesture needs to + /// tell a drag from a click. + pub(super) fn drag(&mut self, from: Pos2, to: Pos2) { + let button = PointerButton::Primary; + self.driver.apply(vec![Event::PointerMoved(from)]); + self.driver.apply(vec![press(from, button, true)]); + self.driver.apply(vec![Event::PointerMoved(from + (to - from) / 2.0)]); + self.driver.apply(vec![Event::PointerMoved(to)]); + self.driver.apply(vec![press(to, button, false)]); + self.clicked = Some(Instant::now()); + } + + /// A control dragged by so much. + pub(super) fn drag_by(&mut self, id: &str, name: &str, by: egui::Vec2) { + let from = middle(self.place(name, |tree| tree.find(id).and_then(Node::bounds))); + self.drag(from, from + by); + } + + /// Two clicks, sent together so that they are one double click however slowly the window draws. + /// ⚠️ A click just before makes egui count three, wherever it was: they wait their turn. + pub(super) fn double_click(&mut self, pos: Pos2) { + while self.clicked.is_some_and(|at| at.elapsed() < DOUBLE_CLICK) { + self.tree(); + } + let click = || [true, false].map(|down| press(pos, PointerButton::Primary, down)); + self.driver.apply(vec![Event::PointerMoved(pos)]); + self.driver.apply([click(), click()].concat()); + self.clicked = Some(Instant::now()); + } + + /// The pointer over a control, once it is shown. + pub(super) fn hover(&mut self, id: &str, name: &str) { + let bounds = self.place(name, |tree| tree.find(id).and_then(Node::bounds)); + self.move_over(bounds); + } + + /// The pointer over a place: what a card shows on hover. + pub(super) fn move_over(&mut self, bounds: Rect) { + self.driver.apply(vec![Event::PointerMoved(middle(bounds))]); + } + + /// Clicks a field, then types at the end of what it holds. + pub(super) fn fill(&mut self, id: &str, name: &str, text: &str) { + self.take_keyboard(id, name); + self.type_text(text); + } + + /// As `fill`, the `n`th field wearing `id`, in reading order, counting from 0. + pub(super) fn fill_nth(&mut self, id: &str, n: usize, name: &str, text: &str) { + self.take_nth_keyboard(id, n, name); + self.type_text(text); + } + + /// Types over what a field holds. ⚠️ Not by a second click, which selects a word only within + /// the double click's delay: the machine's speed. + pub(super) fn replace(&mut self, id: &str, name: &str, text: &str) { + self.take_keyboard(id, name); + self.press(Shortcut::SelectAll); + self.type_text(text); + } + + /// Clicks a field until it holds the keyboard: what is typed a frame early goes nowhere. ⚠️ A + /// click can land in a frame that drops it; the next comes a few frames later — two at once + /// would be a double click. + pub(super) fn take_keyboard(&mut self, id: &str, name: &str) { + self.take_nth_keyboard(id, 0, name); + } + + fn take_nth_keyboard(&mut self, id: &str, n: usize, name: &str) { + let until = Instant::now() + PATIENCE; + loop { + self.click_nth(id, n, name); + if (0..5).any(|_| self.tree().nth_has_focus(id, n)) { + return; + } + assert!(Instant::now() < until, "« {} »: {name} never took the keyboard", current_step()); + } + } + + /// Takes the keyboard to a control by Tab. + pub(super) fn tab_to(&mut self, id: &str, label: &str, name: &str) { + for _ in 0..80 { + self.press(Shortcut::Tab); + let tree = self.tree(); + if tree.has_focus(id) && tree.focused_says() == label { + return; + } + } + panic!("« {} »: Tab never reached {name}", current_step()); + } + + /// A key pressed and released at its place on the keyboard. + pub(super) fn key(&mut self, key: Key, modifiers: Modifiers) { + self.key_printed(key, key, modifiers); + } + + /// As `key`, `printed` being what the layout prints on the key that stands at `place`. + pub(super) fn key_printed(&mut self, printed: Key, place: Key, modifiers: Modifiers) { + let physical_key = Some(place); + let event = |pressed| Event::Key { key: printed, physical_key, pressed, repeat: false, modifiers }; + self.driver.apply(vec![event(true)]); + self.driver.apply(vec![event(false)]); + } + + /// Scrolls `within` down until `find` finds its place, back from the top past its end: a list + /// draws only what is in view. + pub(super) fn scroll_to( + &mut self, + within: &str, + name: &str, + find: impl Fn(&Tree) -> Option, + ) -> Rect { + for notch in 0..60 { + let tree = self.tree(); + let room = tree.find(within).and_then(Node::bounds); + let in_view = + |place: Rect| room.is_none_or(|room| place.y0 >= room.y0 && place.y1 <= room.y1 + 1.0); + if find(&tree).is_some_and(in_view) { + break; + } + // The first reads are the core's to answer. + match notch { + 0..5 => {} + _ if notch % 20 == 19 => self.wheel(within, 100_000.0), + _ => self.wheel(within, -120.0), + } + } + self.place(name, find) + } + + /// Scrolls `within` until a control stands above `foot`: a panel draws what lies past its edge + /// too, where no click reaches it. + pub(super) fn reach(&mut self, within: &str, (id, name): (&str, &str), foot: &str) { + self.expect(&format!("{name} is on the screen"), |tree| tree.has(id)); + for _ in 0..60 { + let tree = self.tree(); + let place = |id| tree.find(id).and_then(Node::bounds); + let above = place(id).zip(place(foot)).is_some_and(|(target, foot)| target.y1 < foot.y0); + if above { + return; + } + self.wheel(within, -120.0); + } + } + + /// The wheel over `within`, in points: down is negative. + pub(super) fn wheel(&mut self, within: &str, points: f32) { + let Some(bounds) = self.tree().find(within).and_then(Node::bounds) else { + return; + }; + self.driver.apply(vec![ + Event::PointerMoved(middle(bounds)), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, points), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }, + ]); + self.driver.settle(); + } +} + +/// Whether a toast, from its words to its cross and the margin around them, stands over a point. +fn covers(words: Rect, cross: Rect, at: Pos2) -> bool { + const MARGIN: f64 = 40.0; + let (x, y) = (f64::from(at.x), f64::from(at.y)); + let high = words.y0.min(cross.y0) - MARGIN / 2.0..words.y1.max(cross.y1) + MARGIN / 2.0; + (words.x0 - MARGIN..cross.x1 + MARGIN).contains(&x) && high.contains(&y) +} + +fn press(pos: Pos2, button: PointerButton, pressed: bool) -> Event { + Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE } +} diff --git a/e2e/src/sdk/attachments.rs b/e2e/src/sdk/attachments.rs new file mode 100644 index 000000000..c9e6c324c --- /dev/null +++ b/e2e/src/sdk/attachments.rs @@ -0,0 +1,74 @@ +use std::sync::Arc; + +use egui::accesskit::Node; +use egui::{Color32, ColorImage, Event}; + +use super::{App, Shortcut}; + +/// The files attached to the note open. +pub struct Attachments<'a>(pub(super) &'a mut App); + +impl Attachments<'_> { + /// *Attach*, the dialog answering one of the person's files. + pub fn add(&mut self, file: &str) { + self.0.files().answer(file); + self.0.click("attachment-add", "the button that attaches a file"); + } + + /// Pastes a picture in the note. + pub fn paste_picture(&mut self) { + let picture = Arc::new(ColorImage::filled([8, 8], Color32::RED)); + self.0.driver.apply(vec![Event::PasteImage(picture)]); + } + + /// Looks at the first picture, then grows it over the window. + pub fn grow(&mut self) { + self.0.click("attachment-preview", "the picture's eye"); + self.0.click("attachment-zoom", "the picture"); + self.0 + .expect("the picture grows over the window", |tree| tree.has("lightbox-image")); + } + + /// Takes the grown picture away. + pub fn shrink(&mut self) { + self.0.press(Shortcut::Escape); + self.0.expect("the picture goes, the note stays", |tree| { + !tree.has("lightbox-image") && tree.has("editor-title") + }); + } + + /// Saves a file elsewhere, the dialog answering where. + pub fn save(&mut self, n: usize, file: &str) { + self.0.files().answer(file); + self.0.click_nth("attachment-save", n, "the file's « Save »"); + } + + /// Clicks a file's cross: the first time asks, the second removes. + pub fn remove(&mut self, n: usize) { + self.0.click_nth("attachment-remove", n, "the file's cross"); + } + + /// As many files are attached. + pub fn expect(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| tree.count("attachment-open") == count); + } + + /// As many files go by this name. + pub fn expect_named(&mut self, name: &str, count: usize, says: &str) { + self.0.expect(says, |tree| { + let files = tree.all("attachment-open"); + files.into_iter().filter(|file| called(file, name)).count() == count + }); + } + + /// The file asked for is refused: a banner says it, which is then dismissed. + pub fn expect_refused(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("error-banner")); + self.0.click("error-dismiss", "the banner's cross"); + self.0.expect("the banner goes", |tree| !tree.has("error-banner")); + } +} + +fn called(file: &Node, name: &str) -> bool { + file.label().is_some_and(|label| label.contains(name)) +} diff --git a/e2e/src/sdk/board.rs b/e2e/src/sdk/board.rs new file mode 100644 index 000000000..0d4dc23b0 --- /dev/null +++ b/e2e/src/sdk/board.rs @@ -0,0 +1,235 @@ +use egui::accesskit::{Node, Rect}; +use egui::{Pos2, Vec2}; + +use super::{App, Shortcut}; +use crate::driver::{Tree, middle, said, within}; + +/// The board: a space's folders drawn as zones holding their notes, the loose ones beside them. +pub struct Board<'a>(pub(super) &'a mut App); + +/// Where a zone stands and how large it is, as a journey keeps it to compare. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Place { + x: f64, + y: f64, + width: f64, + height: f64, +} + +impl Board<'_> { + /// Shows the space as a board. + pub fn show(&mut self) { + self.0.click("view-board", "« Board »"); + self.0.expect("the board is drawn", |tree| tree.has("board")); + } + + /// Shows the space as a list. + pub fn show_list(&mut self) { + self.0.click("view-list", "« List »"); + self.0.expect("the list is back", |tree| !tree.has("board")); + } + + /// Drags a card into a zone. + pub fn drag_card_into(&mut self, card: &str, zone: &str) { + let from = self.card(card); + let into = self.zone(zone); + // The card lands where its corner does, and the grab is its middle. + let to = corner(into) + Vec2::new(150.0, 120.0); + self.0.drag(middle(from), to); + } + + /// Drags a card out of its zone, onto the ground under it. + pub fn drag_card_out(&mut self, card: &str) { + let from = middle(self.card(card)); + self.0.drag(from, from + Vec2::new(0.0, 360.0)); + } + + /// Drags a card onto a folder of the rail. + pub fn drag_card_onto_folder(&mut self, card: &str, folder: &str) { + let from = self.card(card); + let to = self.0.place("the folder in the rail", |tree| { + let mut rows = tree.all("folder-option").into_iter(); + rows.find(|row| said(row) == folder)?.bounds() + }); + self.0.drag(middle(from), middle(to)); + } + + /// Moves a zone by its grip, down to free ground. + pub fn move_zone(&mut self, zone: &str) { + self.drag_control(zone, "board-zone-grip", Vec2::new(93.0, 221.0)); + } + + /// Widens a zone by its corner. + pub fn widen_zone(&mut self, zone: &str) { + self.drag_control(zone, "board-zone-resize", Vec2::new(260.0, 0.0)); + } + + /// Draws a folder on the ground, and names it. + pub fn draw_folder(&mut self, name: &str) { + let ground = self.0.place("the board", |tree| tree.find("board").and_then(Node::bounds)); + let from = Pos2::new(corner(ground).x + 40.0, middle(ground).y * 2.0 - corner(ground).y - 260.0); + self.0.drag(from, from + Vec2::new(300.0, 220.0)); + self.0.fill("folder-name-input", "the new folder's name", name); + self.0.press(Shortcut::Enter); + self.expect_zone(name, "the folder is a zone"); + } + + /// Opens a zone's folder by its title. + pub fn open_zone(&mut self, zone: &str) { + self.0 + .click_where("board-zone-open", "the zone's title", |title| said(title) == zone); + } + + /// Ticks every card of a zone, from its menu. + pub fn tick_zone(&mut self, zone: &str) { + self.0 + .click_where("board-zone-menu", "the zone's « ⋯ »", |menu| said(menu).contains(zone)); + self.0.click("folder-select-notes", "« Select its notes »"); + } + + /// *Align*. + pub fn align(&mut self) { + self.0.click("board-tidy", "« Align »"); + } + + /// *Other arrangements*, then the one that puts everything back in order. + pub fn reorganise(&mut self) { + self.0.click("board-tidy-more", "« Other arrangements »"); + self.0.click("board-tidy-everything", "the arrangement of everything"); + } + + /// Where a zone stands. + pub fn place_of(&mut self, zone: &str) -> Place { + place(self.zone(zone)) + } + + /// The zones are these, in any order. + pub fn expect_zones(&mut self, zones: &[&str], says: &str) { + self.0.expect(says, |tree| { + let mut drawn = tree.texts("board-zone-open"); + let mut wanted = zones.to_vec(); + drawn.sort(); + wanted.sort_unstable(); + drawn == wanted + }); + } + + /// A zone is drawn. + pub fn expect_zone(&mut self, zone: &str, says: &str) { + self.0.expect(says, |tree| zone_of(tree, zone).is_some()); + } + + /// A zone holds these notes. + pub fn expect_in_zone(&mut self, zone: &str, notes: &[&str], says: &str) { + self.0.expect(says, |tree| held(tree, zone) == notes); + } + + /// A zone holds this note, among others. + pub fn expect_holding(&mut self, zone: &str, note: &str, says: &str) { + self.0.expect(says, |tree| held(tree, zone).iter().any(|card| card == note)); + } + + /// These notes stand loose, beside the zones, in any order. + pub fn expect_loose(&mut self, notes: &[&str], says: &str) { + self.0.expect(says, |tree| { + let mut drawn = tree.texts("board-loose-card"); + let mut wanted = notes.to_vec(); + drawn.sort(); + wanted.sort_unstable(); + drawn == wanted + }); + } + + /// A zone is elsewhere than `before`, of the same size. + pub fn expect_moved(&mut self, zone: &str, before: Place, says: &str) { + self.0.expect(says, |tree| { + zone_of(tree, zone).map(place).is_some_and(|now| { + ((now.x - before.x).abs() > 0.5 || (now.y - before.y).abs() > 0.5) + && (now.width - before.width).abs() < 0.5 + }) + }); + } + + /// A zone is elsewhere than `before`, whatever its size. + pub fn expect_moved_anywhere(&mut self, zone: &str, before: Place, says: &str) { + self.0 + .expect(says, |tree| zone_of(tree, zone).map(place).is_some_and(|now| now != before)); + } + + /// A zone is wider than `before`, where it was. + pub fn expect_wider(&mut self, zone: &str, before: Place, says: &str) { + self.0.expect(says, |tree| { + zone_of(tree, zone) + .map(place) + .is_some_and(|now| now.width > before.width + 100.0 && (now.x - before.x).abs() < 0.5) + }); + } + + /// A zone stands exactly where and as large as `before`. + pub fn expect_place(&mut self, zone: &str, before: Place, says: &str) { + self.0.expect(says, |tree| zone_of(tree, zone).map(place) == Some(before)); + } + + /// A note the search leaves out stays on the board, dimmed. + pub fn expect_dimmed(&mut self, note: &str, says: &str) { + self.0.expect(says, |tree| { + let loose = tree.all("board-loose-card").into_iter(); + let mut cards = loose.chain(tree.all("board-zone-card")); + cards.any(|card| said(card) == note && card.is_disabled()) + }); + } + + /// The board is on the screen. + pub fn expect(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("board")); + } + + /// The space is listed, not on a board. + pub fn expect_list(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("board") && tree.is_on("view-list")); + } + + fn zone(&mut self, zone: &str) -> Rect { + self.0.place("the zone", |tree| zone_of(tree, zone)) + } + + fn card(&mut self, card: &str) -> Rect { + self.0.place("the card on the board", |tree| { + let loose = tree.all("board-loose-card").into_iter(); + let mut cards = loose.chain(tree.all("board-zone-card")); + cards.find(|node| said(node) == card)?.bounds() + }) + } + + fn drag_control(&mut self, zone: &str, id: &str, by: Vec2) { + let frame = self.zone(zone); + let control = self.0.place("the zone's handle", |tree| { + let mut controls = tree.all(id).into_iter(); + controls.find(|control| within(control, frame))?.bounds() + }); + self.0.drag(middle(control), middle(control) + by); + } +} + +fn zone_of(tree: &Tree, zone: &str) -> Option { + let mut zones = tree.all("board-zone").into_iter(); + zones.find(|node| said(node) == zone)?.bounds() +} + +/// The titles of the cards inside a zone. +fn held(tree: &Tree, zone: &str) -> Vec { + let Some(frame) = zone_of(tree, zone) else { + return Vec::new(); + }; + let cards = tree.all("board-zone-card").into_iter(); + cards.filter(|card| within(card, frame)).map(said).collect() +} + +fn place(zone: Rect) -> Place { + Place { x: zone.x0, y: zone.y0, width: zone.width(), height: zone.height() } +} + +fn corner(place: Rect) -> Pos2 { + #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] + Pos2::new(place.x0 as f32, place.y0 as f32) +} diff --git a/e2e/src/sdk/calc.rs b/e2e/src/sdk/calc.rs new file mode 100644 index 000000000..a7f5a00eb --- /dev/null +++ b/e2e/src/sdk/calc.rs @@ -0,0 +1,52 @@ +use egui::accesskit::Node; + +use super::{App, Modifiers}; +use crate::driver::Tree; + +/// The calculation open. Its results are read by their figures: the language on the screen writes +/// the decimal mark and the units. +pub struct Calc<'a>(pub(super) &'a mut App); + +impl Calc<'_> { + /// Picks a result, counted from 0. + pub fn pick(&mut self, result: usize) { + self.0.click_nth("calc-result", result, "the result"); + } + + /// Picks a result beside those picked, Ctrl held. + pub fn pick_also(&mut self, result: usize) { + self.0.click_holding(Modifiers::COMMAND, "calc-result", result, "the result"); + } + + /// The results, top to bottom, by their figures. + pub fn expect_results(&mut self, figures: &[&str], says: &str) { + self.0.expect(says, |tree| results(tree) == figures); + } + + /// As many lines say why they have no result. + pub fn expect_errors(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| { + let errors = tree.all("calc-failure"); + errors.len() == count && errors.iter().all(|error| !said(error).is_empty()) + }); + } + + /// The footer sums what is picked, by its figures. + pub fn expect_sum(&mut self, figures: &str, says: &str) { + self.0.expect(says, |tree| { + tree.text("calc-summary").is_some_and(|said| digits(&said).contains(figures)) + }); + } +} + +fn results(tree: &Tree) -> Vec { + tree.all("calc-result").into_iter().map(|node| digits(said(node))).collect() +} + +fn said(node: &Node) -> &str { + node.value().unwrap_or_default() +} + +pub(super) fn digits(text: &str) -> String { + text.chars().filter(char::is_ascii_digit).collect() +} diff --git a/e2e/src/sdk/clipboard.rs b/e2e/src/sdk/clipboard.rs new file mode 100644 index 000000000..97cdb4c7a --- /dev/null +++ b/e2e/src/sdk/clipboard.rs @@ -0,0 +1,43 @@ +use std::time::Instant; + +use platform::clipboard::Clipboard as _; + +use super::App; +use crate::current_step; +use crate::driver::PATIENCE; + +/// The system's clipboard. +pub struct Clipboard<'a>(pub(super) &'a mut App); + +impl Clipboard<'_> { + /// The clipboard holds this text, line endings aside. + pub fn expect(&mut self, text: &str, says: &str) { + self.expect_that(says, |held| held.replace("\r\n", "\n") == text); + } + + /// The clipboard holds a text that says this, among other things. + pub fn expect_saying(&mut self, words: &str, says: &str) { + self.expect_that(says, |held| held.contains(words)); + } + + pub(super) fn expect_that(&mut self, says: &str, holds: impl Fn(&str) -> bool) { + let until = Instant::now() + PATIENCE; + loop { + let held = held(); + if holds(&held) { + return; + } + assert!( + Instant::now() < until, + "« {} »: {says} — the clipboard still holds {held:?} after {PATIENCE:?}", + current_step() + ); + // A frame between two reads. + let _ = self.0.tree(); + } + } +} + +pub(super) fn held() -> String { + platform::clipboard::System.text().unwrap_or_default() +} diff --git a/e2e/src/sdk/code.rs b/e2e/src/sdk/code.rs new file mode 100644 index 000000000..9c8db1309 --- /dev/null +++ b/e2e/src/sdk/code.rs @@ -0,0 +1,65 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut}; +use crate::driver::said; + +/// The request open, written as code. +pub struct Code<'a>(pub(super) &'a mut App); + +impl Code<'_> { + /// Opens the dialog. + pub fn open(&mut self) { + self.0.click("http-code-open", "« Code »"); + self.0.expect("the code is written", |tree| tree.has("http-code-output")); + } + + /// Closes it. + pub fn close(&mut self) { + self.0.press(Shortcut::Escape); + self.0.expect("the dialog closes", |tree| !tree.has("http-code-dialog")); + } + + /// Writes it for another target, found by the filter. + pub fn choose(&mut self, typed: &str, target: &str) { + self.0.replace("http-code-filter", "the filter of the targets", typed); + self.0.click_where("http-code-target", "the target", |row| said(row) == target); + } + + /// Resolves the variables, or leaves them as they are written. + pub fn flip_resolved(&mut self) { + self.0.click("http-code-resolve", "« Resolve the variables »"); + } + + /// Asks for the secrets in clear: the dialog asks before. + pub fn ask_secrets(&mut self) { + self.0.click("http-code-secrets", "« Include the secrets »"); + self.0 + .expect("the dialog asks before writing them", |tree| tree.has("http-code-secrets-ask")); + } + + /// Answers yes. + pub fn include_secrets(&mut self) { + self.0.click("http-code-secrets-yes", "the yes"); + } + + /// Copies the code. + pub fn copy(&mut self) { + self.0.click("http-code-copy", "« Copy »"); + } + + /// The code says this. + pub fn expect(&mut self, words: &str, says: &str) { + self.0.expect(says, |tree| { + let code = tree.find("http-code-output").and_then(Node::label); + code.is_some_and(|code| code.contains(words)) + }); + } + + /// The code says nothing of this. + pub fn expect_without(&mut self, words: &str, says: &str) { + self.0.expect(says, |tree| { + let code = tree.find("http-code-output").and_then(Node::label); + code.is_some_and(|code| !code.contains(words)) + }); + } +} diff --git a/e2e/src/sdk/drawing.rs b/e2e/src/sdk/drawing.rs new file mode 100644 index 000000000..4c7f94855 --- /dev/null +++ b/e2e/src/sdk/drawing.rs @@ -0,0 +1,169 @@ +use egui::accesskit::Node; +use egui::{Pos2, Vec2}; + +use super::{App, Key, Modifiers, Shortcut}; +use crate::current_step; + +/// The drawing open. Places on it are named by the journey and stand still, zoom aside. +pub struct Drawing<'a>(pub(super) &'a mut App); + +/// A tool in hand. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tool { + Rectangle, + Ellipse, + Diamond, + Arrow, + Text, +} + +/// A place on the drawing: its left, its middle or its right, each wide enough for a shape. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Spot { + Left, + Middle, + Right, + Below, +} + +impl Spot { + /// Its corner, in points from the stage's. + fn corner(self) -> Vec2 { + match self { + Self::Left => Vec2::new(40.0, 40.0), + Self::Middle => Vec2::new(200.0, 40.0), + Self::Right => Vec2::new(360.0, 40.0), + Self::Below => Vec2::new(200.0, 220.0), + } + } + + fn middle(self) -> Vec2 { + self.corner() + SHAPE / 2.0 + } +} + +const SHAPE: Vec2 = Vec2::new(100.0, 70.0); + +impl Drawing<'_> { + /// Draws a shape at a place, its tool taken by its button. + pub fn draw(&mut self, tool: Tool, at: Spot) { + let shapes = self.shapes(); + self.take(tool); + self.drag(at.corner(), at.corner() + SHAPE); + self.expect_shapes(shapes + 1, "the shape is drawn"); + } + + /// Draws an arrow from the shape of one place to the shape of another. + pub fn draw_arrow(&mut self, from: Spot, to: Spot) { + let shapes = self.shapes(); + self.take(Tool::Arrow); + self.drag(from.middle(), to.middle()); + self.expect_shapes(shapes + 1, "the arrow is drawn"); + } + + /// Writes a text at a place. + pub fn write(&mut self, text: &str, at: Spot) { + let shapes = self.shapes(); + self.take(Tool::Text); + self.drag(at.corner(), at.corner()); + self.0.expect("a text waits to be typed", |tree| tree.has("drawing-text")); + self.0.type_text(text); + self.0.press(Shortcut::Escape); + self.expect_shapes(shapes + 1, "the text is on the drawing"); + } + + /// Drags the shape of one place to another. + pub fn move_shape(&mut self, from: Spot, to: Spot) { + self.take_selection(); + self.drag(from.middle(), to.middle()); + } + + /// Selects the shape of a place and removes it with Delete. + pub fn delete(&mut self, at: Spot) { + self.take_selection(); + self.drag(at.middle(), at.middle()); + self.0.press(Shortcut::Delete); + } + + /// Zooms in, by its button. + pub fn zoom_in(&mut self) { + self.0.click("drawing-zoom-in", "the button that zooms in"); + } + + /// Shows the whole drawing, by its key. + pub fn show_whole(&mut self) { + // The stage takes the keys from a click on its ground. + self.take_selection(); + self.drag(Vec2::new(8.0, 8.0), Vec2::new(8.0, 8.0)); + self.0.key(Key::F, Modifiers::NONE); + } + + /// Exports the drawing as a PNG, the dialog answering where. + pub fn export_png(&mut self, file: &str) { + self.0.files().answer(file); + self.0.click("drawing-export-png", "« PNG »"); + } + + /// Exports the drawing as an SVG, the dialog answering where. + pub fn export_svg(&mut self, file: &str) { + self.0.files().answer(file); + self.0.click("drawing-export-svg", "« SVG »"); + } + + /// As many shapes are on the drawing, arrows and texts among them. + pub fn expect_shapes(&mut self, count: usize, says: &str) { + let count = count.to_string(); + self.0 + .expect(says, |tree| tree.find("drawing-stage").and_then(Node::value) == Some(count.as_str())); + } + + /// Between two SVG exports, the arrow moved. + pub fn expect_arrow_moved(&mut self, before: &str, after: &str, says: &str) { + let arrow = |bytes: Vec| { + let picture = String::from_utf8_lossy(&bytes).into_owned(); + picture.split(" usize { + self.0.expect("the drawing is open", |tree| tree.has("drawing-stage")); + let tree = self.0.tree(); + let count = tree.find("drawing-stage").and_then(Node::value); + count.and_then(|count| count.parse().ok()).unwrap_or_default() + } + + /// A tool by its button. + fn take(&mut self, tool: Tool) { + let id = match tool { + Tool::Rectangle => "drawing-tool-rectangle", + Tool::Ellipse => "drawing-tool-ellipse", + Tool::Diamond => "drawing-tool-diamond", + Tool::Arrow => "drawing-tool-arrow", + Tool::Text => "drawing-tool-text", + }; + self.0.click(id, "the tool's button"); + self.0.expect("the tool is in hand", |tree| tree.is_on(id)); + } + + fn take_selection(&mut self) { + self.0.click("drawing-tool-select", "the pointer's tool"); + } + + fn drag(&mut self, from: Vec2, to: Vec2) { + let stage = self + .0 + .place("the drawing", |tree| tree.find("drawing-stage").and_then(Node::bounds)); + #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] + let corner = Pos2::new(stage.x0 as f32, stage.y0 as f32); + self.0.drag(corner + from, corner + to); + } +} diff --git a/e2e/src/sdk/editor.rs b/e2e/src/sdk/editor.rs new file mode 100644 index 000000000..154196ed5 --- /dev/null +++ b/e2e/src/sdk/editor.rs @@ -0,0 +1,341 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut}; +use crate::driver::Tree; + +/// The note open: its title, its text and what stands around them. +pub struct Editor<'a>(pub(super) &'a mut App); + +impl Editor<'_> { + /// Types in the title, at the end of what it holds. + pub fn type_title(&mut self, title: &str) { + self.0.fill("editor-title", "the note's title", title); + } + + /// Types in the code, or the text of a calculation. + pub fn type_code(&mut self, code: &str) { + self.0.fill("editor-body", "the note's text", code); + let typed = code.to_owned(); + self.0 + .expect("the note's text is typed", move |tree| held(tree).contains(&typed)); + } + + /// Types over the title. + pub fn retype_title(&mut self, title: &str) { + self.0.replace("editor-title", "the note's title", title); + } + + /// Types over the code. + pub fn retype_code(&mut self, code: &str) { + self.0.take_keyboard("editor-body", "the note's text"); + self.0.press(Shortcut::SelectAll); + self.0.paste(code); + let typed = code.to_owned(); + self.0.expect("the note's text is typed over", move |tree| held(tree) == typed); + } + + /// Types at the end of the code. + pub fn add_to_code(&mut self, code: &str) { + self.0.take_keyboard("editor-body", "the note's text"); + self.0.press(Shortcut::TextEnd); + self.0.type_text(code); + } + + /// Types where the snippet is for. + pub fn type_context(&mut self, context: &str) { + self.0.fill("editor-source", "the note's context", context); + } + + /// Adds a tag. + pub fn add_tag(&mut self, tag: &str) { + self.0.fill("editor-tag-add", "the field of a new tag", tag); + self.0.press(Shortcut::Enter); + self.expect_tag(tag, "the tag is added"); + } + + /// Chooses the language from the keyboard, in its menu's filter. + pub fn choose_language(&mut self, typed: &str) { + self.0.click("editor-language", "the language's menu"); + self.0.take_keyboard("editor-language-filter", "the filter of the languages"); + self.0.type_text(typed); + self.0.press(Shortcut::Enter); + self.0 + .expect("the language's menu closes", |tree| !tree.has("editor-language-filter")); + } + + /// Gives the note a due date: tomorrow, from the calendar's keys. + pub fn choose_due_tomorrow(&mut self) { + self.0.click("editor-deadline", "the due date's field"); + self.0.expect("the calendar opens on this month", |tree| tree.has("date-day")); + self.0.press(Shortcut::Right); + self.0.press(Shortcut::Enter); + self.0.expect("the calendar closes", |tree| !tree.has("date-day")); + } + + /// Types in a Note, where its caret is. + pub fn type_note(&mut self, text: &str) { + self.0.take_keyboard("editor-rich", "the Note's text"); + self.0.type_text(text); + } + + /// *Format*, by its button. + pub fn format(&mut self) { + self.0.click("editor-format", "« Format »"); + } + + /// Takes the format back, from its notice. + pub fn undo_format(&mut self) { + self.0.click("editor-format-undo", "the notice's « Undo »"); + } + + /// Finds a word and puts another in its place, everywhere. + pub fn replace_everywhere(&mut self, word: &str, with: &str) { + self.find(word); + self.0.click("search-replace-toggle", "the arrow that shows the replacement"); + self.0.fill("search-replace-field", "the replacement", with); + self.0.click("search-replace-all", "« Replace all »"); + } + + /// Expands the note over the cards, or puts it back beside them. + pub fn flip_expanded(&mut self) { + self.0.click("editor-fullscreen", "the button that expands the note"); + } + + /// Folds the note's header into a line. + pub fn fold_header(&mut self) { + self.click_button_or_entry("editor-fold-header", "the button that folds the header"); + self.0.expect("the header is a line", |tree| tree.has("editor-header-summary")); + } + + /// Unfolds the note's header, from its line. + pub fn unfold_header(&mut self) { + self.0.click("editor-header-summary", "the header's line"); + self.0.expect("the header is back", |tree| !tree.has("editor-header-summary")); + } + + /// Goes to a line by its number, Ctrl+Alt+G. + pub fn go_to_line(&mut self, line: usize) { + self.0.press(Shortcut::GoToLine); + self.0 + .expect("the field of the line has the keyboard", |tree| tree.has_focus("go-to-line-input")); + self.0.type_text(&line.to_string()); + self.0.press(Shortcut::Enter); + self.0.expect("the code has the keyboard again", |tree| { + !tree.has("go-to-line-input") && tree.has_focus("editor-body") + }); + } + + /// Makes the note a Note, from its *Kind* menu. + pub fn convert_to_note(&mut self) { + // The menu offers the other kinds, the snippet first: a list's has it above « Note ». + let note = if self.0.tree().has("checklist-add") { "editor-kind-1" } else { "editor-kind-0" }; + self.0.click("editor-kind", "the « Kind » menu"); + self.0.click(note, "« Note » in the menu"); + } + + /// Shows the text filled with its fields, or gives the code back. + pub fn flip_filled(&mut self) { + self.0 + .click("placeholder-panel-preview", "the button that shows the text filled"); + } + + /// Opens the find bar from the note's text and types a word in it. + pub fn find(&mut self, word: &str) { + let written = if self.0.tree().has("editor-rich") { "editor-rich" } else { "editor-body" }; + self.0.take_keyboard(written, "the note's text"); + self.0.press(Shortcut::Find); + self.0 + .expect("the find bar opens, the keyboard in it", |tree| tree.has_focus("search-field")); + self.0.type_text(word); + } + + /// Closes the find bar. + pub fn close_find(&mut self) { + self.0.press(Shortcut::Escape); + self.0.expect("the find bar closes", |tree| !tree.has("search-field")); + } + + /// Leaves the note by Esc: the field first, then the note. + pub fn leave_by_escape(&mut self) { + self.0.press(Shortcut::Escape); + if self.0.tree().has("editor-title") { + self.0.press(Shortcut::Escape); + } + self.expect_closed("the note closes"); + } + + /// Closes the note, which is written on the way out. + pub fn close(&mut self) { + self.0.click("editor-close", "the note's closing cross"); + self.expect_closed("the note closes"); + } + + /// A snippet or a calculation is open, its text under the hand. + pub fn expect_code_open(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("editor-body")); + } + + /// A Note is open, written formatted. + pub fn expect_note_open(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("editor-rich") && !tree.has("editor-body")); + } + + /// The code is laid out over several lines. + pub fn expect_several_lines(&mut self, says: &str) { + self.0.expect(says, |tree| held(tree).lines().count() > 5); + } + + /// The code is on one line. + pub fn expect_one_line(&mut self, says: &str) { + self.0.expect(says, |tree| held(tree).lines().count() == 1); + } + + /// The text of the note, as it stands. + pub fn expect_code(&mut self, code: &str, says: &str) { + self.0.expect(says, |tree| held(tree) == code); + } + + /// The find bar counts its matches, as « 1 / 3 ». + pub fn expect_matches(&mut self, counted: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("search-count").as_deref() == Some(counted)); + } + + /// The first line of the code goes on past the edge: the next row is another line's. + pub fn expect_line_unwrapped(&mut self, says: &str) { + self.mark_the_next_row(); + self.0.expect(says, |tree| held(tree).trim_end().ends_with('|')); + } + + /// The first line of the code is laid out over several rows: the next one is still its own. + pub fn expect_line_wrapped(&mut self, says: &str) { + self.mark_the_next_row(); + self.0 + .expect(says, |tree| held(tree).contains('|') && !held(tree).trim_end().ends_with('|')); + } + + /// A mark typed one row down from the start. + fn mark_the_next_row(&mut self) { + self.0.press(Shortcut::Down); + self.0.type_text("|"); + } + + /// The footer says this of what the code holds. + pub fn expect_footer(&mut self, words: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("editor-stats").is_some_and(|said| said.contains(words))); + } + + /// The code gives way to the text read with its values. + pub fn expect_filled(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("editor-body") && tree.has("editor-title")); + } + + /// The code was formatted, and the notice says how many lines changed. + pub fn expect_formatted(&mut self, says: &str) { + self.0.expect(says, |tree| { + let told = notice(tree) == Some("formatted"); + let counted = tree.text("editor-format-notice"); + told && counted.is_some_and(|said| said.contains(|it: char| it.is_ascii_digit())) + }); + } + + /// The notice says where the code's syntax breaks. + pub fn expect_syntax_error(&mut self, says: &str) { + self.0.expect(says, |tree| notice(tree) == Some("syntax")); + } + + /// *Format* is out of reach, and says why under the pointer. + pub fn expect_no_format(&mut self, says: &str) { + self.0.expect(says, |tree| tree.is_disabled("editor-format")); + self.0.hover("editor-format", "« Format »"); + self.0.expect(says, |tree| tree.mentions("Prettier")); + } + + /// The code holds this, among other things. + pub fn expect_code_holding(&mut self, code: &str, says: &str) { + self.0.expect(says, |tree| held(tree).contains(code)); + } + + /// The code holds nothing of this. + pub fn expect_code_without(&mut self, code: &str, says: &str) { + self.0 + .expect(says, |tree| tree.has("editor-body") && !held(tree).contains(code)); + } + + /// The note wears this tag. + pub fn expect_tag(&mut self, tag: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("editor-tag").iter().any(|worn| worn.contains(tag))); + } + + /// The note's kind is said, and cannot be changed. + pub fn expect_no_kind_to_choose(&mut self, says: &str) { + self.0.click("editor-kind", "the note's kind"); + self.0 + .expect_at_rest(says, |tree| tree.has("editor-kind") && !tree.has("editor-kind-0")); + } + + /// The note's title. + pub fn expect_title(&mut self, title: &str, says: &str) { + self.0 + .expect(says, |tree| tree.find("editor-title").and_then(Node::value) == Some(title)); + } + + /// Another note than this one is open. + pub fn expect_another_note(&mut self, title: &str, says: &str) { + self.0.expect(says, |tree| { + tree.find("editor-title") + .and_then(Node::value) + .is_some_and(|open| open != title) + }); + } + + /// The note's context. + pub fn expect_context(&mut self, context: &str, says: &str) { + self.0 + .expect(says, |tree| tree.find("editor-source").and_then(Node::value) == Some(context)); + } + + /// The note takes the whole area, the cards put away. + pub fn expect_expanded(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("note-card") && tree.has("editor-title")); + } + + /// A button of the note's header, or its entry of the ⋯ menu where there is no room for it. + pub(super) fn click_button_or_entry(&mut self, id: &str, name: &str) { + if !self.0.tree().has(id) { + self.0.click("editor-more", "the note's « ⋯ »"); + } + self.0.click(id, name); + } + + /// No note is open. + pub fn expect_closed(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("editor-title")); + } + + /// Moves the caret to the end of the next line, inside its value. + pub fn go_to_line_end_below(&mut self) { + self.0.press(Shortcut::Down); + self.0.press(Shortcut::LineEnd); + self.0.press(Shortcut::Left); + self.0.press(Shortcut::Left); + } + + /// Puts the caret at the start of the code. + pub fn go_to_start(&mut self) { + self.0.take_keyboard("editor-body", "the note's text"); + self.0.press(Shortcut::TextStart); + } +} + +/// The text the code holds. +fn held(tree: &Tree) -> String { + tree.find("editor-body").and_then(Node::value).unwrap_or_default().to_owned() +} + +/// What the format's notice is about. +fn notice(tree: &Tree) -> Option<&str> { + tree.find("editor-format-notice").and_then(Node::description) +} diff --git a/e2e/src/sdk/environments.rs b/e2e/src/sdk/environments.rs new file mode 100644 index 000000000..bcbbb80c8 --- /dev/null +++ b/e2e/src/sdk/environments.rs @@ -0,0 +1,106 @@ +use egui::accesskit::Node; + +use super::App; +use crate::driver::{Tree, said}; + +/// The environments requests are sent with: their page, and the menu that chooses one. +pub struct Environments<'a>(pub(super) &'a mut App); + +impl Environments<'_> { + /// Opens their page, from the menu of the environments. + pub fn open(&mut self) { + self.0.click("http-environment-picker", "the menu of the environments"); + self.0.click("http-environment-manage", "« Manage »"); + self.0.expect("the environments open", |tree| tree.has("http-environments")); + } + + /// Goes back to the requests. + pub fn leave(&mut self) { + self.0.click("http-environments-open", "« Environments » in the rail"); + self.0.expect("the requests are back", |tree| !tree.has("http-environments")); + } + + /// Makes an environment. + pub fn create(&mut self, name: &str) { + self.0.click("http-environment-create-open", "« New environment »"); + self.0.fill("http-environment-create-input", "its name", name); + self.0.click("http-environment-create-submit", "« Create »"); + self.0.expect("it is shown", |tree| { + tree.find("http-environment-name").and_then(Node::value) == Some(name) + }); + } + + /// Gives the environment shown another colour, counted from 0. + pub fn choose_colour(&mut self, n: usize) { + self.0.click_nth("http-environment-colour", n, "a colour"); + self.0.expect("the colour is chosen", |tree| { + let colours = tree.all("http-environment-colour"); + colours + .get(n) + .is_some_and(|colour| crate::driver::is_on(colour) || colour.is_selected() == Some(true)) + }); + } + + /// Adds a variable to what is shown. + pub fn add_variable(&mut self, name: &str, value: &str) { + let at = self.0.tree().count("http-variable-name") - 1; + self.0.fill_nth("http-variable-name", at, "the variable's name", name); + self.type_value(at, value); + } + + /// Adds a secret to the environment shown: its value is masked. + pub fn add_secret(&mut self, name: &str, value: &str) { + let at = self.0.tree().count("http-variable-name") - 1; + self.add_variable(name, value); + self.0.click_nth("http-variable-kind", at, "the variable's kind"); + self.0.click("http-variable-kind-2", "« Secret »"); + self.0.expect("its value is masked", |tree| { + tree.has("http-variable-reveal") && nth_value(tree, at).is_some_and(|held| held != value) + }); + } + + /// Types the value of the variable a *Set in…* made. + pub fn type_value_of(&mut self, name: &str, value: &str) { + let at = self.0.seen("the variable is in the table", |tree| { + let mut names = tree.all("http-variable-name").into_iter(); + names.position(|field| field.value() == Some(name)) + }); + self.type_value(at, value); + } + + /// Asks before a request that could change something leaves with the environment shown. + pub fn protect(&mut self) { + self.0.click("http-environment-protected", "« Protected »"); + self.0 + .expect("the page says what it changes", |tree| tree.has("http-environment-protected-note")); + } + + /// Chooses the environment the requests are sent with, from its menu. + pub fn choose(&mut self, name: &str) { + self.0.click("http-environment-picker", "the menu of the environments"); + self.0 + .click_where("http-environment-option", "the environment in the menu", |option| { + said(option).contains(name) + }); + self.0.expect("it is the one chosen", |tree| { + tree.text("http-environment-picker").is_some_and(|said| said.contains(name)) + }); + } + + /// A variable of what is shown has this value, in clear. + pub fn expect_value(&mut self, value: &str, says: &str) { + self.0.expect(says, |tree| { + let mut values = tree.all("http-variable-value").into_iter(); + values.any(|field| field.value() == Some(value)) + }); + } + + fn type_value(&mut self, at: usize, value: &str) { + self.0.fill_nth("http-variable-value", at, "the variable's value", value); + self.0.expect("the value is typed", |tree| nth_value(tree, at) == Some(value)); + } +} + +fn nth_value(tree: &Tree, at: usize) -> Option<&str> { + tree.all("http-variable-value").get(at).copied().and_then(Node::value) +} diff --git a/e2e/src/sdk/fields.rs b/e2e/src/sdk/fields.rs new file mode 100644 index 000000000..83c46868f --- /dev/null +++ b/e2e/src/sdk/fields.rs @@ -0,0 +1,48 @@ +use super::{App, Shortcut}; + +/// The form that asks for a snippet's `{{fields}}` before it is copied. +pub struct Fields<'a>(pub(super) &'a mut App); + +impl Fields<'_> { + /// Types a field's value, over what it holds; the fields counted from 0, in the text's order. + pub fn type_value(&mut self, field: usize, value: &str) { + self.0.click_nth("placeholder-input", field, "the field of a value to fill"); + self.0.press(Shortcut::SelectAll); + self.0.type_text(value); + } + + /// *Copy as is*: the braces stay. + pub fn copy_as_is(&mut self) { + self.0.click("placeholder-copy-raw", "« Copy as is »"); + self.expect_closed("the form closes once the snippet is copied"); + } + + /// *Cancel*: nothing is kept. + pub fn cancel(&mut self) { + self.0.click("placeholder-cancel", "« Cancel »"); + self.expect_closed("the form closes"); + } + + /// Copies the snippet, filled. + pub fn copy(&mut self) { + self.0.press(Shortcut::Enter); + self.expect_closed("the form closes once the snippet is copied"); + } + + /// The form is open, the keyboard in its first field. + pub fn expect_open(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has_focus("placeholder-input")); + } + + /// A field holds this value. + pub fn expect_value(&mut self, field: usize, value: &str, says: &str) { + self.0.expect(says, |tree| { + let inputs = tree.all("placeholder-input"); + inputs.get(field).and_then(|input| input.value()) == Some(value) + }); + } + + fn expect_closed(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("placeholder-form-hint")); + } +} diff --git a/e2e/src/sdk/files.rs b/e2e/src/sdk/files.rs new file mode 100644 index 000000000..fb1f9545c --- /dev/null +++ b/e2e/src/sdk/files.rs @@ -0,0 +1,77 @@ +use std::path::{Path, PathBuf}; + +use super::App; +use crate::{current_step, server}; + +/// The person's own files, and what they answer to the system's file dialogs: no driver reaches the +/// dialog itself. +pub struct Files<'a>(pub(super) &'a mut App); + +impl Files<'_> { + /// Puts a file among the person's own. + pub fn put(&mut self, name: &str, bytes: &[u8]) { + std::fs::write(self.path(name), bytes).expect("the person's file is written"); + } + + /// Puts a picture of one pixel, a PNG, among the person's own files. + pub fn put_picture(&mut self, name: &str) { + self.put(name, server::PIXEL); + } + + /// Puts a file among the person's own: its path, as a script writes it. + pub fn put_apart(&mut self, name: &str, bytes: &[u8]) -> String { + self.put(name, bytes); + self.path(name).display().to_string().replace('\\', "/") + } + + /// Answers this file to the dialogs from now on: the one to read, or the one to write. + pub fn answer(&mut self, name: &str) { + let path = self.path(name).display().to_string(); + std::fs::write(answer(self.0.room.path()), path).expect("the dialog's answer is written"); + } + + /// A file was written, and its bytes are what `holds` accepts. + pub fn expect(&mut self, name: &str, says: &str, holds: impl Fn(&[u8]) -> bool) { + let path = self.path(name); + self.0.expect(says, |_| std::fs::read(&path).is_ok_and(|bytes| holds(&bytes))); + } + + /// No file was written there. + pub fn expect_none(&mut self, name: &str, says: &str) { + assert!(!self.path(name).exists(), "« {} »: {says}", current_step()); + } + + /// A file was written, the same as another. + pub fn expect_same(&mut self, name: &str, as_name: &str, says: &str) { + let wanted = std::fs::read(self.path(as_name)).expect("the other file is read"); + self.expect(name, says, |bytes| bytes == wanted); + } + + /// What a file holds, once it is written. + pub(super) fn read(&mut self, name: &str, says: &str) -> Vec { + let path = self.path(name); + self.0 + .seen(says, |_| std::fs::read(&path).ok().filter(|bytes| !bytes.is_empty())) + } + + /// Where a file of the person's own is. + fn path(&self, name: &str) -> PathBuf { + self.0.room.path().join("files").join(name) + } +} + +/// Writes over the pages of the one library's database, its header left: a file SQLite opens, and +/// refuses to read. +pub(super) fn damage_library(profile: &Path) { + let libraries = std::fs::read_dir(profile.join("libraries")).expect("the profile has a library"); + let library = libraries.flatten().next().expect("the profile has a library"); + let database = library.path().join("devnotes.sqlite3"); + let mut bytes = std::fs::read(&database).expect("the database is read"); + bytes[100..].fill(0x5a); + std::fs::write(&database, bytes).expect("the damaged database is written"); +} + +/// Where the dialogs read their answer. +pub(super) fn answer(room: &Path) -> PathBuf { + room.join("dialog-answer.txt") +} diff --git a/e2e/src/sdk/filters.rs b/e2e/src/sdk/filters.rs new file mode 100644 index 000000000..d30669484 --- /dev/null +++ b/e2e/src/sdk/filters.rs @@ -0,0 +1,172 @@ +use super::{App, Kind, Shortcut}; +use crate::driver::said; + +/// The header's filters: their menus, and the order of the cards. +pub struct Filters<'a>(pub(super) &'a mut App); + +/// A menu of the filters. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FilterMenu { + Type, + Priority, + Tags, + Format, +} + +/// What the cards are sorted by. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SortBy { + Modified, + Priority, + Format, + Title, +} + +/// What the cards are grouped by. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GroupBy { + Date, + Priority, + Format, + Nothing, +} + +impl Filters<'_> { + /// Shows the band of the filters' menus, or puts it away. + pub fn flip_band(&mut self) { + self.0.click("facets-toggle", "the filters' button"); + } + + /// Opens a menu of the band. + pub fn open(&mut self, menu: FilterMenu) { + let (id, name) = trigger(menu); + self.0.click(id, name); + } + + /// Closes the menu open. + pub fn close_menu(&mut self) { + self.0.press(Shortcut::Escape); + self.0 + .expect("the menu closes", |tree| MENUS.iter().all(|value| !tree.has(value))); + } + + /// Ticks or unticks a kind, in its menu. + pub fn tick_kind(&mut self, kind: Kind) { + self.0.click(kind_chip(kind), "the kind in the menu"); + } + + /// Ticks or unticks the urgent priority, in its menu. + pub fn tick_urgent(&mut self) { + self.0.click("priority-chip-urgent", "« Urgent » in the menu"); + } + + /// Ticks or unticks a tag, in its menu. + pub fn tick_tag(&mut self, tag: &str) { + self.0 + .click_where("tag-pill", "the tag in the menu", |value| said(value).contains(tag)); + } + + /// Ticks or unticks a format, in its menu, by the name it goes by. + pub fn tick_format(&mut self, format: &str) { + self.0 + .click_where("language-chip", "the format in the menu", |value| said(value) == format); + } + + /// *Manage the tags…*, at the foot of their menu. + pub fn manage_tags(&mut self) { + self.0.click("tag-manage", "« Manage the tags… »"); + self.0.expect("the tags are listed", |tree| tree.has("tag-manager-close")); + } + + /// *Clear the filters*, which takes the search with them. + pub fn clear(&mut self) { + self.0.click("clear-filters", "« Clear the filters »"); + } + + /// Sorts the cards. + pub fn sort_by(&mut self, key: SortBy) { + let at = match key { + SortBy::Modified => 0, + SortBy::Priority => 2, + SortBy::Format => 3, + SortBy::Title => 4, + }; + self.order("sort-key", at, "an order of the cards"); + } + + /// Groups the cards. + pub fn group_by(&mut self, grouping: GroupBy) { + let at = match grouping { + GroupBy::Date => 0, + GroupBy::Priority => 1, + GroupBy::Format => 2, + GroupBy::Nothing => 3, + }; + self.order("sort-grouping", at, "a grouping of the cards"); + } + + /// Turns *Pinned first* over. + pub fn flip_pinned_first(&mut self) { + self.order("sort-pinned-first", 0, "« Pinned first »"); + } + + /// The band says how many values are ticked, over all its menus. + pub fn expect_ticked(&mut self, count: usize, says: &str) { + let count = count.to_string(); + self.0 + .expect(says, |tree| tree.text("facets-count").as_deref() == Some(count.as_str())); + } + + /// No value is ticked, and nothing is left to clear. + pub fn expect_none(&mut self, says: &str) { + self.0 + .expect(says, |tree| !tree.has("facets-count") && !tree.has("clear-filters")); + } + + /// A menu says how many of its values are ticked. + pub fn expect_menu_counting(&mut self, menu: FilterMenu, ticked: usize, says: &str) { + let (id, _) = trigger(menu); + let ticked = ticked.to_string(); + self.0 + .expect(says, |tree| tree.text(id).is_some_and(|name| name.contains(&ticked))); + } + + /// The cards are in one list, under no heading of their own. + pub fn expect_one_list(&mut self, says: &str) { + self.0.expect(says, |tree| tree.count("note-section") <= 1); + } + + /// The cards are in at least so many groups. + pub fn expect_several_groups(&mut self, says: &str) { + self.0.expect(says, |tree| tree.count("note-section") > 1); + } + + fn order(&mut self, id: &str, n: usize, name: &str) { + self.0.click("sort-trigger", "the order's menu"); + self.0.click_nth(id, n, name); + self.0.press(Shortcut::Escape); + self.0.expect("the menu closes", |tree| !tree.has("sort-key")); + } +} + +/// A value of each menu: what is on the screen while it is open. +const MENUS: [&str; 5] = ["kind-chip-all", "priority-chip-all", "tag-all", "language-all", "tag-manage"]; + +fn trigger(menu: FilterMenu) -> (&'static str, &'static str) { + match menu { + FilterMenu::Type => ("facet-menu-kind", "the « Type » menu"), + FilterMenu::Priority => ("facet-menu-priority", "the « Priority » menu"), + FilterMenu::Tags => ("facet-menu-tag", "the « Tags » menu"), + FilterMenu::Format => ("facet-menu-language", "the « Format » menu"), + } +} + +fn kind_chip(kind: Kind) -> &'static str { + match kind { + Kind::Note => "kind-chip-note", + Kind::Snippet => "kind-chip-snippet", + Kind::TodoList => "kind-chip-checklist", + Kind::Calculation => "kind-chip-calc", + Kind::Drawing => "kind-chip-drawing", + } +} diff --git a/e2e/src/sdk/gate.rs b/e2e/src/sdk/gate.rs new file mode 100644 index 000000000..d9e7e5773 --- /dev/null +++ b/e2e/src/sdk/gate.rs @@ -0,0 +1,153 @@ +use egui::accesskit::Node; + +use super::App; +use crate::driver::Tree; + +/// The gate: a phrase makes the library, then opens it. +pub struct Gate<'a>(pub(super) &'a mut App); + +impl Gate<'_> { + /// Types the phrase twice and makes the library, its sample notes on the screen. + pub fn create_library(&mut self, phrase: &str) { + self.type_phrase(phrase); + self.confirm_phrase(phrase); + self.submit(); + self.expect_open("the new library opens"); + } + + /// Types the phrase and opens the library. + pub fn unlock(&mut self, phrase: &str) { + self.try_phrase(phrase); + self.expect_open("the phrase opens the library"); + } + + /// Types a phrase and tries it, whatever it opens. + pub fn try_phrase(&mut self, phrase: &str) { + self.type_phrase(phrase); + self.submit(); + } + + /// Types in the phrase's field, at the end of what it holds. ⚠️ The gate moves down when its + /// libraries are listed: a click aimed before lands beside the field. + pub fn type_phrase(&mut self, phrase: &str) { + self.0.expect("the gate lists its libraries", |tree| tree.has("vault-library")); + self.0.fill("vault-passphrase", "the passphrase's field", phrase); + } + + /// Types in the confirmation's field, at the end of what it holds. + pub fn confirm_phrase(&mut self, phrase: &str) { + self.0.fill("vault-confirmation", "the confirmation's field", phrase); + } + + /// Clicks the button that makes or opens the library. + pub fn submit(&mut self) { + self.0.click_until( + "the gate's button", + |app| app.click("vault-submit", "the gate's button"), + answered, + ); + } + + /// Has the gate open another library of the profile. + pub fn choose_library(&mut self, name: &str) { + self.0.click("vault-library-switch", "the menu of the libraries"); + let option = self.0.seen("the library in the menu", |tree| { + let option = tree.named("vault-library-switch-", name)?; + option.author_id().map(str::to_owned) + }); + self.0.click(&option, "the library in the menu"); + self.expect_library(name, "the gate asks for that one"); + } + + /// *Forgotten your passphrase?*: what it would do is said. + pub fn forget(&mut self) { + self.0.click("vault-forgotten", "« Forgotten your passphrase? »"); + self.0.expect("what would be lost is said", |tree| { + tree.has("vault-archive") && !tree.has("vault-passphrase") + }); + } + + /// Goes back to the phrase, nothing touched. + pub fn keep_trying(&mut self) { + self.0.click("vault-keep-trying", "the way back"); + self.expect_phrase_asked("the phrase is asked again"); + } + + /// Archives the library whose phrase is forgotten. + pub fn archive(&mut self) { + self.0.click("vault-archive-confirm", "the button that archives it"); + } + + /// Sets the damaged library aside. + pub fn set_aside(&mut self) { + self.0.click("vault-set-aside", "« Set it aside and start fresh »"); + } + + /// The gate asks for the phrase of this library. + pub fn expect_library(&mut self, name: &str, says: &str) { + self.0 + .expect(says, |tree| tree.find("vault-library-switch").and_then(Node::value) == Some(name)); + } + + /// The gate says the library is damaged, and starts nothing on it. + pub fn expect_damaged(&mut self, says: &str) { + self.0.expect(says, |tree| { + tree.has("vault-damaged") && tree.has("vault-set-aside") && !tree.has("area-switch") + }); + } + + /// The place something was put in is told. + pub fn expect_place_told(&mut self, words: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("status-toast").iter().any(|said| said.contains(words))); + } + + /// The gate asks for a phrase twice: this profile has no library yet. + pub fn expect_new_phrase_asked(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("vault-confirmation") && !tree.has("area-switch")); + } + + /// The gate asks for the library's phrase, once. + pub fn expect_phrase_asked(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("vault-passphrase") && !tree.has("vault-confirmation")); + } + + /// The phrases typed cannot be chosen: the button is out of reach. + pub fn expect_phrase_refused(&mut self, says: &str) { + self.0.expect(says, |tree| tree.is_disabled("vault-submit")); + } + + /// The gate says the two phrases differ: the button is out of reach. + pub fn expect_phrases_differ(&mut self, says: &str) { + self.0.expect(says, |tree| { + tree.text("vault-problem").is_some_and(|said| !said.is_empty()) + && tree.is_disabled("vault-submit") + }); + } + + /// The gate says the phrase is not the library's, which stays shut. + pub fn expect_wrong_phrase(&mut self, says: &str) { + self.0.expect(says, |tree| { + tree.text("vault-problem").is_some_and(|said| !said.is_empty()) && !tree.has("area-notes") + }); + } + + /// The check for a new version answered, and the gate offers none. + pub fn expect_no_update(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("update-dot")); + self.0.expect_at_rest(says, |tree| !tree.has("gate-update")); + } + + fn expect_open(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("area-switch")); + } +} + +/// The gate is opening the library, or says why it does not. +fn answered(tree: &Tree) -> bool { + !tree.has("vault-submit") + || tree.is_disabled("vault-submit") + || tree.text("vault-problem").is_some_and(|said| !said.is_empty()) +} diff --git a/e2e/src/sdk/help.rs b/e2e/src/sdk/help.rs new file mode 100644 index 000000000..015c6aab8 --- /dev/null +++ b/e2e/src/sdk/help.rs @@ -0,0 +1,126 @@ +use super::{App, Shortcut}; + +/// The *About* menu and what it opens. +pub struct Help<'a>(pub(super) &'a mut App); + +/// The documentation's pages, under their four headings. +const DOCUMENTATION: [&str; 11] = [ + "overview", + "start", + "writing", + "organising", + "paste", + "tools", + "api", + "safety", + "transfer", + "settings", + "faq", +]; + +impl Help<'_> { + /// *About → Documentation*. + pub fn open_documentation(&mut self) { + self.choose("about-documentation", "« Documentation »"); + } + + /// *About → Keyboard shortcuts*. + pub fn open_shortcuts(&mut self) { + self.choose("about-shortcuts", "« Keyboard shortcuts »"); + } + + /// *About → What's new*. + pub fn open_whats_new(&mut self) { + self.choose("about-whats-new", "« What's new »"); + } + + /// *About → About DevNotes*. + pub fn open_about(&mut self) { + self.choose("about-about", "« About DevNotes »"); + } + + /// *About → Check for updates*, or the version already found. + pub fn check_for_updates(&mut self) { + self.choose("about-check-updates", "« Check for updates »"); + } + + /// *Later*, in the offer of a new version. + pub fn update_later(&mut self) { + self.0.click("update-later", "« Later »"); + self.0.expect("the offer closes", |tree| !tree.has("update-prompt")); + } + + /// Ticks *Do not offer version … again*, then *Later*. + pub fn skip_update(&mut self) { + self.0.click("update-skip", "« Do not offer this version again »"); + self.update_later(); + } + + /// Closes the panel that is open. + pub fn close(&mut self) { + self.0.press(Shortcut::Escape); + self.0 + .expect("the panel closes", |tree| PANELS.iter().all(|panel| !tree.has(panel))); + } + + /// The documentation lists its pages, and reads one. + pub fn expect_documentation(&mut self, says: &str) { + self.0.expect(says, |tree| { + let pages = tree.all_starting("docs-page-"); + let mut listed: Vec<&str> = pages.iter().map(|id| &id["docs-page-".len()..]).collect(); + listed.sort_unstable(); + let mut known = DOCUMENTATION; + known.sort_unstable(); + listed == known && tree.text("docs-title").is_some_and(|title| !title.is_empty()) + }); + } + + /// Each page of the documentation is one of reading: a title, and sections under it. The + /// overview alone is of cards, one per page. From the last to the first: a page's sections + /// unfold under it, and push the pages below out of view. + pub fn expect_every_page_read(&mut self, says: &str) { + for page in DOCUMENTATION.into_iter().rev() { + self.0.click(&format!("docs-page-{page}"), "a page of the documentation"); + self.0.expect(says, |tree| { + let sections = tree.all_starting("docs-section-").len(); + let cards = tree.all_starting("docs-card-").len(); + if page == "overview" { cards == DOCUMENTATION.len() - 1 } else { sections > 1 && cards == 0 } + }); + } + } + + /// The version of the application is said. + pub fn expect_version(&mut self, says: &str) { + let version = format!("v{}", env!("CARGO_PKG_VERSION")); + self.0 + .expect(says, |tree| tree.text("about-version").as_deref() == Some(version.as_str())); + } + + /// The shortcuts are listed, group by group. + pub fn expect_shortcuts(&mut self, says: &str) { + self.0.expect(says, |tree| tree.count("shortcut-group") > 1); + } + + /// The changelog is read, release by release. + pub fn expect_changelog(&mut self, says: &str) { + self.0.expect(says, |tree| tree.count("news-version") > 1); + } + + /// A new version is offered, its notes with it. + pub fn expect_update_offered(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("update-prompt") && tree.has("update-notes")); + } + + /// The menu wears its dot: a new version is known. + pub fn expect_update_known(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("update-dot") && !tree.has("update-prompt")); + } + + fn choose(&mut self, id: &str, name: &str) { + self.0.click("about-open", "the « About » menu"); + self.0.click(id, name); + } +} + +const PANELS: [&str; 4] = ["docs-dialog", "about-dialog", "shortcut-group", "news-version"]; diff --git a/e2e/src/sdk/history.rs b/e2e/src/sdk/history.rs new file mode 100644 index 000000000..bd486c56c --- /dev/null +++ b/e2e/src/sdk/history.rs @@ -0,0 +1,42 @@ +use super::App; + +/// The versions of the note open. +pub struct History<'a>(pub(super) &'a mut App); + +impl History<'_> { + /// Opens the list of versions. + pub fn open(&mut self) { + self.0.click("revisions-toggle", "« History »"); + self.0.expect("the versions are listed", |tree| tree.has("revision-open")); + } + + /// Looks at what going back to a version would change, the newest counted 0. + pub fn look_at(&mut self, version: usize) { + self.0.click_nth("revision-open", version, "the version"); + self.0.expect("what would change is shown", |tree| tree.has("revision-diff")); + } + + /// Goes back to the version looked at. + pub fn go_back(&mut self) { + self.0.click("revision-restore", "« Go back to this version »"); + } + + /// As many versions are kept. + pub fn expect_versions(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| tree.count("revision-open") == count); + } + + /// Going back would bring a line back, and drop another. + pub fn expect_change(&mut self, back: &str, dropped: &str, says: &str) { + self.0.expect(says, |tree| { + let holds = |id: &str, line: &str| tree.texts(id).iter().any(|shown| shown.contains(line)); + holds("diff-restored", back) && holds("diff-dropped", dropped) + }); + } + + /// The note has no version but its own. + pub fn expect_none(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("editor-title") && !tree.has("revisions-toggle")); + } +} diff --git a/e2e/src/sdk/http.rs b/e2e/src/sdk/http.rs new file mode 100644 index 000000000..1f4c8535c --- /dev/null +++ b/e2e/src/sdk/http.rs @@ -0,0 +1,288 @@ +use egui::accesskit::Node; +use egui::{Key, Modifiers, Pos2}; + +use super::{App, Shortcut}; +use crate::driver::{Tree, said, within}; + +/// The HTTP area: its rail, its tabs, its cookies, and what it asks before DevNotes quits. +pub struct Http<'a>(pub(super) &'a mut App); + +impl Http<'_> { + /// A collection, from the empty rail. + pub fn new_collection(&mut self, name: &str) { + self.0.click("http-rail-empty-create", "the button of a first collection"); + self.name_new(name); + } + + /// A folder in a collection, from its ⋯ menu. + pub fn new_folder(&mut self, parent: &str, name: &str) { + self.open_menu(parent); + self.0.click("http-node-new-folder", "« New folder »"); + self.name_new(name); + } + + /// A request in a collection or a folder, from its ⋯ menu. + pub fn new_request(&mut self, parent: &str, name: &str) { + self.new_of_kind(parent, "http-node-new-http", "« HTTP request »"); + self.name_new(name); + } + + /// A WebSocket in a collection or a folder, from its ⋯ menu. + pub fn new_socket(&mut self, parent: &str, name: &str) { + self.new_of_kind(parent, "http-node-new-websocket", "« WebSocket »"); + self.name_new(name); + } + + /// Clicks a row of the rail, which takes the keyboard: a request opens in its tab. + pub fn take_row(&mut self, name: &str) { + self.0 + .click_where("http-node-name", "the row in the rail", |node| is(node, name)); + } + + /// Opens a request from the rail. + pub fn open(&mut self, name: &str) { + self.take_row(name); + self.0.expect("the request opens", |tree| { + let shown = tree.find("http-request-name").and_then(Node::value); + tree.has("http-url") && shown == Some(name) + }); + } + + /// Folds a collection or a folder, or opens it. + pub fn fold(&mut self, name: &str) { + self.0 + .click_where("http-node-twisty", "the row's triangle", |node| said(node).ends_with(name)); + } + + /// Renames a row in place, by F2, the field left by a click elsewhere. + pub fn rename(&mut self, name: &str, into: &str) { + self.take_row(name); + self.0.key(Key::F2, Modifiers::NONE); + self.0.replace("http-rename-input", "the row's name", into); + self.0.click("http-rail-title", "the rail's title"); + self.expect_renamed(name, into); + } + + /// Renames a row in place, from its ⋯ menu, by Enter. + pub fn rename_from_the_menu(&mut self, name: &str, into: &str) { + self.open_menu(name); + self.0.click("http-node-rename", "« Rename »"); + self.0.replace("http-rename-input", "the row's name", into); + self.0.press(Shortcut::Enter); + self.expect_renamed(name, into); + } + + /// Asks for a row's deletion from its ⋯ menu: the rail asks before. + pub fn ask_deletion(&mut self, name: &str) { + self.open_menu(name); + self.0.click("http-node-delete", "« Delete »"); + self.0 + .expect("the rail asks before deleting", |tree| tree.has("http-delete-confirm")); + } + + /// Answers no to the deletion asked. + pub fn cancel_deletion(&mut self) { + self.0.click("http-delete-cancel", "« Cancel »"); + self.0.expect("the question goes", |tree| !tree.has("http-delete-confirm")); + } + + /// Answers yes to the deletion asked. + pub fn confirm_deletion(&mut self) { + self.0.click("http-delete-submit", "« Delete »"); + self.0.expect("the question goes", |tree| !tree.has("http-delete-confirm")); + } + + /// Has every request under a collection send a *Bearer* token and a header, in its *Settings…*. + pub fn set_below(&mut self, collection: &str, token: &str, (name, value): (&str, &str)) { + self.open_menu(collection); + self.0.click("http-node-settings", "« Settings… »"); + self.0.click("http-auth-kind", "the auth's menu"); + // A collection has nothing above it: « Inherited » is not offered. + self.0.click("http-auth-kind-2", "« Bearer »"); + self.0.fill("http-auth-secret", "the token", token); + let first = self.0.seen("the headers below", |tree| { + let table = tree.find("http-settings-headers-table").and_then(Node::bounds)?; + tree.all("http-kv-key").into_iter().position(|cell| within(cell, table)) + }); + self.0.fill_nth("http-kv-key", first, "the header", &format!("{name}: {value}")); + self.0.click("http-settings-save", "« Save »"); + self.0.expect("the settings close", |tree| !tree.has("http-settings-save")); + } + + /// Opens a draft in a tab of its own. + pub fn new_draft(&mut self) { + let tabs = self.0.tree().count("http-tab-open"); + self.0.click("http-tab-new", "the button of a new request"); + self.0.expect("a draft opens in its tab", |tree| { + tree.has("http-url") && tree.count("http-tab-open") == tabs + 1 + }); + } + + /// Opens a GraphQL draft in a tab of its own. + pub fn new_graphql_draft(&mut self) { + self.0.click("http-tab-new-kind", "the menu beside the new request"); + self.0.click("http-new-kind-graphql", "« GraphQL »"); + self.0.expect("a draft opens in its tab", |tree| tree.has("http-graphql-query")); + } + + /// Shows the tab of a request. + pub fn show_tab(&mut self, name: &str) { + self.0 + .click_where("http-tab-open", "the request's tab", |tab| is_tab(tab, name)); + self.0.expect("the request is shown", |tree| { + tree.find("http-request-name").and_then(Node::value) == Some(name) + }); + } + + /// Closes the last tab by its cross, its changes not kept. + pub fn close_last_tab_discarding(&mut self) { + let tabs = self.0.tree().count("http-tab-open"); + self.0.click_nth("http-tab-close", tabs - 1, "the last tab's cross"); + self.discard(tabs); + } + + /// Closes the last tab by the middle button, its changes not kept. + pub fn close_last_tab_with_the_middle_button(&mut self) { + let tabs = self.0.tree().count("http-tab-open"); + self.0.middle_click_nth("http-tab-open", tabs - 1, "the last tab"); + self.discard(tabs); + } + + /// Drags the first tab past the second. + pub fn drag_first_tab(&mut self) { + let nth = |n: usize| move |tree: &Tree| tree.all("http-tab-open").get(n).and_then(|tab| tab.bounds()); + let (from, to) = (self.0.place("the first tab", nth(0)), self.0.place("the second tab", nth(1))); + #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] + let at = |x: f64| Pos2::new(x as f32, f64::midpoint(from.y0, from.y1) as f32); + self.0.drag(at(from.x0 + 20.0), at(to.x1)); + } + + /// Opens the cookies kept. + pub fn open_cookies(&mut self) { + self.0.click("http-cookies-open", "« Cookies »"); + self.0.expect("the cookies are listed", |tree| tree.has("http-cookies-dialog")); + } + + /// Throws every cookie away, asked twice, and closes them. + pub fn throw_cookies_away(&mut self) { + self.0.click("http-cookies-clear", "« Clear »"); + self.0.click("http-cookies-clear-confirm", "« Clear » again"); + self.0.expect("no cookie is left", |tree| tree.has("http-cookies-empty")); + self.0.click("http-cookies-close", "the cookies' cross"); + self.0.expect("the cookies close", |tree| !tree.has("http-cookies-dialog")); + } + + /// Quits: DevNotes asks what becomes of the requests left with changes. + pub fn ask_to_quit(&mut self) { + self.0.driver.hand_over(Some("quit")); + self.expect_asked_about_changes(1, "DevNotes asks about the changes"); + } + + /// Stays, the changes as they are. + pub fn cancel_leaving(&mut self) { + self.0.click("http-leave-cancel", "« Cancel »"); + self.0.expect("the question goes", |tree| !tree.has("http-leave-dialog")); + } + + /// Saves every change, and DevNotes ends. + pub fn save_and_quit(&mut self) { + self.0.click("http-leave-save", "the button that saves"); + self.0.ended(); + } + + /// Leaves without the changes. + pub fn leave_without_saving(&mut self) { + self.0.click("http-leave-discard", "the button that does not save"); + } + + /// DevNotes asks what becomes of as many requests with changes. + pub fn expect_asked_about_changes(&mut self, count: usize, says: &str) { + self.0 + .expect(says, |tree| tree.has("http-leave-dialog") && tree.count("http-leave-name") == count); + } + + /// The rail lists these, top to bottom, a request after its method. + pub fn expect_rows(&mut self, rows: &[&str], says: &str) { + self.0.expect(says, |tree| tree.texts("http-node-name") == rows); + } + + /// The move just made is said, with these words in it. + pub fn expect_move_said(&mut self, words: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("http-rail-moved").is_some_and(|said| said.contains(words))); + } + + /// The deletion asked says what would go. + pub fn expect_deletion_counted(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("http-delete-count")); + } + + /// As many tabs are open. + pub fn expect_tabs(&mut self, count: usize, says: &str) { + self.0 + .expect(says, |tree| tree.has("http-rail-title") && tree.count("http-tab-open") == count); + } + + /// The tabs open are these, left to right. + pub fn expect_tabs_in_order(&mut self, names: &[&str], says: &str) { + self.0.expect(says, |tree| { + let tabs = tree.all("http-tab-open"); + tabs.len() == names.len() && tabs.iter().zip(names).all(|(tab, name)| is_tab(tab, name)) + }); + } + + /// This cookie is listed. + pub fn expect_cookie(&mut self, name: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("http-cookie").iter().any(|it| it == name)); + } + + /// Opens the ⋯ menu of a row. + pub(super) fn open_menu(&mut self, name: &str) { + self.0 + .click_where("http-node-menu", "the row's « ⋯ »", |menu| said(menu).ends_with(name)); + } + + fn new_of_kind(&mut self, parent: &str, id: &str, name: &str) { + self.open_menu(parent); + self.0.click("http-node-new", "« New »"); + self.0.click(id, name); + } + + /// Names what is being made in the rail. + fn name_new(&mut self, name: &str) { + self.0.fill("http-create-input", "the new one's name", name); + self.0.press(Shortcut::Enter); + self.0.expect("it is in the rail", |tree| has_row(tree, name)); + } + + fn expect_renamed(&mut self, name: &str, into: &str) { + self.0 + .expect("the row has its new name", |tree| has_row(tree, into) && !has_row(tree, name)); + } + + fn discard(&mut self, tabs: usize) { + self.0.click("http-close-discard", "« Do not save »"); + self.0.expect("the tab closes", |tree| { + !tree.has("http-close-dialog") && tree.count("http-tab-open") + 1 == tabs + }); + } +} + +fn has_row(tree: &Tree, name: &str) -> bool { + tree.all("http-node-name").into_iter().any(|row| is(row, name)) +} + +/// A row says its name, a request's after its method. +fn is(row: &Node, name: &str) -> bool { + named(&said(row), name) +} + +/// A tab says its method, its name, then whether it has changes. +fn is_tab(tab: &Node, name: &str) -> bool { + named(said(tab).split(',').next().unwrap_or_default(), name) +} + +fn named(said: &str, name: &str) -> bool { + said == name || said.split_once(' ').is_some_and(|(_, rest)| rest == name) +} diff --git a/e2e/src/sdk/json.rs b/e2e/src/sdk/json.rs new file mode 100644 index 000000000..ec1ad0445 --- /dev/null +++ b/e2e/src/sdk/json.rs @@ -0,0 +1,119 @@ +use egui::accesskit::Node; + +use super::App; + +/// A JSON snippet explored: its graph, its tree, and what is selected in them. An entry is named by +/// its path, as `$.owner.team`. +pub struct Json<'a>(pub(super) &'a mut App); + +/// How a JSON snippet is looked at. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum JsonView { + Code, + Graph, + Tree, +} + +impl Json<'_> { + /// Shows the snippet as its code, its graph or its tree. + pub fn show_as(&mut self, view: JsonView) { + match view { + JsonView::Code => self.0.click("editor-view-code", "the « Code » view"), + JsonView::Graph => self.0.click("editor-view-graph", "the « Graph » view"), + JsonView::Tree => self.0.click("editor-view-tree", "the « Tree » view"), + } + } + + /// Puts the code and the graph side by side, or one at a time again. + pub fn flip_side_by_side(&mut self) { + self.0.click("editor-side-by-side", "« Side by side »"); + } + + /// Brings the whole graph in view. + pub fn fit(&mut self) { + self.0.click("json-fit", "the button that shows the whole graph"); + } + + /// Selects a node of the graph. + pub fn select(&mut self, path: &str) { + self.0 + .click_where("json-node-head", "the node of the graph", |node| at(node, path)); + } + + /// Folds or opens a container of the tree. + pub fn flip_in_the_tree(&mut self, path: &str) { + self.0.click_where("json-line", "the line of the tree", |node| at(node, path)); + } + + /// Selects an entry of the tree. + pub fn select_in_the_tree(&mut self, path: &str) { + self.flip_in_the_tree(path); + self.expect_selected(path, "the entry is selected"); + } + + /// The tree lists this entry. + pub fn expect_listed(&mut self, path: &str, says: &str) { + self.0 + .expect(says, |tree| tree.all("json-line").into_iter().any(|line| at(line, path))); + } + + /// Opens every node. + pub fn open_all(&mut self) { + self.0.click("json-open-all", "« Open all »"); + } + + /// Folds every node. + pub fn collapse_all(&mut self) { + self.0.click("json-collapse-all", "« Collapse all »"); + } + + /// Searches a word in the document. + pub fn search(&mut self, word: &str) { + self.0.replace("json-search", "the document's search", word); + } + + /// Goes to the next match. + pub fn next_match(&mut self) { + self.0.click("json-match-next", "the next match's arrow"); + } + + /// Shows what is selected in the code. + pub fn show_in_code(&mut self) { + self.0.click("json-show-in-code", "« Show in the code »"); + } + + /// The graph draws this many nodes. + pub fn expect_nodes(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| tree.count("json-node-head") == count); + } + + /// This entry is selected, its path said. + pub fn expect_selected(&mut self, path: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("json-selected-path").as_deref() == Some(path)); + } + + /// The search counts its matches. + pub fn expect_matches(&mut self, count: usize, says: &str) { + let count = count.to_string(); + self.0 + .expect(says, |tree| tree.text("json-match-count").as_deref() == Some(count.as_str())); + } + + /// A container of the tree is folded. + pub fn expect_folded_in_the_tree(&mut self, path: &str, says: &str) { + self.0.expect(says, |tree| { + let mut lines = tree.all("json-line").into_iter(); + lines.any(|line| at(line, path) && line.is_expanded() == Some(false)) + }); + } + + /// The code stands beside the graph, or not. + pub fn expect_side_by_side(&mut self, beside: bool, says: &str) { + self.0.expect(says, |tree| tree.has("side-by-side") == beside); + } +} + +fn at(node: &Node, path: &str) -> bool { + node.description() == Some(path) +} diff --git a/e2e/src/sdk/libraries.rs b/e2e/src/sdk/libraries.rs new file mode 100644 index 000000000..d64b214e4 --- /dev/null +++ b/e2e/src/sdk/libraries.rs @@ -0,0 +1,105 @@ +use egui::accesskit::{Node, Rect}; + +use super::{App, Shortcut}; +use crate::driver::Tree; + +/// The libraries of the profile: *File → Libraries…*. +pub struct Libraries<'a>(pub(super) &'a mut App); + +impl Libraries<'_> { + /// Opens the panel. + pub fn open(&mut self) { + self.0.click("file-menu", "the « File » menu"); + self.0.click("file-libraries", "« Libraries… »"); + self.0.expect("the libraries are listed", |tree| tree.has("library-row")); + } + + /// Closes it. + pub fn close(&mut self) { + self.0.click("libraries-close", "the panel's cross"); + self.0.expect("the panel closes", |tree| !tree.has("library-row")); + } + + /// Makes a library: the gate asks for its phrase. + pub fn create(&mut self, name: &str) { + self.0.fill("library-new-name", "the new library's name", name); + self.0.click("library-create", "« Create »"); + self.0.gate().expect_new_phrase_asked("the gate asks for its phrase"); + } + + /// Renames the open library. + pub fn rename_the_open_one(&mut self, into: &str) { + let line = self.0.place("the open library", open_line); + self.click_on(line, "library-start-rename", "« Rename »"); + self.0.replace("library-rename", "the library's name", into); + self.0.press(Shortcut::Enter); + self.0.expect("the library has its new name", |tree| { + !tree.has("library-rename") && line_of(tree, into).is_some() + }); + } + + /// Asks to open another library. + pub fn switch_to(&mut self, name: &str) { + let line = self.line(name); + self.click_on(line, "library-switch", "« Switch »"); + } + + /// Asks to delete a library, named before anything goes. + pub fn ask_deletion(&mut self, name: &str) { + let line = self.line(name); + self.click_on(line, "library-delete", "« Delete »"); + self.0.expect("the deletion names the library", |tree| { + tree.text("library-confirm").is_some_and(|said| said.contains(name)) + }); + } + + /// Answers no to the deletion asked. + pub fn cancel_deletion(&mut self) { + self.0.click("library-cancel-delete", "« Cancel »"); + self.0.expect("the question goes", |tree| !tree.has("library-confirm")); + } + + /// Answers yes to the deletion asked. + pub fn confirm_deletion(&mut self) { + let listed = self.0.tree().count("library-row"); + self.0.click("library-confirm-delete", "« Delete »"); + self.0.expect("the library is gone", |tree| { + tree.count("library-row") + 1 == listed && !tree.has("library-confirm") + }); + } + + /// As many libraries are listed. + pub fn expect_listed(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| tree.count("library-row") == count); + } + + /// The open library cannot be deleted. + pub fn expect_open_one_kept(&mut self, says: &str) { + let line = self.0.place("the open library", open_line); + self.0 + .expect(says, |tree| !tree.all("library-delete").into_iter().any(|button| on(button, line))); + } + + fn line(&mut self, name: &str) -> Rect { + self.0.place("the library in the list", |tree| line_of(tree, name)) + } + + fn click_on(&mut self, line: Rect, id: &str, name: &str) { + self.0.click_where(id, name, |button| on(button, line)); + } +} + +/// Where a library's name stands in the list. +fn line_of(tree: &Tree, name: &str) -> Option { + tree.saying(name).and_then(Node::bounds) +} + +fn open_line(tree: &Tree) -> Option { + tree.find("library-open").and_then(Node::bounds) +} + +/// Whether a button stands on a line, whose words are less high. +fn on(button: &Node, line: Rect) -> bool { + let middle = f64::midpoint(line.y0, line.y1); + button.bounds().is_some_and(|bounds| (bounds.y0..bounds.y1).contains(&middle)) +} diff --git a/e2e/src/sdk/mod.rs b/e2e/src/sdk/mod.rs new file mode 100644 index 000000000..bf2f830f2 --- /dev/null +++ b/e2e/src/sdk/mod.rs @@ -0,0 +1,518 @@ +//! What a person does with the application, area by area. Each method waits until the window can +//! take its act and until it has taken it: a journey never waits on its own. + +mod act; +mod attachments; +mod board; +mod calc; +mod clipboard; +mod code; +mod drawing; +mod editor; +mod environments; +mod fields; +mod files; +mod filters; +mod gate; +mod help; +mod history; +mod http; +mod json; +mod libraries; +mod notes; +mod palette; +mod prefs; +mod rail; +mod request; +mod response; +mod rich; +mod runner; +mod security; +mod selection; +mod sends; +mod shortcut; +mod socket; +mod tags; +mod todo; +mod tools; +mod transfer; +mod trash; +mod tray; +mod window; + +pub use attachments::Attachments; +pub use board::{Board, Place}; +pub use calc::Calc; +pub use clipboard::Clipboard; +pub use code::Code; +pub use drawing::{Drawing, Spot, Tool}; +pub use editor::Editor; +pub use egui::Key; +pub use environments::Environments; +pub use fields::Fields; +pub use files::Files; +pub use filters::{FilterMenu, Filters, GroupBy, SortBy}; +pub use gate::Gate; +pub use help::Help; +pub use history::History; +pub use http::Http; +pub use json::{Json, JsonView}; +pub use libraries::Libraries; +pub use notes::{Kind, Named, Notes, QuickFilter, Sample}; +pub use palette::Palette; +pub use prefs::{CardKey, DefaultKind, Density, Indent, Language, Page, Prefs, Switch, Theme}; +pub use rail::Rail; +pub use request::{Auth, Body, Method, Request, Script}; +pub use response::{BodyView, Part, Response}; +pub use rich::{DrawingSize, Presentation, Rich, RichTool}; +pub use runner::Runner; +pub use security::Security; +pub use selection::Selection; +pub use sends::Sends; +pub use shortcut::Shortcut; +pub use socket::Socket; +pub use tags::Tags; +pub use todo::Todo; +pub use tools::{Copied, Given, Tools}; +pub use transfer::{Export, Transfer}; +pub use trash::Trash; +pub use tray::{Tray, TrayEntry}; +pub use window::{Area, Window}; + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use egui::{Event, Modifiers}; +use tempfile::TempDir; + +use crate::driver::Driver; +use crate::{PASSPHRASE, current_step, server}; + +/// DevNotes as a person has it in front of them, on a profile of the journey's own. +pub struct App { + driver: Driver, + /// The profile, the person's files and the terminal's lines: gone once the application is. + room: TempDir, + /// When the last click was. + clicked: Option, + /// How many times the window had gone out of sight before it last did. + put_away: u32, + /// The journey widened the window: a launch again does too, the system having fitted it to its + /// screen. + wide: bool, + /// The bus the tray is served on. + #[cfg(target_os = "linux")] + session: Option, +} + +/// What a person asks of DevNotes from anywhere, by a key of the whole machine. A second launch +/// stands for the key, which no driver presses. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Global { + Palette, + NewNote, + PasteFromClipboard, +} + +impl App { + /// DevNotes launched for the first time: nothing on the disk, the gate on the screen. + pub fn first_launch(journey: &'static str) -> Self { + Self::launch(journey, Vec::new()) + } + + /// DevNotes with its library made and open on its sample notes: where a journey starts. + pub fn open(journey: &'static str) -> Self { + Self::launch(journey, Vec::new()).with_a_library() + } + + /// As `open`, a new version published on a server of the journey's own. + pub fn open_before_an_update(journey: &'static str) -> Self { + let served = server::publish_update(); + Self::launch(journey, vec![(platform::updater::E2E_UPDATES, served.into())]).with_a_library() + } + + /// As `open`, the tray on a bus of the journey's own under Linux. + pub fn open_with_a_tray(journey: &'static str) -> Self { + #[cfg(target_os = "linux")] + { + let session = tray::linux::Session::start(); + let bus = vec![("DBUS_SESSION_BUS_ADDRESS", session.address.clone().into())]; + let mut app = Self::launch(journey, bus); + app.session = Some(session); + app.with_a_library() + } + #[cfg(not(target_os = "linux"))] + Self::open(journey) + } + + /// DevNotes launched on a profile that outlives it, for a measure: the gate on the screen. + pub fn launch_on(profile: &Path) -> Self { + Self::start("measure", room(), profile.to_owned(), Vec::new()) + } + + fn launch(journey: &'static str, set: Vec<(&'static str, OsString)>) -> Self { + let room = room(); + let profile = room.path().join("profile"); + std::fs::create_dir(&profile).expect("the journey's profile is made"); + Self::start(journey, room, profile, set) + } + + fn start( + journey: &'static str, + room: TempDir, + profile: PathBuf, + mut set: Vec<(&'static str, OsString)>, + ) -> Self { + set.push((platform::dialog::E2E_DIALOG, files::answer(room.path()).into())); + let driver = Driver::launch(journey, profile, terminal(room.path()), set); + App { + driver, + room, + clicked: None, + put_away: 0, + wide: false, + #[cfg(target_os = "linux")] + session: None, + } + } + + fn with_a_library(mut self) -> Self { + self.gate().create_library(PASSPHRASE); + self.notes().expect_samples("the sample notes are on the screen"); + self + } + + /// The gate, where a library is made or opened. + pub fn gate(&mut self) -> Gate<'_> { + Gate(self) + } + + /// The notes area: its rail, its header and its cards. + pub fn notes(&mut self) -> Notes<'_> { + Notes(self) + } + + /// The rail of the notes: its spaces and their folders. + pub fn rail(&mut self) -> Rail<'_> { + Rail(self) + } + + /// The board of the space shown. + pub fn board(&mut self) -> Board<'_> { + Board(self) + } + + /// The header's filters, and the order of the cards. + pub fn filters(&mut self) -> Filters<'_> { + Filters(self) + } + + /// The cards ticked together. + pub fn selection(&mut self) -> Selection<'_> { + Selection(self) + } + + /// The manager of the library's tags. + pub fn tags(&mut self) -> Tags<'_> { + Tags(self) + } + + /// The note open. + pub fn editor(&mut self) -> Editor<'_> { + Editor(self) + } + + /// The Note open, written formatted. + pub fn rich(&mut self) -> Rich<'_> { + Rich(self) + } + + /// The Note open, presented. + pub fn presentation(&mut self) -> Presentation<'_> { + Presentation(self) + } + + /// The todo list open. + pub fn todo(&mut self) -> Todo<'_> { + Todo(self) + } + + /// The calculation open. + pub fn calc(&mut self) -> Calc<'_> { + Calc(self) + } + + /// The drawing open. + pub fn drawing(&mut self) -> Drawing<'_> { + Drawing(self) + } + + /// The files attached to the note open. + pub fn attachments(&mut self) -> Attachments<'_> { + Attachments(self) + } + + /// The versions of the note open. + pub fn history(&mut self) -> History<'_> { + History(self) + } + + /// The trash's panel. + pub fn trash(&mut self) -> Trash<'_> { + Trash(self) + } + + /// The JSON snippet open, explored. + pub fn json(&mut self) -> Json<'_> { + Json(self) + } + + /// The form that asks for a snippet's fields. + pub fn fields(&mut self) -> Fields<'_> { + Fields(self) + } + + /// The tools area. + pub fn tools(&mut self) -> Tools<'_> { + Tools(self) + } + + /// The HTTP area. + pub fn http(&mut self) -> Http<'_> { + Http(self) + } + + /// The request open. + pub fn request(&mut self) -> Request<'_> { + Request(self) + } + + /// The answer under the request open. + pub fn response(&mut self) -> Response<'_> { + Response(self) + } + + /// The WebSocket open. + pub fn socket(&mut self) -> Socket<'_> { + Socket(self) + } + + /// The environments requests are sent with. + pub fn environments(&mut self) -> Environments<'_> { + Environments(self) + } + + /// The request open, written as code. + pub fn code(&mut self) -> Code<'_> { + Code(self) + } + + /// The history of what was sent. + pub fn sends(&mut self) -> Sends<'_> { + Sends(self) + } + + /// A collection's run. + pub fn runner(&mut self) -> Runner<'_> { + Runner(self) + } + + /// A server on this machine that answers the journey's requests: its address. + pub fn serve_api(&mut self) -> String { + format!("http://127.0.0.1:{}", server::serve()) + } + + /// A WebSocket server on this machine that sends each text back: its address. + pub fn serve_socket(&mut self) -> String { + format!("ws://127.0.0.1:{}", server::serve_socket()) + } + + /// The libraries of the profile. + pub fn libraries(&mut self) -> Libraries<'_> { + Libraries(self) + } + + /// What leaves the library and what comes in. + pub fn transfer(&mut self) -> Transfer<'_> { + Transfer(self) + } + + /// The library's passphrase and its copies. + pub fn security(&mut self) -> Security<'_> { + Security(self) + } + + /// The preferences. + pub fn prefs(&mut self) -> Prefs<'_> { + Prefs(self) + } + + /// The *About* menu and what it opens. + pub fn help(&mut self) -> Help<'_> { + Help(self) + } + + /// The palette. + pub fn palette(&mut self) -> Palette<'_> { + Palette(self) + } + + /// The icon in the system's tray. + pub fn tray(&mut self) -> Tray<'_> { + Tray(self) + } + + /// The window itself. + pub fn window(&mut self) -> Window<'_> { + Window(self) + } + + /// The system's clipboard. + pub fn clipboard(&mut self) -> Clipboard<'_> { + Clipboard(self) + } + + /// The person's own files, and what they answer to the file dialogs. + pub fn files(&mut self) -> Files<'_> { + Files(self) + } + + /// Presses a shortcut. + pub fn press(&mut self, shortcut: Shortcut) { + let (key, modifiers) = shortcut.keys(); + self.key(key, modifiers); + } + + /// Presses a shortcut on a keyboard of another layout: its keys stand where they do on QWERTY, + /// another character printed on them. + pub fn press_on_another_layout(&mut self, shortcut: Shortcut) { + let (place, modifiers) = shortcut.keys(); + self.key_printed(Key::Semicolon, place, modifiers); + } + + /// Asks for something from anywhere on the machine, the window in sight or not. + pub fn press_global(&mut self, global: Global) { + self.driver.hand_over(Some(match global { + Global::Palette => "palette", + Global::NewNote => "new-note", + Global::PasteFromClipboard => "capture", + })); + self.driver.settle(); + } + + /// DevNotes ends by itself, everything written; started again, its library is unlocked. + pub fn start_after_the_end(&mut self) { + self.driver.ended(); + self.start_again(); + self.gate().unlock(PASSPHRASE); + } + + /// Types a text where the keyboard is. + pub fn type_text(&mut self, text: &str) { + self.driver.apply(vec![Event::Text(text.to_owned())]); + } + + /// Pastes a text where the keyboard is, as the window delivers it. + pub fn paste(&mut self, text: &str) { + self.driver.apply(vec![Event::Paste(text.to_owned())]); + } + + /// Copies what is selected, as the window delivers Ctrl+C. + pub fn copy(&mut self) { + self.driver.apply(vec![Event::Copy]); + } + + /// Quits and starts DevNotes again, as a person closing it and coming back: the gate asks. + pub fn relaunch(&mut self) { + self.driver.hand_over(Some("quit")); + self.driver.ended(); + self.start_again(); + } + + /// As `relaunch`, through the gate with the journey's phrase. + pub fn relaunch_and_unlock(&mut self) { + self.relaunch(); + self.gate().unlock(PASSPHRASE); + } + + /// Quits, has the library's database damaged while DevNotes is closed, and starts it again. + pub fn relaunch_damaged(&mut self) { + self.driver.hand_over(Some("quit")); + self.driver.ended(); + files::damage_library(self.profile()); + self.driver.start_again(); + } + + /// *File → Quit*, clicked again as it asks, and DevNotes ends. + pub fn quit_from_the_menu(mut self) { + self.click("file-menu", "the « File » menu"); + let quit = self.tree().text("file-quit").unwrap_or_default(); + self.click("file-quit", "« Quit »"); + self.expect("« Quit » asks for a second click", |tree| { + tree.text("file-quit").is_some_and(|said| said != quit) + }); + self.click("file-quit", "« Quit » again"); + self.ended(); + } + + /// Quits DevNotes, once the journey is over. + pub fn quit(mut self) { + self.driver.hand_over(Some("quit")); + self.driver.ended(); + } + + /// The window as it stands, kept beside the journey's other captures. + pub fn capture(&mut self, name: &str) { + self.driver.capture(name); + } + + /// The number the system knows the running process by. + pub fn process(&self) -> u32 { + self.driver.process() + } + + /// DevNotes was launched without a line in the terminal. Said of Linux alone, where it is + /// launched from one often enough for its lines to be read as faults. + pub fn expect_silent_terminal(&mut self, says: &str) { + let wrote = std::fs::read_to_string(terminal(self.room.path())).unwrap_or_default(); + // Mesa's pair about DRI3 is Xvfb's, which has none: no desktop's X server lacks it. + let fault = wrote + .lines() + .any(|line| !(line.starts_with("libEGL warning:") && line.contains("DRI3"))); + assert!(!cfg!(target_os = "linux") || !fault, "« {} »: {says}\n{wrote}", current_step()); + } + + fn start_again(&mut self) { + self.driver.start_again(); + if self.wide { + self.window().widen(); + } + } + + /// DevNotes started a second time while it runs: the window comes back on the screen. + fn launch_again(&mut self) { + self.driver.hand_over(None); + self.driver.settle(); + } + + /// Waits for DevNotes to end by itself, everything written. + fn ended(&mut self) { + self.driver.ended(); + } + + fn profile(&self) -> &Path { + self.driver.profile() + } +} + +/// A directory of the journey's own, the person's files in it. +fn room() -> TempDir { + let room = TempDir::new().expect("a directory of the journey's own"); + std::fs::create_dir(room.path().join("files")).expect("the person's directory is made"); + room +} + +fn terminal(room: &Path) -> PathBuf { + room.join("terminal.txt") +} diff --git a/e2e/src/sdk/notes.rs b/e2e/src/sdk/notes.rs new file mode 100644 index 000000000..5ba70057d --- /dev/null +++ b/e2e/src/sdk/notes.rs @@ -0,0 +1,557 @@ +use egui::accesskit::{Node, Rect}; + +use super::{App, Modifiers, Shortcut}; +use crate::driver::{Tree, said, within}; + +/// The notes area: its rail, its header and its cards. +pub struct Notes<'a>(pub(super) &'a mut App); + +/// A sample note of the first launch, in whichever language the machine speaks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Sample { + Welcome, + PsqlConnection, + ApiResponse, + ReleaseDay, + SnippetToFormat, + ThingsToTry, +} + +impl Sample { + /// Its title, in English and in French. + fn titles(self) -> [&'static str; 2] { + match self { + Self::Welcome => ["Welcome to DevNotes", "Bienvenue dans DevNotes"], + Self::PsqlConnection => ["psql connection", "Connexion psql"], + Self::ApiResponse => ["API response — open it as a graph", "Réponse d’API — à ouvrir en graphe"], + Self::ReleaseDay => ["Release day", "Mise en production"], + Self::SnippetToFormat => ["Code to format (Shift+Alt+F)", "Code à formater (Maj+Alt+F)"], + Self::ThingsToTry => ["Things to try", "À essayer"], + } + } +} + +/// A note as a journey names it: by its title, or a sample. +pub trait Named: Copy { + /// Whether `title` is this note's. + fn is(self, title: &str) -> bool; +} + +impl Named for &str { + fn is(self, title: &str) -> bool { + self == title + } +} + +impl Named for Sample { + fn is(self, title: &str) -> bool { + self.titles().contains(&title) + } +} + +/// A kind of note. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Note, + Snippet, + TodoList, + Calculation, + Drawing, +} + +/// The quick filter of the header. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QuickFilter { + All, + Pinned, + Untriaged, +} + +const SAMPLES: usize = 6; +/// The samples' space, in English and in French. +const FIRST_SPACE: [&str; 2] = ["Getting started", "Découverte"]; + +impl Notes<'_> { + /// *New note*, of the kind the preferences say. + pub fn new_note(&mut self) { + self.0.click("new-note", "« New note »"); + self.0.expect("a new note opens", |tree| tree.has("editor-title")); + } + + /// Duplicates a note, from its card's menu: the copy opens. + pub fn duplicate(&mut self, note: impl Named) { + self.open_card_menu(note); + self.0.click("note-card-duplicate", "« Duplicate »"); + self.0.expect("the copy opens", |tree| tree.has("editor-title")); + } + + /// Sends a note to a space, from its card's menu. + pub fn move_to_space(&mut self, note: impl Named, space: &str) { + self.open_card_menu(note); + self.0.click("note-card-move", "« Move to… »"); + self.0 + .click_where("note-card-move-place", "the place to move to", |place| said(place) == space); + } + + /// Files a note into a folder, from its card's menu and the filter of its places. + pub fn file_into(&mut self, note: impl Named, folder: &str) { + self.open_card_menu(note); + self.0.click("note-card-move", "« Move to… »"); + self.0.fill("note-card-move-filter", "the filter of the places", folder); + self.0.press(Shortcut::Enter); + } + + /// A note made from the card that offers one, in the folder open. + pub fn write_from_the_ghost(&mut self, title: &str, code: &str) { + self.0.click("create-ghost", "the card that offers a note"); + self.0.editor().type_title(title); + self.0.editor().type_code(code); + self.0.editor().close(); + self.expect_card(title, "the note is a card"); + } + + /// Leaves the folder open by its breadcrumb. + pub fn leave_folder(&mut self) { + self.0.click("folder-breadcrumb-back", "the breadcrumb's way back"); + self.0.expect("the folder is left", |tree| !tree.has("folder-breadcrumb-name")); + } + + /// Opens the menu of a card, by its ⋯. + fn open_card_menu(&mut self, note: impl Named) { + self.click_on_card(note, "note-card-menu", "the card's « ⋯ »"); + } + + /// A note of a kind, from the menu beside *New note*. + pub fn new_of_kind(&mut self, kind: Kind) { + let (id, name) = match kind { + Kind::Note => ("new-note-note", "« Note »"), + Kind::Snippet => ("new-note-snippet", "« Snippet »"), + Kind::TodoList => ("new-note-checklist", "« Todo list »"), + Kind::Calculation => ("new-note-calc", "« Calculation »"), + Kind::Drawing => ("new-note-drawing", "« Drawing »"), + }; + self.0.click("new-note-kind", "the menu beside « New note »"); + self.0.click(id, name); + self.0.expect("a new note opens", |tree| tree.has("editor-title")); + } + + /// A snippet written and closed: its title and its code. + pub fn write_snippet(&mut self, title: &str, code: &str) { + self.new_note(); + self.0.editor().type_title(title); + self.0.editor().type_code(code); + self.0.editor().close(); + self.expect_card(title, "the snippet is a card"); + } + + /// Opens a note by its card. + pub fn open(&mut self, note: impl Named) { + let card = self.card(note); + self.0.click_top(card); + self.0.expect("the note opens", |tree| tree.has("editor-title")); + } + + /// Opens the first note listed. + pub fn open_first(&mut self) { + let card = self + .0 + .place("the first card", |tree| tree.find("note-card").and_then(Node::bounds)); + self.0.click_top(card); + self.0.expect("the note opens", |tree| tree.has("editor-title")); + } + + /// Scrolls the cards down by one notch of the wheel. + pub fn scroll_down(&mut self) { + self.0.wheel("canvas", -120.0); + } + + /// Copies a note by the button of its card. + pub fn copy(&mut self, note: impl Named) { + self.click_on_card(note, "note-card-copy", "the card's « Copy »"); + } + + /// Copies a note that has fields, by the button of its card: the form asks for them. + pub fn copy_filled(&mut self, note: impl Named) { + self.click_on_card(note, "note-card-fill", "the card's « Fill and copy »"); + self.0.fields().expect_open("the form asks for the fields"); + } + + /// Ticks an item of a todo list from its card, the items counted from 0. + pub fn tick_on_card(&mut self, note: impl Named, item: usize) { + let card = self.card(note); + self.0 + .click_nth_where("note-card-item", item, "an item on the card", |node| within(node, card)); + } + + /// The title of a note, as its card writes it. + pub fn title_of(&mut self, note: impl Named) -> String { + self.0.seen("the note's card is on the screen", |tree| { + tree.texts("note-card-title").into_iter().find(|title| note.is(title)) + }) + } + + /// Takes the keyboard to a note's card: the search finds it alone, and the arrow goes down to it. + pub fn go_to_card(&mut self, title: &str) { + self.search(title); + self.0.expect("the note is alone", |tree| tree.texts("note-card") == [title]); + self.0.press(Shortcut::Down); + self.0 + .expect("its card has the keyboard", |tree| tree.has_focus("note-card-open")); + } + + /// Deletes a note from the keyboard: the first press asks, the second sends it to the trash. + pub fn delete_from_the_keyboard(&mut self, title: &str) { + self.go_to_card(title); + self.0.press(Shortcut::Delete); + self.0 + .expect("the card asks for a second press", |tree| tree.has("note-card-arming")); + self.0.press(Shortcut::Delete); + self.0 + .expect("the note is in the trash", |tree| !tree.has("note-card") && tree.has("undo-bar")); + } + + /// The undo bar's *Undo*. + pub fn undo(&mut self) { + self.0.click("undo-restore", "the bar's « Undo »"); + } + + /// Takes the undo bar off the screen, its offer turned down. + pub fn dismiss_undo(&mut self) { + self.0.click("undo-dismiss", "the bar's cross"); + self.0.expect("the bar goes", |tree| !tree.has("undo-bar")); + } + + /// The quick filter of the header. + pub fn filter(&mut self, filter: QuickFilter) { + match filter { + QuickFilter::All => self.0.click("quick-filter-0", "« All »"), + QuickFilter::Pinned => self.0.click("quick-filter-1", "« Pinned »"), + QuickFilter::Untriaged => self.0.click("quick-filter-2", "« Untriaged »"), + } + } + + /// A todo list with one task, written and closed. + pub fn write_todo_list(&mut self, title: &str, task: &str) { + self.0.press(Shortcut::NewTodoList); + self.0.editor().type_title(title); + self.0.todo().add(task); + self.0.editor().close(); + self.expect_card(title, "the list is a card"); + } + + /// A Note with one line, written and closed. + pub fn write_note(&mut self, title: &str, text: &str) { + self.0.press(Shortcut::NewNote); + self.0.editor().type_title(title); + self.0.editor().type_note(text); + self.0.editor().close(); + self.expect_card(title, "the Note is a card"); + } + + /// Ticks or unticks a card by its box. + pub(super) fn click_box(&mut self, note: impl Named) { + let card = self.card(note); + self.0.move_over(card); + self.0 + .click_where("note-card-check", "the card's box", |node| within(node, card)); + } + + /// Clicks a card, a key held. + pub(super) fn click_holding(&mut self, held: Modifiers, note: impl Named) { + let card = self.card(note); + self.0.hold(held); + self.0.click_top(card); + self.0.hold(Modifiers::NONE); + } + + /// Types in the search, over what it holds. + pub fn search(&mut self, words: &str) { + self.0.replace("search-input", "the search", words); + } + + /// Empties the search by its cross. + pub fn clear_search(&mut self) { + self.0.click("search-clear", "the search's cross"); + self.0.expect("the search is empty", |tree| !tree.has("search-clear")); + } + + /// Takes the keyboard to the first card. + pub fn go_to_first_card(&mut self) { + self.0.take_keyboard("search-input", "the search"); + self.0.press(Shortcut::Down); + self.0 + .expect("the first card has the keyboard", |tree| tree.has_focus("note-card-open")); + } + + /// The height of the cards, in points. + pub fn card_height(&mut self) -> f64 { + let tree = self.0.tree(); + tree.find("note-card").and_then(Node::bounds).map_or(0.0, |card| card.height()) + } + + /// How far apart two cards of a row stand, in points: what the density sets. + pub fn cards_apart(&mut self) -> f64 { + apart(&self.0.tree()).unwrap_or_default() + } + + /// The cards stand closer than `before`. + pub fn expect_cards_closer(&mut self, before: f64, says: &str) { + self.0.expect(says, |tree| apart(tree).is_some_and(|now| now < before - 1.0)); + } + + /// The cards stand as far apart as `before`. + pub fn expect_cards_apart(&mut self, before: f64, says: &str) { + self.0 + .expect(says, |tree| apart(tree).is_some_and(|now| (now - before).abs() < 1.0)); + } + + /// The cards grew by a line since they were `four` points high, for four lines each. + pub fn expect_one_line_taller(&mut self, four: f64, says: &str) { + // 160 points for five lines against 140 for four, the window's scale aside. + self.0.expect(says, |tree| { + let card = tree.find("note-card").and_then(Node::bounds); + card.is_some_and(|card| (card.height() / four - 160.0 / 140.0).abs() < 0.02) + }); + } + + /// The library holds the first launch's sample notes, in the one space there is, and nothing went wrong: + /// one stands outside every folder. + pub fn expect_samples(&mut self, says: &str) { + self.0.expect(says, |tree| { + let spaces = tree.texts("space-option"); + tree.count("note-card") == SAMPLES + && tree.count("note-card-folder") == SAMPLES - 1 + && !tree.has("error-banner") + && spaces.len() == 1 + && FIRST_SPACE.contains(&spaces[0].as_str()) + }); + } + + /// This note has a card, and no note is open. + pub fn expect_card(&mut self, note: impl Named, says: &str) { + self.0.expect(says, |tree| { + tree.texts("note-card-title").iter().any(|title| note.is(title)) && !tree.has("editor-title") + }); + } + + /// Some card is on the screen, whatever it is. + pub fn expect_some_card(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("note-card")); + } + + /// As many cards are on the screen. + pub fn expect_cards(&mut self, count: usize, says: &str) { + self.0 + .expect(says, |tree| tree.count("note-card") == count && !tree.has("editor-title")); + } + + /// A card quotes the words the search found, whatever part of the note holds them. + pub fn expect_quoting(&mut self, note: impl Named, words: &str, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + tree.has("search-matched") && tree.says_within(card, words) + }); + } + + /// The cards, by their titles, top to bottom then left to right. + pub fn expect_order(&mut self, titles: &[&str], says: &str) { + self.0.expect(says, |tree| tree.texts("note-card") == titles); + } + + /// The first card is this note's. + pub fn expect_first(&mut self, note: impl Named, says: &str) { + self.0 + .expect(says, |tree| tree.texts("note-card").first().is_some_and(|title| note.is(title))); + } + + /// As many cards wear a priority. + pub fn expect_urgent(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| tree.count("priority-bars") == count); + } + + /// A card wears the chip of the folder it is in, its path from the top. + pub fn expect_chip(&mut self, note: impl Named, path: &str, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + let mut chips = tree.all("note-card-folder").into_iter(); + chips.any(|chip| within(chip, card) && said(chip).ends_with(path)) + }); + } + + /// As many cards wear the chip of a folder. + pub fn expect_chips(&mut self, count: usize, says: &str) { + self.0 + .expect(says, |tree| tree.has("note-card") && tree.count("note-card-folder") == count); + } + + /// The folder open is empty, and offers the card a note is made from. + pub fn expect_ghost(&mut self, says: &str) { + self.0.expect(says, |tree| { + tree.has("create-ghost") && !tree.has("note-card") && !tree.has("canvas-no-results") + }); + } + + /// The search has the keyboard. + pub fn expect_keyboard_in_search(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has_focus("search-input")); + } + + /// The undo bar says what was done, and offers it back. + pub fn expect_undo_offered(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.text("undo-text").is_some_and(|said| !said.is_empty())); + } + + /// The search is empty. + pub fn expect_search_empty(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("search-clear")); + } + + /// This card has the keyboard. + pub fn expect_keyboard_on(&mut self, note: impl Named, says: &str) { + self.0 + .expect(says, |tree| tree.has_focus("note-card-open") && note.is(&tree.focused_says())); + } + + /// A card wears its language and how many fields it has. + pub fn expect_card_wearing(&mut self, note: impl Named, language: &str, fields: &str, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + let worn = |id: &str, words: &str| { + tree.all(id) + .into_iter() + .any(|node| within(node, card) && said(node).contains(words)) + }; + worn("note-format", language) && worn("note-card-fields", fields) + }); + } + + /// The first card is this note's, pinned and wearing its priority. + pub fn expect_first_pinned_with_priority(&mut self, note: impl Named, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + let worn = |id: &str| tree.all(id).into_iter().any(|node| within(node, card)); + let first = tree.texts("note-card").first().is_some_and(|title| note.is(title)); + first && worn("note-card-pin") && worn("priority-bars") + }); + } + + /// A card counts its files. + pub fn expect_files_counted(&mut self, note: impl Named, count: &str, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + let mut clips = tree.all("note-card-clip").into_iter(); + clips.any(|clip| within(clip, card) && said(clip).contains(count)) + }); + } + + /// A calculation's card shows its lines and their results. + pub fn expect_calculation(&mut self, note: impl Named, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + tree.all("note-card-calc").into_iter().any(|lines| within(lines, card)) + }); + } + + /// A drawing's card shows its picture. + pub fn expect_picture(&mut self, note: impl Named, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + tree.all("note-card-drawing").into_iter().any(|picture| within(picture, card)) + }); + } + + /// The undo bar is gone: its offer had its time. + pub fn expect_undo_gone(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("undo-bar")); + } + + /// Nothing is on the canvas under this title. + pub fn expect_no_card(&mut self, note: impl Named, says: &str) { + self.0.expect(says, |tree| { + tree.has("canvas-keyboard-hint") && !tree.texts("note-card").iter().any(|title| note.is(title)) + }); + } + + /// A card counts this much of its list done, as « 1/9 ». + pub fn expect_progress(&mut self, note: impl Named, done: &str, says: &str) { + self.0.expect(says, |tree| { + let Some(card) = card_of(tree, note) else { + return false; + }; + let mut progress = tree.all("note-card-progress").into_iter(); + progress.any(|node| within(node, card) && said(node) == done) + }); + } + + /// Nothing answers the search. + pub fn expect_nothing_found(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("canvas-no-results")); + } + + /// A toast says what was done; its cross takes it off the screen. + pub fn expect_acknowledged(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("status-toast")); + self.0.click("status-dismiss", "the toast's cross"); + self.0.expect("the toast goes", |tree| !tree.has("status-toast")); + } + + /// Takes any toast off the screen. + pub fn clear_toasts(&mut self) { + while self.0.tree().has("status-dismiss") { + self.0.click("status-dismiss", "the toast's cross"); + self.0.driver.settle(); + } + } + + /// No toast is on the screen, once what was done is done. + pub fn expect_no_acknowledgement(&mut self, says: &str) { + self.0.expect_at_rest(says, |tree| !tree.has("status-toast")); + } + + /// A button a card shows under the pointer. + fn click_on_card(&mut self, note: impl Named, id: &str, name: &str) { + let card = self.card(note); + self.0.move_over(card); + self.0.click_where(id, name, |node| on_card(node, card)); + } + + /// Where a note's card stands, the cards scrolled to it. + fn card(&mut self, note: impl Named) -> Rect { + self.0.scroll_to("canvas", "the note's card", |tree| card_of(tree, note)) + } +} + +/// Whether a button is one of the card's under the pointer: they hang over its foot. +fn on_card(node: &Node, card: Rect) -> bool { + let hanging = Rect { y1: card.y1 + 24.0, ..card }; + within(node, hanging) +} + +/// Between two cards of one row. +fn apart(tree: &Tree) -> Option { + let cards: Vec = tree.all("note-card").into_iter().filter_map(Node::bounds).collect(); + let mut pairs = cards.windows(2); + let row = pairs.find(|pair| (pair[0].y0 - pair[1].y0).abs() < 1.0)?; + Some(row[1].x0 - row[0].x1) +} + +/// Where the card of `note` stands. +fn card_of(tree: &Tree, note: impl Named) -> Option { + let mut cards = tree.all("note-card").into_iter(); + cards.find(|card| note.is(&said(card)))?.bounds() +} diff --git a/e2e/src/sdk/palette.rs b/e2e/src/sdk/palette.rs new file mode 100644 index 000000000..a4d35d6d8 --- /dev/null +++ b/e2e/src/sdk/palette.rs @@ -0,0 +1,93 @@ +use super::{App, Shortcut}; + +/// The palette, over the window or over whatever was on the screen. +pub struct Palette<'a>(pub(super) &'a mut App); + +impl Palette<'_> { + /// Opens it by its key in the window. + pub fn open(&mut self) { + self.0.press(Shortcut::Palette); + self.expect_open("the palette opens"); + } + + /// Types over what its field holds. + pub fn search(&mut self, words: &str) { + self.0.press(Shortcut::SelectAll); + self.0.type_text(words); + } + + /// Narrows it to a place or a tag: what is typed, then Enter on the first answer. + pub fn narrow_to(&mut self, words: &str) { + self.search(words); + self.0.expect("the palette offers where to search", |tree| { + tree.count("palette-option") > 0 && !tree.has("palette-chip") + }); + self.0.press(Shortcut::Enter); + self.0.expect("the palette is narrowed", |tree| tree.has("palette-chip")); + } + + /// Takes the first answer, by Enter. + pub fn choose_first(&mut self) { + self.0.press(Shortcut::Enter); + self.expect_closed("the palette closes"); + } + + /// Copies the first answer. + pub fn copy_first(&mut self) { + self.0.copy(); + } + + /// Closes it. + pub fn close(&mut self) { + self.0.press(Shortcut::Escape); + self.expect_closed("the palette closes"); + } + + /// The palette is open, the keyboard in its field. + pub fn expect_open(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has_focus("palette-input")); + } + + /// The palette is not on the screen. + pub fn expect_closed(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("palette-input")); + } + + /// Some answers are listed, whatever they are. + pub fn expect_answers(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.count("palette-option") > 0 && !tree.has("palette-empty")); + } + + /// There is one answer, whatever it is. + pub fn expect_one_answer(&mut self, says: &str) { + self.0.expect(says, |tree| tree.count("palette-option") == 1); + } + + /// This is the one answer. + pub fn expect_only(&mut self, words: &str, says: &str) { + self.0.expect(says, |tree| { + let answers = tree.texts("palette-option"); + answers.len() == 1 && answers[0].contains(words) + }); + } + + /// This is among the answers. + pub fn expect_found(&mut self, words: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("palette-option").iter().any(|answer| answer.contains(words))); + } + + /// Nothing is found, and a note named after what was typed is offered. + pub fn expect_creation_offered(&mut self, says: &str) { + self.0.expect(says, |tree| { + tree.has("palette-create") && tree.has("palette-empty") && tree.count("palette-option") == 0 + }); + } + + /// The commands are listed. + pub fn expect_commands(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.count("palette-option") >= 5 && tree.has("palette-group")); + } +} diff --git a/e2e/src/sdk/prefs.rs b/e2e/src/sdk/prefs.rs new file mode 100644 index 000000000..f71e697c5 --- /dev/null +++ b/e2e/src/sdk/prefs.rs @@ -0,0 +1,249 @@ +use std::collections::BTreeMap; +use std::path::Path; + +use egui::accesskit::Node; +use egui::{Key, Modifiers}; +use serde_json::Value; + +use super::App; + +/// The preferences: *File → Preferences…*, and the file they are kept in. +pub struct Prefs<'a>(pub(super) &'a mut App); + +/// A page of the panel. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Page { + General, + Variables, + Shortcuts, + Security, + Copies, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Theme { + Dark, + Light, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Density { + Comfortable, + Compact, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Language { + French, + English, +} + +/// What *New note* makes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DefaultKind { + Note, + Snippet, +} + +/// What Tab writes in the code. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Indent { + FourSpaces, +} + +/// A switch of the panel. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Switch { + WrapLines, + CloseToTray, + MinimizeToTray, + CopyAcknowledged, +} + +/// An action a key of the cards is for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CardKey { + Pin, + Check, +} + +impl Prefs<'_> { + /// *File → Preferences…*, on its first page. + pub fn open(&mut self) { + self.0.click("file-menu", "the « File » menu"); + self.0.click("file-preferences", "« Preferences… »"); + self.0.expect("the preferences open", |tree| tree.has("settings-dialog")); + } + + /// Opens the panel, changes what `change` does, and closes it with its button. + pub fn change(&mut self, change: impl FnOnce(&mut Self)) { + self.open(); + change(self); + self.close(); + } + + /// Goes to a page of the panel. + pub fn go_to(&mut self, page: Page) { + match page { + Page::General => self.0.click("settings-page-general", "the « General » page"), + Page::Variables => self.0.click("settings-page-variables", "the « Variables » page"), + Page::Shortcuts => self.0.click("settings-page-shortcuts", "the « Shortcuts » page"), + Page::Security => self.0.click("settings-page-security", "the « Security » page"), + Page::Copies => self.0.click("settings-page-backups", "the « Copies » page"), + } + } + + /// *Apply*: the panel stays. + pub fn apply(&mut self) { + self.0.click("settings-apply", "« Apply »"); + self.0 + .expect("what was chosen is applied", |tree| tree.is_disabled("settings-apply")); + } + + /// The button that applies and closes. + pub fn close(&mut self) { + self.0.click("settings-close", "the button that applies and closes"); + self.expect_closed(); + } + + /// *Cancel*: what was shown goes back. + pub fn cancel(&mut self) { + self.0.click("settings-cancel", "« Cancel »"); + self.expect_closed(); + } + + /// Chooses dark or light. + pub fn choose_theme(&mut self, theme: Theme) { + match theme { + Theme::Dark => self.choose("setting-theme-1", "« Dark »"), + Theme::Light => self.choose("setting-theme-2", "« Light »"), + } + } + + /// Chooses how close the cards stand. + pub fn choose_density(&mut self, density: Density) { + match density { + Density::Comfortable => self.choose("setting-density-0", "« Comfortable »"), + Density::Compact => self.choose("setting-density-1", "« Compact »"), + } + } + + /// Chooses the language of the window. + pub fn choose_language(&mut self, language: Language) { + self.choose("setting-locale", "the language's menu"); + match language { + Language::French => self.0.click("setting-locale-1", "« Français »"), + Language::English => self.0.click("setting-locale-2", "« English »"), + } + } + + /// Chooses what *New note* makes. + pub fn choose_default_kind(&mut self, kind: DefaultKind) { + match kind { + DefaultKind::Note => self.choose("setting-note-kind-0", "« Note » as the default"), + DefaultKind::Snippet => self.choose("setting-note-kind-1", "« Snippet » as the default"), + } + } + + /// Chooses how many lines a card previews: 3, 4 or 5. + pub fn choose_preview_lines(&mut self, lines: usize) { + self.choose(&format!("setting-preview-lines-{}", lines - 3), "a number of lines"); + } + + /// Chooses what Tab writes in the code. + pub fn choose_indent(&mut self, indent: Indent) { + self.choose("setting-indent", "the indentation's menu"); + match indent { + Indent::FourSpaces => self.0.click("setting-indent-2", "« 4 spaces »"), + } + } + + /// Chooses how many decimals a calculation's results have. + pub fn choose_decimals(&mut self, places: usize) { + self.choose("setting-calc-decimals", "the decimals' menu"); + self.0 + .click(&format!("setting-calc-decimals-{}", places + 1), "a number of decimals"); + } + + /// Turns a switch over. + pub fn flip(&mut self, switch: Switch) { + match switch { + Switch::WrapLines => self.choose("setting-code-wrap", "the switch of the wrapped lines"), + Switch::CloseToTray => self.choose("setting-close-to-tray", "« Close to tray »"), + Switch::MinimizeToTray => self.choose("setting-minimize-to-tray", "« Minimize to tray »"), + Switch::CopyAcknowledged => { + self.choose("setting-copy-confirmation", "the switch of the copy's acknowledgement"); + } + } + } + + /// Adds a global variable, on its page. + pub fn add_variable(&mut self, name: &str, value: &str) { + self.0.click("variable-add", "« Add a variable »"); + self.0.fill("variable-name", "the variable's name", name); + self.0.fill("variable-value", "the variable's value", value); + } + + /// Presses a letter as the key of an action, on the « Shortcuts » page. + pub fn take_key(&mut self, action: CardKey, letter: Key) { + self.choose(&field(action), "the action's key"); + self.0.key(letter, Modifiers::NONE); + } + + /// Puts an action's key back. + pub fn reset_key(&mut self, action: CardKey) { + self.choose(&field(action).replace("field", "reset"), "the key's « Reset »"); + } + + /// The panel says another action holds the key asked for. + pub fn expect_key_flagged(&mut self, action: CardKey, says: &str) { + let at = field(action).replace("field", "error"); + self.0.expect(says, |tree| tree.has(&at)); + } + + /// An action's key, as the panel shows it. + pub fn expect_key(&mut self, action: CardKey, shown: &str, says: &str) { + let at = field(action); + self.0.expect(says, |tree| tree.find(&at).and_then(Node::value) == Some(shown)); + } + + /// The file on the disk holds this value for a setting, named as the file names it. + pub fn expect_stored(&mut self, setting: &str, value: &str, says: &str) { + let file = self.0.profile().join("preferences.json"); + let key = format!("devnotes.{setting}"); + self.0 + .expect(says, |_| stored(&file).get(&key).and_then(Value::as_str) == Some(value)); + } + + /// The file on the disk holds one key per setting, each a text. + pub fn expect_stored_as_texts(&mut self, says: &str) { + let file = self.0.profile().join("preferences.json"); + self.0.expect(says, |_| { + let settings = stored(&file); + !settings.is_empty() && settings.values().all(Value::is_string) + }); + } + + fn expect_closed(&mut self) { + self.0.expect("the preferences close", |tree| !tree.has("settings-dialog")); + } + + /// Scrolled to, above the panel's foot. + fn choose(&mut self, id: &str, name: &str) { + self.0.reach("settings-content", (id, name), "settings-cancel"); + self.0.click(id, name); + } +} + +fn field(action: CardKey) -> String { + let action = match action { + CardKey::Pin => "pin", + CardKey::Check => "check", + }; + format!("shortcut-field-canvas.{action}") +} + +fn stored(file: &Path) -> BTreeMap { + let text = std::fs::read_to_string(file).unwrap_or_default(); + serde_json::from_str(&text).unwrap_or_default() +} diff --git a/e2e/src/sdk/rail.rs b/e2e/src/sdk/rail.rs new file mode 100644 index 000000000..2da1d5aa6 --- /dev/null +++ b/e2e/src/sdk/rail.rs @@ -0,0 +1,290 @@ +use egui::accesskit::{Node, Rect}; + +use super::{App, Shortcut}; +use crate::driver::{Tree, is_on, middle, said}; + +/// The rail of the notes: its spaces and their folders. +pub struct Rail<'a>(pub(super) &'a mut App); + +impl Rail<'_> { + /// A space of its own, shown once made: it is empty. + pub fn new_space(&mut self, name: &str) { + self.0.click("space-create-open", "the button of a new space"); + self.0.fill("space-create-input", "the new space's name", name); + self.0.press(Shortcut::Enter); + self.0 + .expect("the new space is shown, empty", |tree| !tree.has("note-card") && is_shown(tree, name)); + } + + /// *All spaces*. + pub fn show_all_spaces(&mut self) { + self.0.click("space-option-all", "« All spaces »"); + self.0.expect("every space is shown", |tree| tree.is_on("space-option-all")); + } + + /// Shows one space. + pub fn show_space(&mut self, name: &str) { + self.0 + .click_where("space-option", "the space in the rail", |row| said(row) == name); + self.0.expect("the space is shown", |tree| is_shown(tree, name)); + } + + /// Renames a space, in its panel. + pub fn rename_space(&mut self, name: &str, into: &str) { + self.open_space_panel(name); + self.0.replace("space-rename-input", "the space's name", into); + self.0.press(Shortcut::Enter); + self.0.expect("the space wears its new name", |tree| { + let names = tree.texts("space-option"); + names.iter().any(|row| row == into) && !names.iter().any(|row| row == name) + }); + } + + /// Pins a space, in its panel, which is then put away. + pub fn pin_space(&mut self, name: &str) { + self.open_space_panel(name); + self.0.click("space-pin", "« Pin »"); + self.close_space_panel(name); + } + + /// Opens the panel of a space, where it would be deleted. + pub fn open_space_panel(&mut self, name: &str) { + self.0 + .click_where("space-edit", "the space's « ⋯ »", |row| said(row).contains(name)); + } + + /// Puts the panel of a space away, by what opened it. + pub fn close_space_panel(&mut self, name: &str) { + self.open_space_panel(name); + self.0.expect("the panel closes", |tree| !tree.has("space-rename-input")); + } + + /// Deletes the space whose panel is open, its notes moved where the panel says. + pub fn delete_space(&mut self) { + self.0.click("space-delete", "« Delete »"); + self.0.click("space-delete", "« Delete », again"); + } + + /// A folder in the space shown. + pub fn new_folder(&mut self, name: &str) { + self.ask_folder(name); + self.0 + .expect("the folder is listed", |tree| tree.texts("folder-option").iter().any(|row| row == name)); + } + + /// Asks for a folder, whatever is answered. + pub fn ask_folder(&mut self, name: &str) { + self.0.click("folder-create-open", "the button of a new folder"); + self.0.fill("folder-create-input", "the new folder's name", name); + self.0.press(Shortcut::Enter); + } + + /// A folder inside another, from its panel. + pub fn new_sub_folder(&mut self, parent: &str, name: &str) { + self.open_folder_panel(parent); + self.0.click("folder-subfolder-open", "« New sub-folder »"); + self.0.fill("folder-subfolder-input", "the sub-folder's name", name); + self.0.press(Shortcut::Enter); + self.expect_inside(name, parent, "the sub-folder is drawn inside its folder"); + } + + /// Renames a folder, in its panel. + pub fn rename_folder(&mut self, name: &str, into: &str) { + self.open_folder_panel(name); + self.0.replace("folder-rename-input", "the folder's name", into); + self.0.press(Shortcut::Enter); + self.0.expect("the folder wears its new name", |tree| { + tree.texts("folder-option").iter().any(|row| row == into) + }); + } + + /// Gives a folder the last colour of its panel. + pub fn recolour_folder(&mut self, name: &str) { + self.open_folder_panel(name); + let last = self + .0 + .seen("the colours are in the panel", |tree| tree.count("folder-colour").checked_sub(1)); + self.0.click_nth("folder-colour", last, "a colour"); + self.0.expect("the colour is the folder's", |tree| { + tree.all("folder-colour").last().is_some_and(|colour| is_on(colour)) + }); + self.open_folder_panel(name); + self.0.expect("the panel closes", |tree| !tree.has("folder-rename-input")); + } + + /// Opens the panel of a folder. + pub fn open_folder_panel(&mut self, name: &str) { + self.0 + .click_where("folder-edit", "the folder's « ⋯ »", |row| said(row).contains(name)); + } + + /// Deletes a folder, its notes handed to its parent. + pub fn delete_folder(&mut self, name: &str) { + self.open_folder_panel(name); + self.delete_folder_open(); + self.expect_no_folder(name, "the folder is gone"); + } + + /// Deletes a folder with the notes it holds. + pub fn delete_folder_with_its_notes(&mut self, name: &str) { + self.open_folder_panel(name); + self.0.click("folder-delete-held", "what becomes of its notes"); + self.0.click("folder-delete-held-1", "« Delete them too »"); + self.delete_folder_open(); + self.expect_no_folder(name, "the folder is gone"); + } + + /// The panel's *Delete*, twice. + fn delete_folder_open(&mut self) { + self.0.click("folder-delete", "« Delete »"); + self.0.click("folder-delete", "« Delete », again"); + } + + /// Opens a folder. + pub fn open_folder(&mut self, name: &str) { + self.0 + .click_where("folder-option", "the folder in the rail", |row| said(row) == name); + self.expect_folder_open(name, "the folder is open"); + } + + /// Drags a folder onto another. + pub fn drag_folder_onto(&mut self, name: &str, onto: &str) { + let (from, to) = (self.folder_row(name), self.folder_row(onto)); + self.0.drag(middle(from), middle(to)); + } + + /// Drags a folder onto a space. + pub fn drag_folder_onto_space(&mut self, name: &str, space: &str) { + let from = self.folder_row(name); + let to = self.0.place("the space in the rail", |tree| row(tree, "space-option", space)); + self.0.drag(middle(from), middle(to)); + self.0.expect("the folder is listed under the space", |tree| { + space_of(tree, name) == Some(space.to_owned()) + }); + } + + /// Takes the keyboard to a folder and moves it out of the one it is in, Alt+←. + pub fn move_folder_out(&mut self, name: &str) { + self.0.tab_to("folder-option", name, "the folder in the rail"); + self.0.press(Shortcut::MoveOut); + } + + /// The one other space than `name`, whatever the machine's language calls it. + pub fn other_space(&mut self, name: &str) -> String { + self.0.seen("another space is listed", |tree| { + tree.texts("space-option").into_iter().find(|space| space != name) + }) + } + + /// The first space of the rail. + pub fn expect_first_space(&mut self, name: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("space-option").first().is_some_and(|first| first == name)); + } + + /// This space is the one shown. + pub fn expect_space_shown(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| is_shown(tree, name)); + } + + /// No space goes by this name. + pub fn expect_no_space(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| { + tree.has("space-option") && !tree.texts("space-option").iter().any(|row| row == name) + }); + } + + /// One space goes by this name. + pub fn expect_one_space(&mut self, name: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("space-option").iter().filter(|row| *row == name).count() == 1); + } + + /// As many spaces are listed. + pub fn expect_spaces(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| tree.count("space-option") == count); + } + + /// The space whose panel is open cannot be deleted: it is the last one. + pub fn expect_no_deletion(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("space-delete-blocked") && !tree.has("space-delete")); + } + + /// The panel says where the space's notes would go. + pub fn expect_notes_destination(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("space-delete-consequence") && tree.has("space-delete-held")); + } + + /// A folder is drawn inside another. + pub fn expect_inside(&mut self, name: &str, parent: &str, says: &str) { + self.0.expect(says, |tree| { + let place = |folder| row(tree, "folder-option", folder); + place(name) + .zip(place(parent)) + .is_some_and(|(inner, outer)| inner.x0 > outer.x0 && inner.y0 > outer.y0) + }); + } + + /// Two folders are drawn side by side, neither inside the other. + pub fn expect_beside(&mut self, name: &str, other: &str, says: &str) { + self.0.expect(says, |tree| { + let left = |folder| row(tree, "folder-option", folder).map(|place| place.x0); + left(name).zip(left(other)).is_some_and(|(a, b)| (a - b).abs() < 1.0) + }); + } + + /// No folder goes by this name. + pub fn expect_no_folder(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| { + tree.has("space-option") && !tree.texts("folder-option").iter().any(|row| row == name) + }); + } + + /// A banner says why the folder was not made; it is then dismissed, and the field put away. + pub fn expect_folder_refused(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("error-banner")); + self.0.click("error-dismiss", "the banner's cross"); + self.0.press(Shortcut::Escape); + self.0.expect("the banner goes", |tree| !tree.has("error-banner")); + } + + /// As many folders go by this name. + pub fn expect_folders_named(&mut self, name: &str, count: usize, says: &str) { + self.0.expect(says, |tree| { + tree.texts("folder-option").iter().filter(|row| *row == name).count() == count + }); + } + + /// A folder is open, named by the breadcrumb. + pub fn expect_folder_open(&mut self, name: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("folder-breadcrumb-name").as_deref() == Some(name)); + } + + /// No folder is open. + pub fn expect_no_folder_open(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("area-notes") && !tree.has("folder-breadcrumb-name")); + } + + fn folder_row(&mut self, name: &str) -> Rect { + self.0.place("the folder in the rail", |tree| row(tree, "folder-option", name)) + } +} + +fn row(tree: &Tree, id: &str, name: &str) -> Option { + tree.all(id).into_iter().find(|row| said(row) == name).and_then(Node::bounds) +} + +/// The space a folder is listed under: the last row of a space above its own. +fn space_of(tree: &Tree, folder: &str) -> Option { + let folder = row(tree, "folder-option", folder)?; + let above = |space: &&Node| space.bounds().is_some_and(|bounds| bounds.y0 < folder.y0); + tree.all("space-option").into_iter().rfind(above).map(said) +} + +fn is_shown(tree: &Tree, space: &str) -> bool { + tree.all("space-option").into_iter().any(|row| said(row) == space && is_on(row)) +} diff --git a/e2e/src/sdk/request.rs b/e2e/src/sdk/request.rs new file mode 100644 index 000000000..4e98fb943 --- /dev/null +++ b/e2e/src/sdk/request.rs @@ -0,0 +1,374 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut}; +use crate::driver::{Tree, said}; + +/// The request open: its address, its parts, and what is done with it. +pub struct Request<'a>(pub(super) &'a mut App); + +/// A method of the menu. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Method { + Get, + Post, +} + +/// How a request authenticates. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Auth<'a> { + Inherited, + Basic { name: &'a str, password: &'a str }, + Bearer(&'a str), + ApiKey { name: &'a str, value: &'a str }, +} + +/// A body, as it is written in its part. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Body<'a> { + Json(&'a str), + /// A field and its value. + Form(&'a str, &'a str), + /// A field and its value, then a field that is the file answered to the dialog. + Multipart((&'a str, &'a str), &'a str), + /// The file answered to the dialog. + File, +} + +/// When a script runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Script { + Before, + After, + Tests, +} + +impl Request<'_> { + /// Types over the request's name. + pub fn type_name(&mut self, name: &str) { + self.0.replace("http-request-name", "the request's name", name); + } + + /// Types an address over the one written. + pub fn type_url(&mut self, url: &str) { + self.0.replace("http-url", "the address", url); + self.expect_url(url, "the address is typed"); + } + + /// Types at the end of the address. + pub fn add_to_url(&mut self, words: &str) { + self.0.take_keyboard("http-url", "the address"); + self.0.press(Shortcut::LineEnd); + self.0.type_text(words); + } + + /// Chooses a method. + pub fn choose_method(&mut self, method: Method) { + self.0.click("http-method", "the method's menu"); + match method { + Method::Get => self.0.click("http-method-0", "« GET »"), + Method::Post => self.0.click("http-method-1", "« POST »"), + } + } + + /// Ticks or unticks a parameter, counted from 0. + pub fn flip_param(&mut self, n: usize) { + self.go_to("params"); + self.0.click_nth("http-kv-enabled", n, "the parameter's box"); + } + + /// Types a header as it is read, « Name: value », in the first row. + pub fn type_header(&mut self, header: &str) { + self.go_to("headers"); + self.0.fill_nth("http-kv-key", 0, "the header's name", header); + } + + /// Chooses how it authenticates. + pub fn choose_auth(&mut self, auth: Auth<'_>) { + self.go_to("auth"); + self.0.click("http-auth-kind", "the auth's menu"); + match auth { + Auth::Inherited => self.0.click("http-auth-kind-0", "« Inherited »"), + Auth::Basic { name, password } => { + self.0.click("http-auth-kind-2", "« Basic »"); + self.0.replace("http-auth-username", "the name", name); + self.0.replace("http-auth-secret", "the password", password); + } + Auth::Bearer(token) => { + self.0.click("http-auth-kind-3", "« Bearer »"); + self.0.replace("http-auth-secret", "the token", token); + } + Auth::ApiKey { name, value } => { + self.0.click("http-auth-kind-4", "« API key »"); + self.0.replace("http-auth-key-name", "the key's name", name); + self.0.replace("http-auth-secret", "the key's value", value); + } + } + } + + /// Shows the auth's secret, or hides it again. + pub fn flip_secret(&mut self) { + self.go_to("auth"); + self.0.click("http-auth-reveal", "the secret's eye"); + } + + /// Writes a body. + pub fn type_body(&mut self, body: Body<'_>) { + self.go_to("body"); + match body { + Body::Json(text) => { + self.0.click("http-body-kind-1", "« JSON »"); + self.type_over("http-body-text", "the body", text); + } + Body::Form(key, value) => { + self.0.click("http-body-kind-3", "« Form »"); + self.0.fill_nth("http-kv-key", 0, "the field's name", key); + self.0.fill_nth("http-kv-value", 0, "the field's value", value); + } + Body::Multipart((key, value), file) => { + self.0.click("http-body-kind-4", "« Multipart »"); + self.0.fill_nth("http-part-key", 0, "the part's name", key); + self.0.fill_nth("http-part-value", 0, "the part's value", value); + self.0.fill_nth("http-part-key", 1, "the next part's name", file); + self.0.click_nth("http-part-kind", 1, "the next part's kind"); + self.0.click("http-part-choose", "the button that chooses its file"); + } + Body::File => { + self.0.click("http-body-kind-5", "« File »"); + self.0.click("http-body-choose", "the button that chooses the file"); + } + } + } + + /// Writes a script, over what it held. + pub fn type_script(&mut self, script: Script, code: &str) { + self.show_script(script); + self.type_over("http-script-code", "the script", code); + } + + /// Shows a script. + pub fn show_script(&mut self, script: Script) { + match script { + Script::Before => { + self.go_to("scripts"); + self.0.click("http-script-phase-0", "« Before the request »"); + } + Script::After => { + self.go_to("scripts"); + self.0.click("http-script-phase-1", "« After the response »"); + } + Script::Tests => self.go_to("tests"), + } + } + + /// Writes a GraphQL query. + pub fn type_query(&mut self, query: &str) { + self.go_to("query"); + self.type_over("http-graphql-query", "the query", query); + } + + /// Adds the variables the query lacks. + pub fn add_missing_variables(&mut self) { + self.0.click("http-graphql-add", "« Add »"); + } + + /// Sends it, Ctrl+Enter, whatever comes of it: the last answer is cleared before. + pub fn send(&mut self) { + if self.0.tree().has("http-response-clear") { + self.0.click("http-response-clear", "« Clear »"); + self.0 + .expect("the last answer is cleared", |tree| tree.has("http-response-idle")); + } + self.0.press(Shortcut::Send); + } + + /// Sends it to an address. + pub fn send_to(&mut self, url: &str) { + self.type_url(url); + self.send(); + } + + /// Cancels the send under way. + pub fn cancel_send(&mut self) { + self.0.expect("the send is under way", |tree| tree.has("http-response-sending")); + self.0.click("http-send", "« Cancel »"); + } + + /// Saves it, Ctrl+S. + pub fn save(&mut self) { + self.0.press(Shortcut::Save); + self.0.expect("the request is saved", |tree| tree.is_disabled("http-save")); + } + + /// Saves a draft, Ctrl+S, under a name, in the first place offered. + pub fn save_as(&mut self, name: &str) { + self.0.press(Shortcut::Save); + self.0.replace("http-save-name", "the request's name", name); + self.0.click("http-save-submit", "« Save »"); + self.0.expect("the request is saved", |tree| { + !tree.has("http-save-dialog") && tree.is_disabled("http-save") + }); + } + + /// Answers yes to the question of a protected environment. + pub fn send_anyway(&mut self) { + self.0.click("http-protected-send", "the yes"); + } + + /// Answers no to the question of a protected environment. + pub fn do_not_send(&mut self) { + self.0.click("http-protected-cancel", "« Cancel »"); + self.0.expect("the question goes", |tree| !tree.has("http-protected-confirm")); + } + + /// Points at a variable the request uses: its card. + pub fn point_at_variable(&mut self, name: &str) { + let written = format!("{{{{{name}}}}}"); + let place = self.0.place("the variable under the address", |tree| { + let mut chips = tree.all("http-used-variable").into_iter(); + chips.find(|chip| said(chip) == written).and_then(Node::bounds) + }); + self.0.move_over(place); + } + + /// Shows the secret of the card pointed at. + pub fn reveal_variable(&mut self) { + self.0.click("http-used-variable-reveal", "« Show »"); + } + + /// *Set in…*, on the card of a variable set nowhere. + pub fn define_variable(&mut self) { + self.0.click("http-used-variable-define", "« Set in… »"); + self.0.expect("where it goes is shown", |tree| tree.has("http-environments")); + } +} + +impl Request<'_> { + /// The address reads so. + pub fn expect_url(&mut self, url: &str, says: &str) { + self.0 + .expect(says, |tree| tree.find("http-url").and_then(Node::value) == Some(url)); + } + + /// The parameters are these, whether they are sent or not. + pub fn expect_params(&mut self, names: &[&str], says: &str) { + self.0.expect(says, |tree| { + let mut keys = values(tree, "http-kv-key"); + // The last row is the one to come. + keys.pop(); + keys == names + }); + } + + /// The first header is this, split into its two cells. + pub fn expect_first_header(&mut self, name: &str, value: &str, says: &str) { + self.0.expect(says, |tree| { + values(tree, "http-kv-key").first().map(String::as_str) == Some(name) + && values(tree, "http-kv-value").first().map(String::as_str) == Some(value) + }); + } + + /// The auth is inherited, and says from where. + pub fn expect_inherited_from(&mut self, name: &str, says: &str) { + self.go_to("auth"); + self.0 + .expect(says, |tree| tree.text("http-auth-inherited").is_some_and(|said| said.contains(name))); + } + + /// The auth's secret reads so. + pub fn expect_secret(&mut self, secret: &str, says: &str) { + self.0 + .expect(says, |tree| tree.find("http-auth-secret").and_then(Node::value) == Some(secret)); + } + + /// The auth's secret is masked. + pub fn expect_secret_masked(&mut self, secret: &str, says: &str) { + self.0.expect(says, |tree| { + tree.find("http-auth-secret") + .and_then(Node::value) + .is_some_and(|held| held != secret) + }); + } + + /// The body is a JSON that reads, and the type it leaves as is said. + pub fn expect_json_valid(&mut self, says: &str) { + self.0.expect(says, |tree| { + let sent_as = tree.text("http-body-type"); + tree.has("http-body-valid") && sent_as.is_some_and(|said| said.contains("application/json")) + }); + } + + /// The query's variables that have no value are named. + pub fn expect_missing_variable(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| { + tree.has("http-graphql-missing") + && tree.texts("http-graphql-variable").iter().any(|it| it == name) + }); + } + + /// The query lacks no variable. + pub fn expect_no_missing_variable(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("http-graphql-variables") && !tree.has("http-graphql-missing")); + } + + /// The card pointed at says a variable's value. + pub fn expect_variable_value(&mut self, value: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("http-used-variable-value").as_deref() == Some(value)); + } + + /// The card pointed at says where the variable comes from. + pub fn expect_variable_from(&mut self, place: &str, says: &str) { + self.0.expect(says, |tree| { + tree.text("http-used-variable-from").is_some_and(|said| said.contains(place)) + }); + } + + /// The card pointed at masks the variable's value. + pub fn expect_variable_masked(&mut self, says: &str) { + self.0.expect(says, |tree| { + tree.text("http-used-variable-value") + .is_some_and(|said| !said.is_empty() && said.chars().all(|it| it == '•')) + }); + } + + /// A protected environment asks before it leaves. + pub fn expect_asked_before_sending(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("http-protected-confirm") && !tree.has("http-response-status")); + } + + /// The script shown is this one. + pub fn expect_script(&mut self, code: &str, says: &str) { + self.0 + .expect(says, |tree| tree.find("http-script-code").and_then(Node::value) == Some(code)); + } + + /// Shows a part of the request, under « … » when the window is too narrow for its tab. + fn go_to(&mut self, part: &str) { + let tab = format!("http-section-{part}"); + let says = format!("the part « {part} » of the request"); + self.0.expect(&says, |tree| tree.has(&tab) || tree.has("http-section-more")); + if self.0.tree().has(&tab) { + self.0.click(&tab, &says); + } else { + self.0.click("http-section-more", "the parts left out"); + self.0.click(&format!("http-section-more-{part}"), &says); + } + } + + /// Types over what an editor of several lines holds. + fn type_over(&mut self, id: &str, name: &str, text: &str) { + self.0.take_keyboard(id, name); + self.0.press(Shortcut::SelectAll); + self.0.paste(text); + self.0 + .expect(&format!("{name} is typed"), |tree| tree.find(id).and_then(Node::value) == Some(text)); + } +} + +/// What the fields wearing `id` hold, in reading order. +fn values(tree: &Tree, id: &str) -> Vec { + let value = |node: &Node| node.value().unwrap_or_default().to_owned(); + tree.all(id).into_iter().map(value).collect() +} diff --git a/e2e/src/sdk/response.rs b/e2e/src/sdk/response.rs new file mode 100644 index 000000000..92ad5794c --- /dev/null +++ b/e2e/src/sdk/response.rs @@ -0,0 +1,198 @@ +use super::App; +use crate::driver::said; + +/// The answer under the request. +pub struct Response<'a>(pub(super) &'a mut App); + +/// How the body is read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BodyView { + Formatted, + Raw, + Graph, + Tree, +} + +/// A part of the answer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Part { + Body, + Tests, + Headers, + Cookies, + Timeline, +} + +impl Response<'_> { + /// Reads the body another way. + pub fn show_as(&mut self, view: BodyView) { + let (id, name) = match view { + BodyView::Formatted => ("http-response-view-0", "« Formatted »"), + BodyView::Raw => ("http-response-view-1", "« Raw »"), + BodyView::Graph => ("http-response-view-2", "« Graph »"), + BodyView::Tree => ("http-response-view-3", "« Tree »"), + }; + self.0.click(id, name); + } + + /// Shows a part of the answer. + pub fn go_to(&mut self, part: Part) { + let (id, name) = match part { + Part::Body => ("http-response-section-body", "« Body »"), + Part::Tests => ("http-response-section-tests", "« Tests »"), + Part::Headers => ("http-response-section-headers", "« Headers »"), + Part::Cookies => ("http-response-section-cookies", "« Cookies »"), + Part::Timeline => ("http-response-section-timeline", "« Timeline »"), + }; + self.0.click(id, name); + } + + /// Keeps the entry selected in the explorer in a variable, by a rule each answer follows. + pub fn extract_to(&mut self, variable: &str) { + self.0.click("json-extract", "« Extract to a variable »"); + self.0.replace("http-extract-name", "the variable's name", variable); + self.0.click("http-extract-submit", "« Extract »"); + self.0.expect("the rule is made", |tree| !tree.has("http-extract-dialog")); + } + + /// Saves the whole body in the file answered to the dialog. + pub fn save_to_file(&mut self) { + self.0.click("http-response-save", "« Save as a file »"); + } + + /// Keeps the answer as a note, under this title. + pub fn save_as_note(&mut self, title: &str) { + self.0.click("http-response-save-note", "« Save as note »"); + self.0.replace("save-as-note-title", "the note's title", title); + self.0.click("save-as-note-submit", "« Save »"); + self.0.expect("the note is saved", |tree| !tree.has("save-as-note-title")); + } + + /// Opens the script that stopped the send, at its line. + pub fn open_script(&mut self) { + self.0.click("http-script-open", "« Open the script »"); + } + + /// Lets the file a script asked for be sent. + pub fn allow_file(&mut self) { + self.0.click("http-script-file-send", "the yes"); + } + + /// Refuses the file a script asked for. + pub fn refuse_file(&mut self) { + self.0.click("http-script-file-cancel", "« Cancel »"); + self.0.expect("the question goes", |tree| !tree.has("http-script-file-confirm")); + } + + /// Opens the console. + pub fn open_console(&mut self) { + self.0.click("http-console-unfold", "the console's bar"); + } + + /// Empties the console. + pub fn clear_console(&mut self) { + self.0.click("http-console-clear", "the console's « Clear »"); + self.0.expect("the console is empty", |tree| !tree.has("http-console-line")); + } + + /// The answer came, with this status. + pub fn expect_status(&mut self, status: &str, says: &str) { + self.0.expect(says, |tree| { + tree.text("http-response-status").as_deref() == Some(status) && !tree.has("http-response-sending") + }); + } + + /// The answer says how long it took and how much it weighs. + pub fn expect_time_and_size(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("http-response-time") && tree.has("http-response-size")); + } + + /// The body says this. + pub fn expect_body(&mut self, words: &str, says: &str) { + self.0.expect(says, |tree| { + let read = tree.text("http-response-pretty").or_else(|| tree.text("http-response-body")); + read.is_some_and(|body| body.contains(words)) + }); + } + + /// The part shown says this. + pub fn expect_saying(&mut self, words: &str, says: &str) { + self.0.expect(says, |tree| tree.mentions(words)); + } + + /// The timeline shows what was sent, beginning so. + pub fn expect_sent(&mut self, start: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("http-response-sent").is_some_and(|sent| sent.starts_with(start))); + } + + /// The timeline shows as many redirects. + pub fn expect_redirects(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| tree.count("http-response-redirect") == count); + } + + /// The answer set this cookie. + pub fn expect_cookie(&mut self, name: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("http-response-cookie").iter().any(|it| it == name)); + } + + /// The body is a picture, shown. + pub fn expect_picture(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("http-response-image")); + } + + /// The send was cancelled. + pub fn expect_cancelled(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("http-response-cancelled")); + } + + /// The send was refused, and says this. + pub fn expect_refused(&mut self, words: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("http-response-failure").is_some_and(|said| said.contains(words))); + } + + /// A script stopped the send, its message and its line said. + pub fn expect_stopped(&mut self, message: &str, says: &str) { + self.0.expect(says, |tree| { + let stopped = tree.text("http-script-stop-message"); + tree.has("http-script-stop-where") && stopped.is_some_and(|said| said.contains(message)) + }); + } + + /// A script asks to send a file: nothing has left. + pub fn expect_file_asked(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| { + let asked = tree.text("http-script-file-confirm"); + !tree.has("http-response-status") && asked.is_some_and(|said| said.contains(name)) + }); + } + + /// Every test of the answer passed, this one among them. + pub fn expect_test_passed(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| { + tree.has("http-tests-passed") && tree.texts("http-test").iter().any(|it| it == name) + }); + } + + /// A test of the answer failed, with what it expected and what it received. + pub fn expect_test_failed(&mut self, name: &str, (expected, received): (&str, &str), says: &str) { + self.0.expect(says, |tree| { + let versus = tree.text("http-test-versus").unwrap_or_default(); + tree.has("http-tests-failed") + && tree.texts("http-test").iter().any(|it| it == name) + && versus.contains(expected) + && versus.contains(received) + }); + } + + /// The console heard this. + pub fn expect_console(&mut self, words: &str, says: &str) { + self.0.expect(says, |tree| { + let mut lines = tree.all("http-console-line").into_iter(); + lines.any(|line| said(line).contains(words)) + }); + } +} diff --git a/e2e/src/sdk/rich.rs b/e2e/src/sdk/rich.rs new file mode 100644 index 000000000..dde0dbbcc --- /dev/null +++ b/e2e/src/sdk/rich.rs @@ -0,0 +1,258 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut}; +use crate::driver::{Tree, is_on}; + +/// A Note's text, written formatted. +pub struct Rich<'a>(pub(super) &'a mut App); + +/// A button of the toolbar. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RichTool { + Heading1, + Heading2, + Heading3, + Bold, + Italic, + Strikethrough, + InlineCode, + BulletList, + NumberedList, + TaskList, + Quote, + CodeBlock, + Table, + RowBelow, + ColumnAfter, +} + +impl RichTool { + fn id(self) -> &'static str { + match self { + Self::Heading1 => "rich-h1", + Self::Heading2 => "rich-h2", + Self::Heading3 => "rich-h3", + Self::Bold => "rich-bold", + Self::Italic => "rich-italic", + Self::Strikethrough => "rich-strike", + Self::InlineCode => "rich-code", + Self::BulletList => "rich-bullet", + Self::NumberedList => "rich-ordered", + Self::TaskList => "rich-tasks", + Self::Quote => "rich-quote", + Self::CodeBlock => "rich-codeBlock", + Self::Table => "rich-table", + Self::RowBelow => "rich-rowAfter", + Self::ColumnAfter => "rich-columnAfter", + } + } +} + +impl Rich<'_> { + /// Types where the caret is, a letter at a time: what starts a line may format it. + pub fn type_keys(&mut self, text: &str) { + for letter in text.chars() { + self.0.type_text(&letter.to_string()); + } + } + + /// Clicks a button of the toolbar. + pub fn click(&mut self, tool: RichTool) { + self.0.click(tool.id(), "a button of the Note's toolbar"); + } + + /// A line of its own, formatted by a button: an Enter more leaves a list or a quote, a click + /// more the words' own format. + pub fn write_line(&mut self, tool: RichTool, text: &str) { + self.click(tool); + self.0.type_text(text); + self.0.press(Shortcut::Enter); + if self.0.tree().is_on(tool.id()) { + match tool { + RichTool::BulletList | RichTool::NumberedList | RichTool::TaskList | RichTool::Quote => { + self.0.press(Shortcut::Enter); + } + _ => self.click(tool), + } + } + self.0.expect("the next line is not formatted", |tree| !tree.is_on(tool.id())); + } + + /// Writes a code block, its language chosen from the keyboard in its menu. + pub fn write_code(&mut self, language: &str, code: &str) { + self.click(RichTool::CodeBlock); + self.0.type_text(code); + self.0.click("rich-code-language", "the menu of the block's language"); + self.0.take_keyboard("rich-code-language-filter", "the filter of the languages"); + self.0.type_text(language); + self.0.press(Shortcut::Enter); + self.0.expect("the menu closes", |tree| !tree.has("rich-code-language-filter")); + self.0.take_keyboard("editor-rich", "the Note's text"); + self.0.press(Shortcut::TextEnd); + } + + /// Writes a link at the caret, from its form. + pub fn write_link(&mut self, text: &str, address: &str) { + self.0.click("rich-link", "the link's button"); + self.0.fill("rich-link-text", "the link's text", text); + self.0.fill("rich-link-address", "the link's address", address); + self.0.press(Shortcut::Enter); + self.0.expect("the link's form closes", |tree| !tree.has("rich-link-apply")); + } + + /// Goes to the end of the Note, its caret on a line of its own. + pub fn go_to_end(&mut self) { + self.0.take_keyboard("editor-rich", "the Note's text"); + self.0.press(Shortcut::TextEnd); + self.0.press(Shortcut::Enter); + } + + /// Goes to the start of the Note, its caret on a line of its own. + pub fn go_to_start(&mut self) { + self.0.take_keyboard("editor-rich", "the Note's text"); + self.0.press(Shortcut::TextStart); + self.0.press(Shortcut::Enter); + self.0.press(Shortcut::Up); + } + + /// Ticks or unticks a task of the Note, counted from 0. + pub fn tick(&mut self, task: usize) { + self.0.click_nth("rich-task", task, "the task's box"); + } + + /// Puts the whole Note on the clipboard as Markdown, from the menu under the right button. + pub fn copy_as_markdown(&mut self) { + self.0.take_keyboard("editor-rich", "the Note's text"); + self.0.press(Shortcut::SelectAll); + self.0.right_click("editor-rich", "the Note's text"); + self.0.click("rich-menu-copy-markdown", "« Copy as Markdown »"); + } + + /// Puts the whole Note on the clipboard, whose table has as many rows — the header's among + /// them — and columns. + pub fn copy_table_and_expect(&mut self, rows: usize, columns: usize, says: &str) { + self.copy_as_markdown(); + self.0.clipboard().expect_that(says, |held| { + let lines = held.lines().filter(|line| line.starts_with('|') && !line.contains("---")); + let cells: Vec = lines.map(|line| line.matches('|').count() - 1).collect(); + cells.len() == rows && cells.iter().all(|count| *count == columns) + }); + } + + /// Inserts a drawing of the library, the first of the menu. + pub fn insert_drawing(&mut self) { + self.0.click("rich-embed-drawing", "the menu of the drawings"); + self.0.click("rich-embed-drawing-0", "the drawing"); + self.0.expect("the drawing is shown in the Note", |tree| tree.has("rich-embed")); + } + + /// Selects the drawing shown in the Note and gives it a part of the Note's width. + pub fn size_drawing(&mut self, size: DrawingSize) { + if !self.0.tree().has("rich-embed-resize") { + let drawing = |tree: &Tree| tree.find("rich-embed").and_then(Node::bounds); + let click = |app: &mut App| { + let place = app.place("the drawing in the Note", drawing); + app.click_top(place); + }; + self.0 + .click_until("the drawing in the Note", click, |tree| tree.has("rich-embed-resize")); + } + let id = match size { + DrawingSize::Quarter => "rich-embed-size-1", + DrawingSize::Whole => "rich-embed-size-4", + }; + self.0.click(id, "a width of the drawing"); + } + + /// Drags the corner of the drawing out to the right. + pub fn drag_drawing_corner_out(&mut self) { + self.0 + .drag_by("rich-embed-resize", "the drawing's corner", egui::vec2(1_200.0, 0.0)); + } + + /// The width of the drawing shown in the Note, in points. + pub fn drawing_width(&mut self) -> f64 { + self.0 + .expect("the drawing's corner is shown", |tree| tree.has("rich-embed-resize")); + drawn_width(&self.0.tree()) + } + + /// The drawing takes this part of `whole` in width. + pub fn expect_drawing_width(&mut self, whole: f64, part: f64, says: &str) { + self.0.expect(says, |tree| (drawn_width(tree) - whole * part).abs() < 2.0); + } + + /// The Note's text, as it is read. + pub fn expect_text(&mut self, text: &str, says: &str) { + self.0 + .expect(says, |tree| tree.find("editor-rich").and_then(Node::value) == Some(text)); + } + + /// A task of the Note is ticked, or not. + pub fn expect_ticked(&mut self, task: usize, ticked: bool, says: &str) { + self.0 + .expect(says, |tree| tree.all("rich-task").get(task).is_some_and(|task| is_on(task) == ticked)); + } +} + +/// How much of a Note's width a drawing takes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DrawingSize { + Quarter, + Whole, +} + +fn drawn_width(tree: &Tree) -> f64 { + tree.find("rich-embed") + .and_then(Node::bounds) + .map_or(0.0, |bounds| bounds.width()) +} + +/// A Note presented over the whole window. +pub struct Presentation<'a>(pub(super) &'a mut App); + +impl Presentation<'_> { + /// Presents the Note open. + pub fn open(&mut self) { + self.0.editor().click_button_or_entry("editor-present", "« Present »"); + self.0.expect("the cover is shown", |tree| tree.has("presentation-cover")); + } + + /// Opens the map of the headings. + pub fn open_map(&mut self) { + self.0.click("presentation-map", "« Map »"); + } + + /// Goes to the next slide by the arrow, and the count follows. + pub fn next(&mut self) { + let before = self.0.tree().text("presentation-count"); + self.0.press(Shortcut::Right); + self.0.expect("the next slide is shown", |tree| { + tree.has("presentation") && tree.text("presentation-count") != before + }); + } + + /// Leaves by Esc. + pub fn leave(&mut self) { + self.0.press(Shortcut::Escape); + self.0 + .expect("the Note is back", |tree| !tree.has("presentation") && tree.has("editor-title")); + } + + /// The slides are counted, the one shown first: « 1 / 4 » in any language's words. + pub fn expect_count(&mut self, at: usize, of: usize, says: &str) { + self.0.expect(says, |tree| { + let figures = tree.text("presentation-count").unwrap_or_default(); + let figures: Vec<&str> = figures + .split(|it: char| !it.is_ascii_digit()) + .filter(|it| !it.is_empty()) + .collect(); + figures == [at.to_string().as_str(), of.to_string().as_str()] + }); + } + + /// The map draws this many headings. + pub fn expect_map(&mut self, headings: usize, says: &str) { + self.0.expect(says, |tree| tree.count("presentation-map-node") == headings); + } +} diff --git a/e2e/src/sdk/runner.rs b/e2e/src/sdk/runner.rs new file mode 100644 index 000000000..a93f657dc --- /dev/null +++ b/e2e/src/sdk/runner.rs @@ -0,0 +1,105 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut}; +use crate::driver::said; + +/// A collection's run: its order, its settings and its results. +pub struct Runner<'a>(pub(super) &'a mut App); + +impl Runner<'_> { + /// Opens the run of a collection, from its ⋯ menu. + pub fn open(&mut self, collection: &str) { + self.0.http().open_menu(collection); + self.0.click("http-node-run", "« Run »"); + self.0.expect("its requests are listed", |tree| tree.has("http-runner-row")); + } + + /// Types over how many times the collection runs. + pub fn set_iterations(&mut self, count: &str) { + self.0.replace("http-runner-iterations", "the iterations", count); + self.0.expect("as many iterations are asked", |tree| { + tree.find("http-runner-iterations").and_then(Node::value) == Some(count) + }); + } + + /// Takes the data file answered to the dialog: an iteration a row. + pub fn choose_data(&mut self) { + self.0.click("http-runner-data-choose", "« Data file »"); + self.0.expect("the file is read", |tree| tree.has("http-runner-data")); + } + + /// Leaves a request out, or takes it back, by Space on its row. + pub fn flip_request(&mut self, name: &str) { + self.take_request(name); + self.0.press(Shortcut::Space); + } + + /// Moves a request down, by Alt+↓ on its row. + pub fn move_down(&mut self, name: &str) { + self.take_request(name); + self.0.press(Shortcut::MoveDown); + } + + /// Turns *Stop at the first failure* over. + pub fn flip_stop(&mut self) { + self.0.click("http-runner-stop", "« Stop at the first failure »"); + } + + /// Runs the collection until it is over. + pub fn run(&mut self) { + self.0.click("http-runner-start", "« Run »"); + self.0.expect("the run is over", |tree| { + let figures = tree.text("http-runner-figures"); + !tree.has("http-runner-cancel") && figures.is_some_and(|said| said.ends_with(" s")) + }); + } + + /// Shows the requests that failed alone. + pub fn show_failed(&mut self) { + self.0.click("http-runner-filter-failed", "« Failed »"); + } + + /// Shows every request that ran again. + pub fn show_all(&mut self) { + self.0.click("http-runner-filter-all", "« All »"); + } + + /// The requests run in this order. + pub fn expect_order(&mut self, names: &[&str], says: &str) { + self.0.expect(says, |tree| tree.texts("http-runner-row") == names); + } + + /// The results list as many iterations, requests that passed and requests that failed. + pub fn expect_results(&mut self, iterations: usize, (passed, failed): (usize, usize), says: &str) { + self.0.expect(says, |tree| { + tree.count("http-runner-iteration") == iterations + && tree.count("http-runner-result-passed") == passed + && tree.count("http-runner-result-failed") == failed + }); + } + + /// A request is nowhere among the results. + pub fn expect_not_run(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| { + let results = ["http-runner-result-passed", "http-runner-result-failed"]; + let listed = |id: &&str| tree.texts(id).iter().any(|result| result.ends_with(name)); + tree.has("http-runner-figures") && !results.iter().any(listed) + }); + } + + /// What failed is open on the assertion that did. + pub fn expect_assertion(&mut self, test: &str, versus: &str, says: &str) { + self.0.expect(says, |tree| { + let mut tests = tree.all("http-runner-test").into_iter(); + tests.any(|line| said(line).contains(test) && said(line).contains(versus)) + }); + } + + fn take_request(&mut self, name: &str) { + self.0 + .click_where("http-runner-row", "the request in the run", |row| said(row) == name); + self.0.expect("the row has the keyboard", |tree| { + tree.has_focus("http-runner-row") && tree.focused_says() == name + }); + } +} diff --git a/e2e/src/sdk/security.rs b/e2e/src/sdk/security.rs new file mode 100644 index 000000000..268390ee1 --- /dev/null +++ b/e2e/src/sdk/security.rs @@ -0,0 +1,87 @@ +use super::{App, Page}; + +/// The library's passphrase and its copies, on their pages of the preferences. +pub struct Security<'a>(pub(super) &'a mut App); + +impl Security<'_> { + /// Opens the dialog that changes the passphrase. + pub fn ask_change(&mut self) { + self.0.prefs().open(); + self.0.prefs().go_to(Page::Security); + self.0.click("setting-change-passphrase", "« Change… »"); + self.0.expect("the dialog opens", |tree| tree.has("change-passphrase")); + } + + /// Tries the change: the phrase as it is said to be, then the new one, twice. + pub fn try_change(&mut self, current: &str, next: &str) { + self.0.expect("the fields can be typed in", |tree| { + tree.find("change-passphrase-current").is_some_and(|field| !field.is_disabled()) + }); + self.0.fill("change-passphrase-current", "the current phrase", current); + self.0.fill("change-passphrase-next", "the new phrase", next); + self.0.fill("change-passphrase-confirmation", "its confirmation", next); + self.0.click("change-passphrase-submit", "« Change »"); + } + + /// Opens the page of the copies. + pub fn open_copies(&mut self) { + self.0.prefs().open(); + self.0.prefs().go_to(Page::Copies); + } + + /// Asks to put the last copy back: the page says what it would do. + pub fn ask_restore(&mut self) { + self.0 + .reach("settings-content", ("backup-restore", "« Restore »"), "settings-cancel"); + self.0.click("backup-restore", "« Restore »"); + self.0 + .expect("the page says what it would do", |tree| tree.has("backup-confirm")); + } + + /// Answers no. + pub fn cancel_restore(&mut self) { + self.0 + .reach("settings-content", ("backup-cancel", "« Cancel »"), "settings-cancel"); + self.0.click("backup-cancel", "« Cancel »"); + self.0.expect("the question goes", |tree| !tree.has("backup-confirm")); + } + + /// Answers yes: the gate asks for the phrase of the copy put back. + pub fn confirm_restore(&mut self) { + let yes = ("backup-confirm-restore", "the yes"); + self.0.reach("settings-content", yes, "settings-cancel"); + self.0.click("backup-confirm-restore", "the yes"); + self.0.gate().expect_phrase_asked("the gate asks for the phrase"); + } + + /// The change is refused, and says why. + pub fn expect_refused(&mut self, says: &str) { + self.0.expect(says, |tree| { + tree.has("change-passphrase") + && tree.text("change-passphrase-problem").is_some_and(|said| !said.is_empty()) + }); + } + + /// The passphrase is changed, and the session carries on. + pub fn expect_changed(&mut self, says: &str) { + self.0 + .expect(says, |tree| !tree.has("change-passphrase") && tree.has("settings-dialog")); + self.0.notes().clear_toasts(); + self.0.prefs().close(); + self.0.expect("the notes are still there", |tree| tree.has("note-card")); + } + + /// As many copies are kept, each with when it was taken. + pub fn expect_copies(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| { + let details = tree.texts("backup-detail"); + details.len() == count && details.iter().all(|detail| is_stamped(detail)) + }); + } +} + +/// Whether a copy says its instant first: « 2026-12-04_09-00-00 ». +fn is_stamped(words: &str) -> bool { + let stamp = words.split_whitespace().next().unwrap_or_default(); + stamp.len() == 19 && stamp.as_bytes()[10] == b'_' +} diff --git a/e2e/src/sdk/selection.rs b/e2e/src/sdk/selection.rs new file mode 100644 index 000000000..ddfb5d358 --- /dev/null +++ b/e2e/src/sdk/selection.rs @@ -0,0 +1,79 @@ +use super::{App, Modifiers, Shortcut}; + +/// The cards ticked together, and the bar that acts on them. +pub struct Selection<'a>(pub(super) &'a mut App); + +impl Selection<'_> { + /// Ticks or unticks a card by its box. + pub fn tick(&mut self, title: &str) { + self.0.notes().click_box(title); + } + + /// Ticks a card by a click with Ctrl held. + pub fn ctrl_click(&mut self, title: &str) { + self.0.notes().click_holding(Modifiers::COMMAND, title); + } + + /// Ticks the cards from the last one ticked to this one, by a click with Shift held. + pub fn shift_click(&mut self, title: &str) { + self.0.notes().click_holding(Modifiers::SHIFT, title); + } + + /// Moves the notes to a space or a folder, by the end of the place's name. + pub fn move_to(&mut self, place: &str) { + self.0.click("selection-move", "« Move to… »"); + let inside = format!(" › {place}"); + self.0.click_where("selection-move-place", "the place to move to", |entry| { + entry.label().is_some_and(|name| name == place || name.ends_with(&inside)) + }); + } + + /// Takes the notes out of every folder: the first place of the menu. + pub fn take_out_of_folders(&mut self) { + self.0.click("selection-move", "« Move to… »"); + self.0.click("selection-move-place", "« No folder »"); + } + + /// Adds a tag to the notes. + pub fn add_tag(&mut self, tag: &str) { + self.0.fill("selection-tag", "the field of a tag to add", tag); + self.0.press(Shortcut::Enter); + } + + /// Gives the notes the urgent priority, from the menu of what is left. + pub fn make_urgent(&mut self) { + self.0.click("selection-more", "the selection's « ⋯ »"); + self.0.click("selection-more-priority", "« Priority »"); + self.0.click("selection-more-priority-4", "« Urgent »"); + } + + /// Puts the notes on the clipboard as Markdown. + pub fn copy_as_markdown(&mut self) { + self.0.click("selection-more", "the selection's « ⋯ »"); + self.0.click("selection-more-copy", "« Copy as Markdown »"); + } + + /// Sends the notes to the trash: the second click does it. + pub fn delete(&mut self) { + self.0.click("selection-delete", "the selection's « Delete »"); + self.0.click("selection-delete", "« Delete » again"); + } + + /// Lets the cards go, by the bar's cross. + pub fn clear(&mut self) { + self.0.click("selection-clear", "the selection's cross"); + self.expect_none("the selection is let go"); + } + + /// As many cards are ticked, and counted. + pub fn expect(&mut self, count: usize, says: &str) { + let count = count.to_string(); + self.0 + .expect(says, |tree| tree.text("selection-count").is_some_and(|said| said.contains(&count))); + } + + /// No card is ticked. + pub fn expect_none(&mut self, says: &str) { + self.0.expect(says, |tree| !tree.has("selection-count")); + } +} diff --git a/e2e/src/sdk/sends.rs b/e2e/src/sdk/sends.rs new file mode 100644 index 000000000..22b5e5681 --- /dev/null +++ b/e2e/src/sdk/sends.rs @@ -0,0 +1,65 @@ +use super::App; +use crate::driver::said; + +/// The history of what was sent. +pub struct Sends<'a>(pub(super) &'a mut App); + +impl Sends<'_> { + /// Opens its page, from the rail. + pub fn open(&mut self) { + self.0.click("http-history-open", "« History » in the rail"); + self.0.expect("the history is shown", |tree| tree.has("http-history")); + } + + /// Goes back to the requests. + pub fn leave(&mut self) { + self.0.click("http-history-open", "« History » in the rail"); + self.0.expect("the requests are back", |tree| !tree.has("http-history")); + } + + /// Reads the last send of a request. + pub fn read_last_of(&mut self, request: &str) { + self.0 + .click_where("http-history-item", "the send in the history", |item| said(item) == request); + self.0.expect("the send is shown", |tree| tree.has("http-history-url")); + } + + /// Reopens the send read, over what its request or its draft holds now. + pub fn reopen(&mut self) { + self.0.click("http-history-reopen", "« Reopen »"); + self.0 + .expect("the page answers", |tree| tree.has("http-history-replace") || !tree.has("http-history")); + if self.0.tree().has("http-history-replace") { + self.0.click("http-history-replace-confirm", "« Replace »"); + } + self.0 + .expect("the request is back", |tree| !tree.has("http-history") && tree.has("http-url")); + } + + /// Erases the first send listed. + pub fn erase_first(&mut self) { + let sends = self.0.tree().count("http-history-item"); + self.0.hover("http-history-item", "the first send"); + self.0.click("http-history-delete", "its cross"); + self.0.expect("it is gone", |tree| tree.count("http-history-item") + 1 == sends); + } + + /// Erases every send, asked twice. + pub fn erase_all(&mut self) { + self.0.click("http-history-clear", "« Clear »"); + self.0.click("http-history-clear-confirm", "« Clear » again"); + self.expect_none("nothing is listed any more"); + } + + /// Nothing is listed. + pub fn expect_none(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("http-history") && tree.has("http-history-empty")); + } + + /// The send read shows nothing of a secret. + pub fn expect_masked(&mut self, secret: &str, says: &str) { + self.0 + .expect(says, |tree| tree.has("http-history-url") && !tree.mentions(secret)); + } +} diff --git a/e2e/src/sdk/shortcut.rs b/e2e/src/sdk/shortcut.rs new file mode 100644 index 000000000..45978f18b --- /dev/null +++ b/e2e/src/sdk/shortcut.rs @@ -0,0 +1,120 @@ +use egui::{Key, Modifiers}; + +/// A shortcut as a person knows it: what it does, whatever key of their keyboard says it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shortcut { + /// Esc. + Escape, + /// Enter. + Enter, + /// Tab. + Tab, + /// The arrows. + Up, + Down, + Left, + Right, + /// The end of the line. + LineEnd, + /// The start of the text, its end. + TextStart, + TextEnd, + /// Ctrl+N: a code snippet. + NewSnippet, + /// Ctrl+Shift+N: a Note. + NewNote, + /// Ctrl+Shift+L: a todo list. + NewTodoList, + /// Ctrl+Shift+M: a calculation. + NewCalculation, + /// Ctrl+Shift+D: a drawing. + NewDrawing, + /// Ctrl+B and Ctrl+I, in a Note. + Bold, + Italic, + /// Alt+↑: moves what has the keyboard up. + MoveUp, + /// Alt+↓: moves what has the keyboard down. + MoveDown, + /// Alt+→: moves what has the keyboard into what is above it. + MoveIn, + /// Alt+←: moves what has the keyboard out of what it is in. + MoveOut, + /// Space. + Space, + /// Ctrl+Enter: sends the request open. + Send, + /// Ctrl+S: saves the request open. + Save, + /// Del. + Delete, + /// Ctrl+Z. + Undo, + /// Ctrl+A. + SelectAll, + /// Ctrl+Alt+P: the palette. + Palette, + /// Ctrl+K: the search. + Search, + /// Ctrl+Shift+T: the search of the tools. + SearchTools, + /// Ctrl+F. + Find, + /// Ctrl+Alt+G. + GoToLine, + /// Shift+Alt+F. + Format, + /// Ctrl+1, Ctrl+2 and Ctrl+3. + NotesArea, + ToolsArea, + HttpArea, + /// Ctrl+B: the side rail. + SideRail, + /// A letter or a digit on the card that has the keyboard. + CardKey(Key), +} + +impl Shortcut { + pub(crate) fn keys(self) -> (Key, Modifiers) { + match self { + Self::Escape => (Key::Escape, Modifiers::NONE), + Self::Enter => (Key::Enter, Modifiers::NONE), + Self::Tab => (Key::Tab, Modifiers::NONE), + Self::Up => (Key::ArrowUp, Modifiers::NONE), + Self::Down => (Key::ArrowDown, Modifiers::NONE), + Self::Left => (Key::ArrowLeft, Modifiers::NONE), + Self::LineEnd => (Key::End, Modifiers::NONE), + Self::Right => (Key::ArrowRight, Modifiers::NONE), + Self::TextStart => (Key::Home, Modifiers::COMMAND), + Self::TextEnd => (Key::End, Modifiers::COMMAND), + Self::NewSnippet => (Key::N, Modifiers::COMMAND), + Self::NewNote => (Key::N, Modifiers::COMMAND | Modifiers::SHIFT), + Self::NewTodoList => (Key::L, Modifiers::COMMAND | Modifiers::SHIFT), + Self::NewCalculation => (Key::M, Modifiers::COMMAND | Modifiers::SHIFT), + Self::NewDrawing => (Key::D, Modifiers::COMMAND | Modifiers::SHIFT), + Self::Italic => (Key::I, Modifiers::COMMAND), + Self::MoveUp => (Key::ArrowUp, Modifiers::ALT), + Self::MoveDown => (Key::ArrowDown, Modifiers::ALT), + Self::MoveIn => (Key::ArrowRight, Modifiers::ALT), + Self::Space => (Key::Space, Modifiers::NONE), + Self::Send => (Key::Enter, Modifiers::COMMAND), + Self::Save => (Key::S, Modifiers::COMMAND), + Self::MoveOut => (Key::ArrowLeft, Modifiers::ALT), + Self::Delete => (Key::Delete, Modifiers::NONE), + Self::Undo => (Key::Z, Modifiers::COMMAND), + Self::SelectAll => (Key::A, Modifiers::COMMAND), + Self::Palette => (Key::P, Modifiers::COMMAND | Modifiers::ALT), + Self::Search => (Key::K, Modifiers::COMMAND), + Self::SearchTools => (Key::T, Modifiers::COMMAND | Modifiers::SHIFT), + Self::Find => (Key::F, Modifiers::COMMAND), + Self::GoToLine => (Key::G, Modifiers::COMMAND | Modifiers::ALT), + Self::Format => (Key::F, Modifiers::SHIFT | Modifiers::ALT), + Self::NotesArea => (Key::Num1, Modifiers::COMMAND), + Self::ToolsArea => (Key::Num2, Modifiers::COMMAND), + Self::HttpArea => (Key::Num3, Modifiers::COMMAND), + Self::CardKey(key) => (key, Modifiers::NONE), + // The same keys: in a Note they are the text's. + Self::SideRail | Self::Bold => (Key::B, Modifiers::COMMAND), + } + } +} diff --git a/e2e/src/sdk/socket.rs b/e2e/src/sdk/socket.rs new file mode 100644 index 000000000..7c0b270b0 --- /dev/null +++ b/e2e/src/sdk/socket.rs @@ -0,0 +1,47 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut}; +use crate::driver::said; + +/// The WebSocket open: its message and its log. +pub struct Socket<'a>(pub(super) &'a mut App); + +impl Socket<'_> { + /// Connects it, or disconnects it. + pub fn flip_connection(&mut self) { + self.0.click("http-socket-connect", "« Connect »"); + } + + /// Sends a message, Ctrl+Enter. + pub fn send(&mut self, message: &str) { + self.0.replace("http-socket-message", "the message", message); + self.0.expect("the message is typed", |tree| { + tree.find("http-socket-message").and_then(Node::value) == Some(message) + }); + self.0.press(Shortcut::Send); + } + + /// Keeps the message written. + pub fn keep(&mut self) { + self.0.click("http-socket-keep", "« Keep »"); + self.0.expect("the message is kept", |tree| tree.has("http-socket-saved")); + } + + /// Sends the first message kept. + pub fn send_kept(&mut self) { + self.0.click("http-socket-saved-send", "the « Send » of the message kept"); + } + + /// The log has as many lines. + pub fn expect_log(&mut self, lines: usize, says: &str) { + self.0.expect(says, |tree| tree.count("http-socket-entry") == lines); + } + + /// The log says a message as many times: sent, and received. + pub fn expect_logged(&mut self, message: &str, times: usize, says: &str) { + self.0.expect(says, |tree| { + let lines = tree.all("http-socket-entry").into_iter(); + lines.filter(|line| said(line).contains(message)).count() == times + }); + } +} diff --git a/e2e/src/sdk/tags.rs b/e2e/src/sdk/tags.rs new file mode 100644 index 000000000..2d7e56355 --- /dev/null +++ b/e2e/src/sdk/tags.rs @@ -0,0 +1,75 @@ +use egui::accesskit::Node; + +use super::App; + +/// The manager of the library's tags. +pub struct Tags<'a>(pub(super) &'a mut App); + +impl Tags<'_> { + /// Ticks a tag of the list, its name filled in the field. + pub fn tick(&mut self, tag: &str) { + let row = format!("#{tag}"); + self.0 + .click_where("tag-item", "the tag in the list", |item| item.label() == Some(row.as_str())); + self.0.expect("its name fills the field", |tree| { + tree.find("tag-target").and_then(Node::value) == Some(tag) + }); + } + + /// Types another name over the ticked tag's, and asks for it: what it would touch is said. + pub fn ask_rename(&mut self, name: &str) { + self.0.replace("tag-target", "the tag's new name", name); + self.0.click("tag-apply", "« Rename »"); + self.expect_asked(); + } + + /// Asks to delete the ticked tag: what it would touch is said. + pub fn ask_delete(&mut self) { + self.0.click("tag-delete", "« Delete »"); + self.expect_asked(); + } + + /// Goes through with what was asked. + pub fn confirm(&mut self) { + self.0.click("tag-confirm-apply", "the button that goes through with it"); + self.0.expect("it is done", |tree| !tree.has("tag-confirm-apply")); + } + + /// Gives up what was asked. + pub fn give_up(&mut self) { + self.0.click("tag-confirm-cancel", "« Cancel »"); + self.0 + .expect("nothing is asked any more", |tree| !tree.has("tag-confirm-apply")); + } + + /// Closes the manager. + pub fn close(&mut self) { + self.0.click("tag-manager-close", "the manager's cross"); + self.0.expect("the manager closes", |tree| !tree.has("tag-manager-close")); + } + + /// What was asked says how many notes it would touch. + pub fn expect_touching(&mut self, notes: usize, says: &str) { + let notes = notes.to_string(); + self.0 + .expect(says, |tree| tree.text("tag-confirm-text").is_some_and(|said| said.contains(¬es))); + } + + /// The list holds this tag. + pub fn expect_listed(&mut self, tag: &str, says: &str) { + let row = format!("#{tag}"); + self.0.expect(says, |tree| tree.texts("tag-item").contains(&row)); + } + + /// The list does not hold this tag. + pub fn expect_gone(&mut self, tag: &str, says: &str) { + let row = format!("#{tag}"); + self.0 + .expect(says, |tree| tree.has("tag-manager-close") && !tree.texts("tag-item").contains(&row)); + } + + fn expect_asked(&mut self) { + self.0 + .expect("what it would touch is said", |tree| tree.has("tag-confirm-text")); + } +} diff --git a/e2e/src/sdk/todo.rs b/e2e/src/sdk/todo.rs new file mode 100644 index 000000000..286fd48e3 --- /dev/null +++ b/e2e/src/sdk/todo.rs @@ -0,0 +1,74 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut}; +use crate::driver::{Tree, is_on}; + +/// The todo list open. +pub struct Todo<'a>(pub(super) &'a mut App); + +impl Todo<'_> { + /// Adds a task, typed. + pub fn add(&mut self, words: &str) { + self.add_empty(); + self.0.type_text(words); + } + + /// Adds an empty task, the keyboard in it. + pub fn add_empty(&mut self) { + let before = self.0.tree().count("checklist-text"); + self.0.click("checklist-add", "« Add a task »"); + self.0.expect("a new row takes the keyboard", |tree| { + tree.count("checklist-text") == before + 1 && tree.has_focus("checklist-text") + }); + } + + /// Splits a task before its last word, by Enter. + pub fn split_before(&mut self, task: usize, last_word: &str) { + self.take(task); + self.0.press(Shortcut::LineEnd); + for _ in last_word.chars() { + self.0.press(Shortcut::Left); + } + self.0.press(Shortcut::Enter); + } + + /// Moves a task up, Alt+↑. + pub fn move_up(&mut self, task: usize) { + self.take(task); + self.0.press(Shortcut::MoveUp); + } + + /// Ticks or unticks a task. + pub fn tick(&mut self, task: usize) { + self.0.click_nth("checklist-check", task, "the task's box"); + } + + /// Removes a task by its cross. + pub fn remove(&mut self, task: usize) { + self.0.click_nth("checklist-remove", task, "the task's cross"); + } + + /// The tasks, top to bottom. + pub fn expect(&mut self, tasks: &[&str], says: &str) { + self.0.expect(says, |tree| words(tree) == tasks); + } + + /// Which tasks are ticked, top to bottom. + pub fn expect_ticked(&mut self, ticked: &[bool], says: &str) { + self.0.expect(says, |tree| { + let boxes: Vec = tree.all("checklist-check").into_iter().map(is_on).collect(); + boxes == ticked + }); + } + + fn take(&mut self, task: usize) { + self.0.click_nth("checklist-text", task, "the task"); + self.0 + .expect("the task has the keyboard", |tree| tree.has_focus("checklist-text")); + } +} + +fn words(tree: &Tree) -> Vec { + let rows = tree.all("checklist-text").into_iter(); + rows.map(|row| Node::value(row).unwrap_or_default().to_owned()).collect() +} diff --git a/e2e/src/sdk/tools.rs b/e2e/src/sdk/tools.rs new file mode 100644 index 000000000..194f70c2a --- /dev/null +++ b/e2e/src/sdk/tools.rs @@ -0,0 +1,275 @@ +use egui::accesskit::Node; + +use super::{App, Shortcut, clipboard}; +use crate::driver::said; + +/// The tools area: its home and the tool that is open. +pub struct Tools<'a>(pub(super) &'a mut App); + +/// What a tool is given to answer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Given { + /// Its *Example*. + Example, + /// Words searched in its table. + Search(&'static str), +} + +/// What copying one of a tool's answers gives, each answer by its name. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Copied { + /// What is shown. + Shown(&'static str), + /// What is shown, and by *Raw* what is written here. + Raw(&'static str, &'static str), + /// A text holding what is written here, shown otherwise. + Holding(&'static str, &'static str), + /// Nothing is to be copied. + Nothing, +} + +impl Tools<'_> { + /// Goes to the tools and their search, Ctrl+Shift+T. + pub fn go_to_search(&mut self) { + self.0.press(Shortcut::SearchTools); + self.expect_search_ready("the tools' search has the keyboard"); + } + + /// Searches the tools and their references, over what was searched. + pub fn search(&mut self, words: &str) { + self.0.press(Shortcut::SelectAll); + self.0.type_text(words); + self.0.expect("the search answers", |tree| tree.has("tools-first-result")); + } + + /// Opens the first answer of the search, by Enter. + pub fn open_first(&mut self) { + self.0.press(Shortcut::Enter); + self.expect_tool_open("the first answer opens"); + } + + /// Empties the search, by Esc. + pub fn clear_search(&mut self) { + self.0.press(Shortcut::Escape); + self.0 + .expect("the whole catalogue is back", |tree| !tree.has("tools-first-result")); + } + + /// Leaves one category on the home, from the rail. + pub fn choose_category(&mut self, name: &str) { + self.click_named("tools-rail-category-", name, "the category in the rail"); + } + + /// Goes back to every tool, from the rail. + pub fn show_all(&mut self) { + self.0.click("tools-rail-all", "« All tools »"); + } + + /// Opens a tool from the home, by the name it goes by in the catalogue. + pub fn open(&mut self, tool: &str) { + self.0.click(&format!("tools-entry-{tool}"), "the tool on the home"); + self.expect_tool_open("the tool opens"); + } + + /// Opens a tool from the keyboard: its name searched, walked down to and opened. + pub fn open_from_the_keyboard(&mut self, name: &str) { + self.go_to_search(); + self.search(name); + self.expect_listed(name, "the search finds the tool"); + for _ in 0..40 { + if self.0.tree().focused_says() == name { + break; + } + self.0.press(Shortcut::Down); + } + self.0.press(Shortcut::Enter); + self.expect_open(name, "the tool opens"); + } + + /// Stars the tool open, or takes its star off. + pub fn flip_star(&mut self) { + self.0.click("tool-favourite", "the tool's star"); + } + + /// Gives the tool what it answers. + pub fn give(&mut self, given: Given) { + match given { + Given::Example => self.0.click("tool-sample", "« Example »"), + Given::Search(words) => { + self.0.expect("the table is shown", |tree| tree.has("reference-row")); + let rows = self.0.tree().count("reference-row"); + self.0.replace("reference-search", "the table's search", words); + self.0.expect("the search narrows the table", |tree| { + (1..rows).contains(&tree.count("reference-row")) + }); + } + } + } + + /// The tool answers this, among other things. + pub fn expect_answer(&mut self, words: &str, says: &str) { + self.0.expect(says, |tree| tree.mentions(words)); + } + + /// An answer is copied as it should. + pub fn expect_copied(&mut self, copied: Copied, says: &str) { + match copied { + Copied::Shown(name) => self.expect_copied_as_shown(name), + Copied::Raw(name, raw) => { + self.expect_copied_as_shown(name); + let named = format!(" {name},"); + self.0.click_where("copy-raw", "the answer's « Raw »", |button| { + said(button).contains(&named) + }); + self.0.clipboard().expect(raw, says); + } + Copied::Holding(name, words) => { + self.copy(name); + self.0.clipboard().expect_saying(words, says); + } + Copied::Nothing => {} + } + } + + /// *Save as note*: the answer filed with a title, in a folder of a space, with a tag. + pub fn save_as_note(&mut self, title: &str, (space, folder): (&str, &str), tag: &str) { + self.0.click("tool-save-as-note", "« Save as note »"); + self.0.replace("save-as-note-title", "the note's title", title); + self.choose("save-as-note-space", "the note's space", space); + self.choose("save-as-note-folder", "the note's folder", folder); + self.0.fill("save-as-note-tags", "the note's tags", tag); + self.0.click("save-as-note-submit", "« Save »"); + self.0.expect("the note is saved", |tree| !tree.has("save-as-note-title")); + } + + /// Fills the tool's text from a note, found in the picker by its title. + pub fn fill_from_note(&mut self, title: &str) { + self.0.click("note-import-text", "« Import from a note »"); + self.0.fill("note-picker-search", "the picker's search", title); + self.0 + .click_where("note-picker-option", "the note in the picker", |note| said(note) == title); + } + + /// Hashes the file answered to the dialog. + pub fn hash_file(&mut self) { + self.0.click("hash-source-1", "« File »"); + self.0.click("hash-pick-file", "the button that picks a file"); + } + + /// Reads the file answered to the dialog into Base64. + pub fn encode_file(&mut self) { + self.0.click("base64-source-1", "« File »"); + self.0.click("base64-pick-file", "the button that picks a file"); + self.0.expect("the file is read", |tree| tree.has("base64-file")); + } + + /// Decodes what the clipboard holds. + pub fn decode_what_was_copied(&mut self) { + let copied = clipboard::held(); + self.0.click("base64-direction-1", "« Decode »"); + self.0.take_keyboard("base64-input", "the text to decode"); + self.0.paste(&copied); + } + + /// Saves the bytes decoded as the file answered to the dialog. + pub fn save_decoded(&mut self) { + self.0.click("base64-save-file", "the button that saves the bytes"); + } + + /// Saves the code drawn as a PNG, in the file answered to the dialog. + pub fn save_code_as_png(&mut self) { + self.0.click("qr-png", "« PNG »"); + } + + /// Saves the code drawn as an SVG, in the file answered to the dialog. + pub fn save_code_as_svg(&mut self) { + self.0.click("qr-svg", "« Download SVG »"); + } + + /// Saves the people drawn, in the file answered to the dialog. + pub fn export_people(&mut self) { + self.0.click("identity-export", "« Export… »"); + } + + /// The tools are on the screen, the keyboard in their search. + pub fn expect_search_ready(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("area-tools") && tree.has_focus("tools-search")); + } + + /// A tool is listed on the home. + pub fn expect_listed(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| tree.named("tools-entry-", name).is_some()); + } + + /// A tool is not listed on the home. + pub fn expect_not_listed(&mut self, name: &str, says: &str) { + self.0 + .expect(says, |tree| tree.has("tools-search") && tree.named("tools-entry-", name).is_none()); + } + + /// The whole catalogue is listed, and it holds as many tools. + pub fn expect_catalogue_of(&mut self, count: usize, says: &str) { + self.0.expect(says, |tree| { + let entries = tree.all_starting("tools-entry-").into_iter(); + entries.filter(|id| !id.starts_with("tools-entry-star-")).count() == count + }); + } + + /// A tool is open. + pub fn expect_tool_open(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("area-tools") && tree.has("tool-title")); + } + + /// The tool of this name is open. + pub fn expect_open(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| tree.text("tool-title").as_deref() == Some(name)); + } + + /// A tool is among the favourites on the home. + pub fn expect_favourite(&mut self, name: &str, says: &str) { + self.0.expect(says, |tree| tree.named("tools-favourite-", name).is_some()); + } + + /// The last tools opened, on the home. + pub fn expect_recent(&mut self, names: &[&str], says: &str) { + self.0 + .expect(says, |tree| names.iter().all(|name| tree.named("tools-recent-", name).is_some())); + } + + /// The picture decoded is shown, with what it is. + pub fn expect_picture(&mut self, what: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("base64-image-facts").is_some_and(|facts| facts.contains(what))); + } + + /// Copies an answer: every line of what is copied is on the screen. + /// Copied again while the clipboard holds another answer than the one shown: one still on + /// its way lands after the first click. + fn expect_copied_as_shown(&mut self, name: &str) { + let answered = |tree: &crate::driver::Tree| { + let held = clipboard::held(); + !held.is_empty() && held.lines().all(|line| tree.mentions(line)) + }; + self.0.click_until("the answer's copy", |app| Tools(app).copy(name), answered); + } + + fn copy(&mut self, name: &str) { + let named = format!(" {name}"); + self.0 + .click_where("copy-value", "the answer's copy", |button| said(button).ends_with(&named)); + } + + /// Chooses a place in a menu of *Save as note*. + fn choose(&mut self, menu: &str, name: &str, place: &str) { + self.0.click(menu, name); + self.click_named(&format!("{menu}-"), place, "the place in the menu"); + } + + fn click_named(&mut self, start: &str, label: &str, name: &str) { + let id = self.0.seen(&format!("{name} is on the screen"), |tree| { + tree.named(start, label).and_then(Node::author_id).map(str::to_owned) + }); + self.0.click(&id, name); + } +} diff --git a/e2e/src/sdk/transfer.rs b/e2e/src/sdk/transfer.rs new file mode 100644 index 000000000..7fdaa706f --- /dev/null +++ b/e2e/src/sdk/transfer.rs @@ -0,0 +1,108 @@ +use super::{App, Shortcut}; + +/// What leaves the library and what comes in: the *File* menu's exports and imports, to and from +/// the file answered to the dialog. +pub struct Transfer<'a>(pub(super) &'a mut App); + +/// What an export takes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Export { + Everything, + /// The space shown. + Space, + /// The cards ticked. + Selection, +} + +impl Transfer<'_> { + /// Asks for an export, whatever comes of it. + pub fn ask(&mut self, export: Export) { + self.0.click("file-menu", "the « File » menu"); + match export { + Export::Everything => self.0.click("file-option-exportAll", "« Export everything… »"), + Export::Space => self.0.click("file-option-exportSpace", "« Export the space… »"), + Export::Selection => self.0.click("file-option-exportSelection", "« Export the selection… »"), + } + } + + /// Exports in the clear. + pub fn export(&mut self, export: Export) { + self.ask(export); + self.0 + .click("passphrase-prompt-plain", "the button that leaves it in the clear"); + self.expect_prompt_closed(); + } + + /// Exports under a phrase. + pub fn export_sealed(&mut self, export: Export, phrase: &str) { + self.ask(export); + self.0.fill("passphrase-prompt-field", "the file's phrase", phrase); + self.0.fill("passphrase-prompt-confirmation", "its confirmation", phrase); + self.0.click("passphrase-prompt-submit", "« Protect »"); + self.expect_prompt_closed(); + } + + /// Gives the export asked up, by Esc on its phrase. + pub fn give_up(&mut self) { + self.0 + .expect("the export asks for a phrase", |tree| tree.has("passphrase-prompt")); + self.0.press(Shortcut::Escape); + self.expect_prompt_closed(); + } + + /// Imports the file. + pub fn import(&mut self) { + self.0.click("file-menu", "the « File » menu"); + self.0.click("file-option-import", "« Import… »"); + } + + /// Tries a phrase on the file imported. + pub fn try_phrase(&mut self, phrase: &str) { + self.0.expect("the import asks for the file's phrase", |tree| { + tree.find("passphrase-prompt-field").is_some_and(|field| !field.is_disabled()) + }); + self.0.fill("passphrase-prompt-field", "the file's phrase", phrase); + self.0.click("passphrase-prompt-submit", "« Open »"); + } + + /// *Copy selection as Markdown*. + pub fn copy_selection_as_markdown(&mut self) { + self.0.click("file-menu", "the « File » menu"); + self.0.click("file-option-copyMarkdown", "« Copy selection as Markdown »"); + } + + /// The operation reports, saying this among other things; the report is then dismissed. + pub fn expect_reported(&mut self, words: &str, says: &str) { + self.0 + .expect(says, |tree| tree.texts("status-toast").iter().any(|said| said.contains(words))); + self.0.notes().clear_toasts(); + } + + /// The phrase is not the file's, and the import says so. + pub fn expect_wrong_phrase(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.text("passphrase-prompt-problem").is_some_and(|said| !said.is_empty())); + } + + /// No phrase is asked: the operation ended before. + pub fn expect_nothing_asked(&mut self, says: &str) { + self.0 + .expect_at_rest(says, |tree| tree.has("file-menu") && !tree.has("passphrase-prompt")); + } + + /// The menu offers the selection's entries only when something is selected. + pub fn expect_selection_waiting(&mut self, says: &str) { + self.0.click("file-menu", "the « File » menu"); + self.0.expect(says, |tree| { + tree.is_disabled("file-option-exportSelection") + && tree.is_disabled("file-option-copyMarkdown") + && !tree.is_disabled("file-option-exportAll") + }); + self.0.press(Shortcut::Escape); + self.0.expect("the menu closes", |tree| !tree.has("file-option-exportAll")); + } + + fn expect_prompt_closed(&mut self) { + self.0.expect("the prompt closes", |tree| !tree.has("passphrase-prompt")); + } +} diff --git a/e2e/src/sdk/trash.rs b/e2e/src/sdk/trash.rs new file mode 100644 index 000000000..eb024a7bd --- /dev/null +++ b/e2e/src/sdk/trash.rs @@ -0,0 +1,58 @@ +use super::{App, Shortcut}; + +/// The trash's panel. +pub struct Trash<'a>(pub(super) &'a mut App); + +impl Trash<'_> { + /// Opens the trash from the notes' header. + pub fn open(&mut self) { + self.0.click("trash-open", "the trash's button"); + self.0.expect("the trash opens", |tree| tree.has("trash-close")); + } + + /// Closes the panel. + pub fn close(&mut self) { + self.0.press(Shortcut::Escape); + self.0.expect("the trash closes", |tree| !tree.has("trash-close")); + } + + /// Restores a note, by its title. + pub fn restore(&mut self, title: &str) { + let row = self.row(title); + self.0.click_nth("trash-restore", row, "the note's « Restore »"); + } + + /// Deletes a note for good, by its title: the second click does it. + pub fn purge(&mut self, title: &str) { + let row = self.row(title); + self.0.click_nth("trash-purge", row, "the note's « Delete for good »"); + self.0 + .expect("the first click deletes nothing", |tree| tree.texts("trash-row-title").len() > row); + self.0.click_nth("trash-purge", row, "the note's « Delete for good », again"); + } + + /// Empties the trash, once it has said what it erases. + pub fn empty(&mut self) { + self.0.click("trash-empty", "« Empty the trash »"); + self.0 + .expect("the trash says what it erases", |tree| tree.has("trash-empty-warning")); + self.0.click("trash-empty-confirm", "« Empty »"); + } + + /// The trash holds these notes, in any order. + pub fn expect(&mut self, titles: &[&str], says: &str) { + self.0.expect(says, |tree| { + let mut held = tree.texts("trash-row-title"); + let mut wanted = titles.to_vec(); + held.sort(); + wanted.sort_unstable(); + held == wanted && (!titles.is_empty() || tree.has("trash-empty-state")) + }); + } + + fn row(&mut self, title: &str) -> usize { + self.0.seen(&format!("« {title} » is in the trash"), |tree| { + tree.texts("trash-row-title").iter().position(|row| row == title) + }) + } +} diff --git a/e2e/src/sdk/tray.rs b/e2e/src/sdk/tray.rs new file mode 100644 index 000000000..2d003c391 --- /dev/null +++ b/e2e/src/sdk/tray.rs @@ -0,0 +1,188 @@ +use super::App; + +/// The icon in the system's tray, and its menu. +pub struct Tray<'a>(pub(super) &'a mut App); + +/// An entry of the tray's menu. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrayEntry { + Open, + NewNote, + PasteFromClipboard, + Palette, + Quit, +} + +impl Tray<'_> { + /// Chooses an entry of the menu: under Linux on the item itself, served on the journey's bus; on + /// the others, whose icon no driver reaches, as the menu hands it over. + pub fn choose(&mut self, entry: TrayEntry) { + #[cfg(target_os = "linux")] + self.0.session.as_ref().expect("the journey has its own bus").click(entry); + #[cfg(not(target_os = "linux"))] + self.0.driver.hand_over(Some(match entry { + TrayEntry::Open => "tray:open", + TrayEntry::NewNote => "tray:new-note", + TrayEntry::PasteFromClipboard => "tray:capture", + TrayEntry::Palette => "tray:palette", + TrayEntry::Quit => "tray:quit", + })); + } +} + +/// A session bus, a `StatusNotifierWatcher` and a host's calls, as a panel makes them. +#[cfg(target_os = "linux")] +pub(super) mod linux { + use std::cell::OnceCell; + use std::collections::HashMap; + use std::io::{BufRead, BufReader}; + use std::process::{Child, Command, Stdio}; + use std::sync::mpsc::{self, Receiver, Sender}; + + use zbus::blocking::{Connection, Proxy}; + use zbus::zvariant::{OwnedObjectPath, OwnedValue, Structure, Value}; + + use super::TrayEntry; + use crate::driver::PATIENCE; + + /// An entry of a menu as dbusmenu sends it: id, properties, children. + type Entry = (i32, HashMap, Vec); + + /// The journey's own: the machine's may have a panel on it, or no bus at all. + pub(crate) struct Session { + daemon: Child, + pub(crate) address: String, + watcher: OnceCell, + menu: OnceCell, + } + + impl Session { + pub(crate) fn start() -> Self { + let mut daemon = Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address"]) + .stdout(Stdio::piped()) + .spawn() + .expect("dbus-daemon runs"); + let mut address = String::new(); + BufReader::new(daemon.stdout.take().expect("its address")) + .read_line(&mut address) + .expect("dbus-daemon says its address"); + Session { + daemon, + address: address.trim().to_owned(), + watcher: OnceCell::new(), + menu: OnceCell::new(), + } + } + + /// The panel comes after the application, as a session's may. + pub(super) fn click(&self, entry: TrayEntry) { + let watcher = self.watcher.get_or_init(|| Watcher::serve(&self.address)); + self.menu.get_or_init(|| Menu::of(watcher)).click(entry); + } + } + + impl Drop for Session { + fn drop(&mut self) { + let _ = self.daemon.kill(); + let _ = self.daemon.wait(); + } + } + + /// The one call an item makes of a watcher; a host's calls are made from here. + struct Registry { + told: Sender, + } + + #[zbus::interface(name = "org.kde.StatusNotifierWatcher")] + impl Registry { + /// By its bus name, or by its path from its own connection. + #[expect(clippy::needless_pass_by_value, reason = "zbus hands the header over by value")] + fn register_status_notifier_item( + &self, + service: &str, + #[zbus(header)] header: zbus::message::Header<'_>, + ) { + let name = if service.starts_with('/') { + header.sender().map(ToString::to_string).unwrap_or_default() + } else { + service.to_owned() + }; + let _ = self.told.send(name); + } + } + + struct Watcher { + connection: Connection, + registered: Receiver, + } + + impl Watcher { + fn serve(address: &str) -> Self { + let (told, registered) = mpsc::channel(); + let connection = zbus::blocking::connection::Builder::address(address) + .unwrap() + .name("org.kde.StatusNotifierWatcher") + .unwrap() + .serve_at("/StatusNotifierWatcher", Registry { told }) + .unwrap() + .build() + .unwrap(); + Watcher { connection, registered } + } + } + + /// The item's menu as a host reads it, its separators left out. + struct Menu { + proxy: Proxy<'static>, + entries: Vec, + } + + impl Menu { + /// Of the first item to register: a condition, waited for. + fn of(watcher: &Watcher) -> Self { + let item = watcher + .registered + .recv_timeout(PATIENCE) + .expect("an item registers with the watcher"); + let sni = Proxy::new( + &watcher.connection, + item.clone(), + "/StatusNotifierItem", + "org.kde.StatusNotifierItem", + ) + .unwrap(); + let path: OwnedObjectPath = sni.get_property("Menu").unwrap(); + let proxy = + Proxy::new(&watcher.connection, item, path.as_str().to_owned(), "com.canonical.dbusmenu") + .unwrap(); + let (_, (_, _, children)): (u32, Entry) = + proxy.call("GetLayout", &(0_i32, 1_i32, Vec::::new())).unwrap(); + let entries = children.iter().filter_map(entry).collect(); + Menu { proxy, entries } + } + + fn click(&self, entry: TrayEntry) { + let at = match entry { + TrayEntry::Open => 0, + TrayEntry::NewNote => 1, + TrayEntry::PasteFromClipboard => 2, + TrayEntry::Palette => 3, + TrayEntry::Quit => 4, + }; + self.proxy + .call::<_, _, ()>("Event", &(self.entries[at], "clicked", Value::from(0_i32), 0_u32)) + .unwrap(); + } + } + + /// An entry's id; `None` for a separator. + fn entry(child: &OwnedValue) -> Option { + let child = Structure::try_from(child.try_clone().unwrap()).expect("an entry"); + let fields = child.fields(); + let id = i32::try_from(&fields[0]).expect("an entry's id"); + let properties = HashMap::::try_from(fields[1].try_clone().unwrap()).unwrap(); + let kind = properties.get("type").and_then(|kind| kind.downcast_ref::().ok()); + (kind.as_deref() != Some("separator")).then_some(id) + } +} diff --git a/e2e/src/sdk/window.rs b/e2e/src/sdk/window.rs new file mode 100644 index 000000000..10110f13f --- /dev/null +++ b/e2e/src/sdk/window.rs @@ -0,0 +1,185 @@ +use egui::accesskit::Node; + +use super::App; +use crate::current_step; +use crate::driver::{Tree, middle}; + +/// The window itself: its title bar and what the system does with it. +pub struct Window<'a>(pub(super) &'a mut App); + +/// An area of the application. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Area { + Notes, + Tools, + Http, +} + +impl Window<'_> { + /// Goes to an area by the switch of the areas. + pub fn go_to(&mut self, area: Area) { + match area { + Area::Notes => self.0.click("area-option-notes", "« Notes » among the areas"), + Area::Tools => self.0.click("area-option-tools", "« Tools » among the areas"), + Area::Http => self.0.click("area-option-http", "« HTTP » among the areas"), + } + } + + /// Makes the window wide enough for a note beside its cards, or over them with its details. + pub fn widen(&mut self) { + self.0.wide = true; + self.0.driver.resize(1_440, 900); + } + + /// Switches between dark and light from the title bar. + pub fn switch_theme(&mut self) { + self.0.click("theme-toggle", "the theme's button"); + } + + /// Maximises the window, or restores it, by its control. + pub fn maximize_or_restore(&mut self) { + self.0.click("window-maximize", "the window's « Maximise »"); + } + + /// Double-clicks the empty part of the title bar. + pub fn double_click_title_bar(&mut self) { + let toggle = self + .0 + .place("the theme's button", |tree| tree.find("theme-toggle").and_then(Node::bounds)); + self.0.double_click(middle(toggle) - egui::vec2(100.0, 0.0)); + } + + /// Minimises the window by its control. + pub fn minimize(&mut self) { + self.0.put_away = self.times_put_away(); + self.0.click("window-minimize", "the window's « Minimise »"); + } + + /// Minimises the window, « Minimize to tray » on: until the system says it is minimised, which + /// the preference acts on. + pub fn minimize_to_tray(&mut self) { + self.minimize(); + self.0.driver.settle_out_of_sight(); + } + + /// Closes the window as its close button does, DevNotes staying in the tray. + pub fn close_to_tray(&mut self) { + self.0.put_away = self.times_put_away(); + self.0.driver.hand_over(Some("close")); + self.0.driver.settle_out_of_sight(); + } + + /// Starts DevNotes a second time while it runs. + pub fn start_again(&mut self) { + self.0.launch_again(); + } + + /// Closes the window, DevNotes ending with it: by its control, or as macOS' own does. + pub fn close_for_good(&mut self) { + if cfg!(target_os = "macos") { + self.0.driver.hand_over(Some("close")); + } else { + self.0.click("window-close", "the window's « Close »"); + } + } + + /// The word the title bar has for the theme it would switch to, which says the theme on. + pub fn theme_offered(&mut self) -> String { + self.0.tree().text("theme-toggle").unwrap_or_default() + } + + /// The window wears another theme than the one that offered `word`. + pub fn expect_theme_changed(&mut self, word: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("theme-toggle").is_some_and(|now| now != word)); + } + + /// The window wears the theme that offers `word`. + pub fn expect_theme(&mut self, word: &str, says: &str) { + self.0.expect(says, |tree| tree.text("theme-toggle").as_deref() == Some(word)); + } + + /// The name of the window's control that maximises, which is another once it would restore. + pub fn maximize_offered(&mut self) -> String { + self.0 + .expect("the window's controls are drawn", |tree| tree.has("window-maximize")); + self.0.tree().text("window-maximize").unwrap_or_default() + } + + /// The window is maximised: its control no longer offers `word`. + pub fn expect_maximized(&mut self, word: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("window-maximize").is_some_and(|now| now != word)); + } + + /// The window is restored: its control offers `word` again. + pub fn expect_restored(&mut self, word: &str, says: &str) { + self.0 + .expect(says, |tree| tree.text("window-maximize").as_deref() == Some(word)); + } + + /// The window has no control of DevNotes' own: the system draws its three buttons. + pub fn expect_system_buttons(&mut self, says: &str) { + self.0 + .expect(says, |tree| !tree.has("window-maximize") && !tree.has("window-close")); + } + + /// This area is on the screen. + pub fn expect_area(&mut self, area: Area, says: &str) { + let id = match area { + Area::Notes => "area-notes", + Area::Tools => "area-tools", + Area::Http => "area-http", + }; + self.0.expect(says, |tree| tree.has(id)); + } + + /// The side rail is put away: the areas' switch stands in the title bar. + pub fn expect_rail_away(&mut self, says: &str) { + self.0.expect(says, switch_in_the_bar); + } + + /// The side rail is there, the areas' switch in it. + pub fn expect_rail(&mut self, says: &str) { + self.0 + .expect(says, |tree| tree.has("area-option-notes") && !switch_in_the_bar(tree)); + } + + /// The window speaks the language that names the « File » menu so. + pub fn expect_file_menu(&mut self, word: &str, says: &str) { + self.0.expect(says, |tree| tree.text("file-menu").as_deref() == Some(word)); + } + + /// The window went out of sight once since it was put away, and is back. + pub fn expect_back(&mut self, says: &str) { + let before = self.0.put_away; + let gone = |tree: &Tree| times(tree).is_some_and(|now| now > before); + self.0.expect(&format!("{says}: it went out of sight"), gone); + self.0 + .expect(&format!("{says}: it is in sight again"), |tree| tree.has("window-shown")); + let since = self.times_put_away() - before; + assert_eq!(since, 1, "« {} »: {says} — it went out of sight {since} times", current_step()); + } + + /// The window never left the screen. + pub fn expect_in_sight(&mut self, says: &str) { + self.0.expect(says, |tree| tree.has("window-shown")); + } + + /// How many times the window went out of sight. + fn times_put_away(&mut self) -> u32 { + times(&self.0.tree()).expect("the e2e flavour counts the window put away") + } +} + +fn times(tree: &Tree) -> Option { + tree.text("window-put-away").and_then(|count| count.parse().ok()) +} + +/// The areas' switch beside the theme's button, above the notes' header. +fn switch_in_the_bar(tree: &Tree) -> bool { + let top = |id| tree.find(id).and_then(Node::bounds).map(|bounds| bounds.y0); + top("area-option-notes") + .zip(top("theme-toggle")) + .is_some_and(|(switch, bar)| switch < bar + 20.0) +} diff --git a/e2e/src/server.rs b/e2e/src/server.rs index 33bef7d18..42bbf3e9a 100644 --- a/e2e/src/server.rs +++ b/e2e/src/server.rs @@ -1,14 +1,14 @@ -//! A server on this machine for the scenarios' sends, as the reference's suite had: `/json` -//! answers a small JSON and sets a cookie, `/slow` the same after two seconds, `/echo` what it -//! was sent, `/redirect/N` N redirects then `/json`, `/bytes` what is no text, `/png` a picture, +//! A server on this machine for the journeys' sends: `/json` answers a small JSON and sets a +//! cookie, `/slow` the same after two seconds, `/echo` what it was sent, `/redirect/N` N redirects +//! then `/json`, `/large` more than an answer shows, `/bytes` what is no text, `/png` a picture, //! anything else is a 404. Each connection is answered once, then closed. use std::io::{Read, Write}; use std::net::{Ipv4Addr, TcpListener, TcpStream}; use std::time::Duration; -/// Its port: the server lives as long as the scenario's process. -pub fn serve() -> u16 { +/// Its port: the server lives as long as the journey's process. +pub(crate) fn serve() -> u16 { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("a local port is free"); let port = listener.local_addr().expect("the port is known").port(); std::thread::spawn(move || { @@ -19,8 +19,47 @@ pub fn serve() -> u16 { port } -/// A socket server echoing each text, for the scenarios' connections; its port. -pub fn serve_socket() -> u16 { +/// A server publishing a version far ahead of this one, with its notes; the address of its +/// `latest.json`. Nothing is downloaded from it. +pub(crate) fn publish_update() -> String { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("a local port is free"); + let origin = format!("http://{}", listener.local_addr().expect("the address is known")); + let entry = + serde_json::json!({ "signature": "", "url": format!("{origin}/installer"), "format": "nsis" }); + let manifest = serde_json::json!({ + "version": "99.0.0", + "notes": "### Added + +- Everything", + "pub_date": "2026-12-03T00:00:00Z", + "platforms": { + "windows-x86_64": entry, + "linux-x86_64": entry, + "macos-aarch64": entry, + "macos-x86_64": entry, + }, + }) + .to_string(); + std::thread::spawn(move || { + for mut stream in listener.incoming().flatten() { + let _ = stream.read(&mut [0; 1024]); + let length = manifest.len(); + let head = format!( + "HTTP/1.1 200 OK +Content-Length: {length} +Connection: close + +" + ); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(manifest.as_bytes()); + } + }); + format!("{origin}/latest.json") +} + +/// A socket server echoing each text, for the journeys' connections; its port. +pub(crate) fn serve_socket() -> u16 { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("a local port is free"); let port = listener.local_addr().expect("the port is known").port(); std::thread::spawn(move || { @@ -51,7 +90,7 @@ fn answer(mut stream: TcpStream) { let head = String::from_utf8_lossy(&head).into_owned(); let path = head.split_whitespace().nth(1).unwrap_or("/").to_owned(); if path.starts_with("/slow") { - #[expect(clippy::disallowed_methods, reason = "the server's own latency, not a scenario waiting")] + #[expect(clippy::disallowed_methods, reason = "the server's own latency, not a journey waiting")] std::thread::sleep(Duration::from_secs(2)); } let sent = body_of(&mut stream, &head); @@ -108,6 +147,9 @@ fn reply(path: &str, head: &str, sent: &[u8]) -> Reply { if path.starts_with("/bytes") { return plain("200 OK", "application/octet-stream", &[0xff; 2048]); } + if path.starts_with("/large") { + return plain("200 OK", "text/plain", &vec![b'x'; 2 * 1024 * 1024]); + } if path.starts_with("/png") { return plain("200 OK", "image/png", PIXEL); } @@ -115,7 +157,7 @@ fn reply(path: &str, head: &str, sent: &[u8]) -> Reply { } /// One white pixel. -const PIXEL: &[u8] = &[ +pub(crate) const PIXEL: &[u8] = &[ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x09, diff --git a/e2e/tests/01_first_day.rs b/e2e/tests/01_first_day.rs new file mode 100644 index 000000000..9a774582c --- /dev/null +++ b/e2e/tests/01_first_day.rs @@ -0,0 +1,121 @@ +//! Journey 1, « First day »: a machine where DevNotes never ran. The gate makes the library, a real +//! relaunch opens it, and the samples are walked as their own list proposes. + +use e2e::{App, JsonView, PASSPHRASE, Sample, Shortcut, step}; + +#[test] +fn first_day() { + let mut app = App::first_launch("01_first_day"); + + making_the_library(&mut app); + coming_back(&mut app); + first_tour(&mut app); + the_documentation(&mut app); + + app.quit(); +} + +fn making_the_library(app: &mut App) { + // Typed in two goes: the start alone is under the floor of twelve characters. + let (start, rest) = PASSPHRASE.split_at(7); + + step("the first launch asks to protect the library, and says nothing in the terminal", || { + app.gate().expect_new_phrase_asked("the phrase is asked twice"); + app.expect_silent_terminal("the launch wrote nothing in the terminal"); + app.capture("gate"); + }); + + step("a phrase under twelve characters is refused", || { + app.gate().type_phrase(start); + app.gate().confirm_phrase(start); + app.gate().expect_phrase_refused("the button stays out of reach"); + }); + + step("two phrases that differ are refused", || { + app.gate().type_phrase(rest); + app.gate().expect_phrases_differ("the gate says the two phrases differ"); + }); + + step("a good phrase, twice, opens the notes on their samples", || { + app.gate().confirm_phrase(rest); + app.gate().submit(); + app.notes().expect_samples("the sample notes are on the screen"); + app.capture("samples"); + }); +} + +fn coming_back(app: &mut App) { + step("quit and started again, DevNotes asks for the phrase, once", || { + app.relaunch(); + app.gate().expect_phrase_asked("the phrase is asked once"); + }); + + step("a wrong phrase is refused, and nothing opens", || { + app.gate().try_phrase("not the phrase"); + app.gate().expect_wrong_phrase("the gate says the phrase is wrong"); + }); + + step("the right one opens the library, its samples seeded once", || { + app.gate().unlock(PASSPHRASE); + app.notes().expect_samples("the sample notes are on the screen"); + }); +} + +fn first_tour(app: &mut App) { + step("a sample opens from its card", || { + app.notes().open(Sample::Welcome); + app.editor().expect_note_open("the welcome is read formatted"); + app.editor().close(); + }); + + step("« psql connection » is copied with its fields filled", || { + app.notes().copy_filled(Sample::PsqlConnection); + app.fields().type_value(0, "db.internal"); + app.fields().copy(); + app.clipboard() + .expect_saying("psql -h db.internal -p 5432", "the connection is copied, filled"); + }); + + step("the API response opens as a graph", || { + app.notes().open(Sample::ApiResponse); + app.json().show_as(JsonView::Graph); + app.json().expect_nodes(3, "the response is drawn as a graph"); + app.editor().close(); + }); + + step("a word is found in « Release day »", || { + app.notes().open(Sample::ReleaseDay); + app.editor().find("kubectl"); + app.editor().expect_matches("1 / 1", "the word is found once"); + app.editor().close_find(); + app.editor().close(); + }); + + step("the snippet to format is formatted", || { + app.notes().open(Sample::SnippetToFormat); + app.press(Shortcut::Format); + app.editor().expect_several_lines("the code is laid out"); + app.editor().close(); + }); + + step("an item of « Things to try » is ticked from its card", || { + app.notes().tick_on_card(Sample::ThingsToTry, 0); + app.notes() + .expect_progress(Sample::ThingsToTry, "1/9", "the card counts one thing tried"); + }); +} + +fn the_documentation(app: &mut App) { + step("the documentation opens without the network, each page of its kind", || { + app.help().open_documentation(); + app.help().expect_documentation("its eleven pages are listed"); + app.capture("documentation"); + app.help() + .expect_every_page_read("each page has its sections, the overview its cards"); + }); + + step("Esc goes back to the notes", || { + app.press(Shortcut::Escape); + app.notes().expect_card(Sample::Welcome, "the notes are where they were left"); + }); +} diff --git a/e2e/tests/01_first_launch.rs b/e2e/tests/01_first_launch.rs deleted file mode 100644 index 43600bcdc..000000000 --- a/e2e/tests/01_first_launch.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! A blank profile: the gate creates the library, then a real relaunch unlocks it. - -use e2e::{App, PASSPHRASE, step}; - -#[test] -fn first_launch() { - let profile = tempfile::tempdir().unwrap(); - let terminal = tempfile::NamedTempFile::new().unwrap(); - let mut app = App::launch_writing_to("01_first_launch", profile.path(), terminal.path()); - // Typed in two goes: the start alone is under the floor of twelve characters. - let (start, rest) = PASSPHRASE.split_at(7); - - step("a blank profile opens on the gate, asking the phrase twice", || { - app.wait_for("vault-confirmation"); - assert!(!app.has("area-switch")); - app.capture("gate-create"); - }); - - // Only Linux is launched from a terminal often enough for its lines to be read as faults. - // Mesa's pair about DRI3 is Xvfb's, which has none: no desktop's X server lacks it. - step("the launch wrote nothing in the terminal", || { - let said = std::fs::read_to_string(terminal.path()).unwrap(); - let faults: Vec<&str> = said - .lines() - .filter(|line| !(line.starts_with("libEGL warning:") && line.contains("DRI3"))) - .collect(); - if cfg!(target_os = "linux") { - assert!(faults.is_empty(), "the launch wrote:\n{said}"); - } - }); - - step("a phrase under twelve characters cannot be chosen", || { - app.fill("vault-passphrase", start); - app.fill("vault-confirmation", start); - app.eventually("the submit is disabled", |tree| { - tree.find("vault-submit").is_some_and(egui::accesskit::Node::is_disabled) - }); - }); - - step("a long enough phrase, twice, creates the library and opens it", || { - app.fill("vault-passphrase", rest); - app.fill("vault-confirmation", rest); - app.click("vault-submit"); - app.wait_for("area-notes"); - assert!(app.has("area-switch")); - }); - - // Nothing compares a seeded word: the samples are in the system's language. - step("a new library opens on its six samples, one left out of the folders", || { - app.eventually("the six cards are drawn", |tree| tree.count("note-card") == 6); - assert_eq!(app.tree().count("note-card-folder"), 5); - assert!(!app.has("error-banner")); - app.capture("first-launch-samples"); - }); - - let mut app = app.relaunch(); - - step("a relaunch asks for the phrase once", || { - app.wait_for("vault-passphrase"); - assert!(!app.has("vault-confirmation")); - }); - - step("a wrong phrase is refused and says so", || { - app.fill("vault-passphrase", "not the phrase"); - app.click("vault-submit"); - app.eventually("the problem line speaks", |tree| { - tree.text("vault-problem").is_some_and(|said| !said.is_empty()) - }); - assert!(!app.has("area-notes")); - app.capture("gate-wrong"); - }); - - step("the phrase chosen opens the library, its samples seeded once", || { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("the six cards are drawn", |tree| tree.count("note-card") == 6); - }); - - app.quit(); -} diff --git a/e2e/tests/02_note_lifecycle.rs b/e2e/tests/02_note_lifecycle.rs deleted file mode 100644 index d95083469..000000000 --- a/e2e/tests/02_note_lifecycle.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! Creating a note writes nothing until it is worth saving, and the editor writes on the way -//! out: two rules about a row in the database, proved on the assembled window. - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; -const TITLE: &str = "Rotate the staging certificate"; -const BODY: &str = "openssl req -new -key staging.key -out staging.csr"; - -fn cards(app: &mut App, count: usize, what: &str) { - app.eventually(what, |tree| tree.count("note-card") == count); -} - -#[test] -fn note_lifecycle() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("02_note_lifecycle", profile.path()); - app.create_library(); - cards(&mut app, CARDS, "the samples are drawn"); - - step("a card names its kind by an icon, and only a snippet its format", || { - let tree = app.tree(); - assert_eq!(tree.count("kind-icon"), CARDS); - let formats = tree.count("note-format"); - assert!(formats > 0 && formats < CARDS, "{formats} formats"); - // Title bar over status line, on every card. - for (icon, when) in tree.all("kind-icon").iter().zip(tree.all("note-card-when")) { - let (icon, when) = (icon.bounds().unwrap(), when.bounds().unwrap()); - assert!(icon.y1 <= when.y0, "{icon:?} over {when:?}"); - } - }); - - step("a new note opens as a draft that is not yet a note", || { - app.click("new-note"); - app.wait_for("editor-title"); - // Beside the editor fewer cards fit on screen, none in a narrow window: none is added. - let drawn = app.tree().count("note-card"); - assert!(drawn <= CARDS, "{drawn} cards drawn"); - }); - - step("it is written once it carries something worth keeping", || { - app.fill("editor-title", TITLE); - app.fill("editor-body", BODY); - app.capture("editor-draft"); - app.click("editor-close"); - app.eventually("the editor is closed and the note is a card", |tree| { - !tree.has("editor-title") && tree.texts("note-card").contains(&TITLE.to_owned()) - }); - cards(&mut app, CARDS + 1, "one card more, and only one"); - }); - - step("the ghost opens a draft, and closed untouched it writes nothing", || { - app.scroll_to("canvas", "create-ghost"); - app.scroll_above("canvas", "create-ghost", "canvas-keyboard-hint"); - app.at_rest("create-ghost"); - app.click("create-ghost"); - app.wait_for("editor-title"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - // Under a header of two rows the top ones went out of view, and were not counted. - app.scroll_top("canvas"); - cards(&mut app, CARDS + 1, "no card more"); - }); - - step("the kind menu opens the same draft as the button", || { - app.click("new-note-kind"); - app.click("new-note-snippet"); - app.wait_for("editor-title"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - cards(&mut app, CARDS + 1, "no card more"); - }); - - step("each kind opens from its own key, and writes nothing untouched", || { - for (key, shift) in [(Key::N, false), (Key::N, true), (Key::L, true)] { - let modifiers = if shift { Modifiers::COMMAND | Modifiers::SHIFT } else { Modifiers::COMMAND }; - app.press(key, modifiers); - app.wait_for("editor-title"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - } - cards(&mut app, CARDS + 1, "no card more"); - assert!(app.has("canvas-keyboard-hint")); - }); - - step("a note opened from its card shows what was written", || { - app.click_where("note-card-open", |node| node.label() == Some(TITLE)); - app.eventually("the note is read back whole", |tree| { - tree.find("editor-body").and_then(egui::accesskit::Node::value) == Some(BODY) - }); - app.click("editor-close"); - }); - - let mut app = app.relaunch(); - - step("the note is read back from the library on a relaunch", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("its card is there", |tree| tree.texts("note-card").contains(&TITLE.to_owned())); - }); - - app.quit(); -} diff --git a/e2e/tests/02_snippet_to_paste.rs b/e2e/tests/02_snippet_to_paste.rs new file mode 100644 index 000000000..eda999423 --- /dev/null +++ b/e2e/tests/02_snippet_to_paste.rs @@ -0,0 +1,279 @@ +//! Journey 2, « A snippet, from writing to pasting »: written with its fields, copied filled, +//! formatted, explored when it is JSON, its draft kept whatever happens around it, and reached from +//! the keyboard. + +use e2e::{App, JsonView, Key, Sample, Shortcut, step}; + +const JUMP: &str = "Jump host"; +const SAMPLES: usize = 6; + +#[test] +fn snippet_to_paste() { + let mut app = App::open("02_snippet_to_paste"); + app.window().widen(); + + writing(&mut app); + copying(&mut app); + formatting(&mut app); + exploring(&mut app); + keeping_the_draft(&mut app); + from_the_keyboard(&mut app); + + app.quit(); +} + +fn writing(app: &mut App) { + step("an empty snippet left by Esc writes nothing", || { + app.press(Shortcut::NewSnippet); + app.editor().expect_code_open("a snippet is open"); + app.editor().leave_by_escape(); + app.notes().expect_cards(SAMPLES, "no note was written"); + }); + + step("a title, a language, code with fields, a context and tags make a note", || { + app.press(Shortcut::NewSnippet); + app.editor().type_title(JUMP); + app.editor().choose_language("rust"); + app.editor().type_code("ssh {{host}} -p {{port=22}}"); + app.editor().type_context("runbooks/ssh.md"); + app.editor().add_tag("remote"); + app.editor().add_tag("shell"); + app.editor().expect_footer("RS", "the footer says the language"); + app.editor().expect_footer("· 1 ", "the footer counts one line"); + app.capture("snippet"); + app.editor().leave_by_escape(); + }); + + step("its card shows them", || { + app.notes() + .expect_card_wearing(JUMP, "RS", "2", "the card wears its language and its fields"); + app.notes().expect_cards(SAMPLES + 1, "one note was written"); + app.notes().open(JUMP); + app.editor().expect_context("runbooks/ssh.md", "the context was written"); + app.editor().close(); + }); +} + +fn copying(app: &mut App) { + step("copied from its card, it asks for its fields and is copied filled", || { + app.notes().copy_filled(JUMP); + app.fields().type_value(0, "db.internal"); + app.capture("fields"); + app.fields().copy(); + app.clipboard() + .expect("ssh db.internal -p 22", "the field left empty takes the value the text suggests"); + }); + + step("what was typed comes back, and cancelling keeps nothing", || { + app.notes().copy_filled(JUMP); + app.fields().expect_value(0, "db.internal", "the value typed comes back"); + app.fields().type_value(0, "db.discarded"); + app.fields().cancel(); + app.notes().copy_filled(JUMP); + app.fields().expect_value(0, "db.internal", "what was cancelled is gone"); + }); + + step("« Copy as is » keeps the braces", || { + app.fields().copy_as_is(); + app.clipboard() + .expect("ssh {{host}} -p {{port=22}}", "the snippet is copied as it is written"); + }); + + step("the note open shows its text filled, and gives the code back", || { + app.notes().open(JUMP); + app.editor().flip_filled(); + app.editor().expect_filled("the text is read with its values"); + app.editor().flip_filled(); + app.editor().expect_code_open("the code is back"); + app.editor().close(); + }); + + step("a note with no field is copied at once, and the copy acknowledged", || { + app.notes().clear_toasts(); + app.notes().copy(Sample::ApiResponse); + app.clipboard().expect_saying("billing", "the response is copied"); + app.notes().expect_acknowledged("a toast says the copy was done"); + }); +} + +fn formatting(app: &mut App) { + step("the sample written on one line is formatted, and « Undo » goes back", || { + app.notes().open(Sample::SnippetToFormat); + app.editor().format(); + app.editor().expect_formatted("the notice says how many lines changed"); + app.editor().expect_several_lines("the code is laid out"); + app.editor().undo_format(); + app.editor().expect_one_line("the code is on one line again"); + }); + + step("a syntax error is said, and nothing changes", || { + app.editor().add_to_code(")"); + app.editor().format(); + app.editor().expect_syntax_error("the notice says where it breaks"); + app.editor().expect_one_line("the code is as typed"); + app.editor().close(); + }); + + step("a snippet keeps its fields when it is formatted", || { + app.press(Shortcut::NewSnippet); + app.editor().type_title("Call"); + app.editor().choose_language("typescript"); + app.editor().type_code(r#"const url="{{base}}/api/{{version=v2}}";fetch(url)"#); + app.editor().format(); + app.editor().expect_formatted("the code is formatted"); + app.editor() + .expect_code_holding("{{base}}/api/{{version=v2}}", "its fields are as written"); + app.editor().close(); + }); + + step("a language Prettier does not read says why it is not formatted", || { + app.notes().open(JUMP); + app.editor().expect_no_format("« Format » is out of reach, with its reason"); + app.editor().close(); + }); +} + +fn exploring(app: &mut App) { + step("a JSON snippet opens as a graph, a node selected with its path", || { + app.notes().open(Sample::ApiResponse); + app.editor().flip_expanded(); + app.json().show_as(JsonView::Graph); + app.json().fit(); + app.json().expect_nodes(6, "every node is drawn"); + app.json().select("$.owner"); + app.json().expect_selected("$.owner", "the node's path is said"); + app.capture("graph"); + }); + + step("everything folds, and opens", || { + app.json().collapse_all(); + app.json().expect_nodes(1, "the root is alone"); + app.json().open_all(); + app.json().expect_nodes(6, "every node is back"); + }); + + step("a search steps to its match, shown in the code", || { + app.json().search("ONCALL"); + app.json().expect_matches(1, "one match is counted"); + app.json().next_match(); + app.json().expect_selected("$.owner.onCall", "the match is selected"); + app.json().show_in_code(); + app.editor().expect_code_open("the code is back"); + app.copy(); + app.clipboard().expect("\"@oncall\"", "the match is selected in it"); + }); + + step("the tree folds a container", || { + app.json().show_as(JsonView::Tree); + app.json().flip_in_the_tree("$.owner"); + app.json().expect_folded_in_the_tree("$.owner", "the owner is folded"); + }); + + step("side by side, the code and the graph select in each other", || { + app.json().show_as(JsonView::Graph); + app.json().flip_side_by_side(); + app.json().expect_side_by_side(true, "the code stands beside the graph"); + app.editor().go_to_start(); + app.editor().go_to_line_end_below(); + app.json() + .expect_selected("$.service", "the caret in a value selects it in the graph"); + app.json().select("$.endpoints"); + app.json().show_in_code(); + app.copy(); + app.clipboard() + .expect_saying("invoices", "the node's lines are selected in the code"); + app.json().show_as(JsonView::Graph); + app.json().flip_side_by_side(); + app.json().expect_side_by_side(false, "one at a time again"); + app.editor().flip_expanded(); + app.editor().close(); + }); +} + +fn keeping_the_draft(app: &mut App) { + step("a word is found and replaced, and Tab stays in the code", || { + app.notes().open(JUMP); + app.editor().replace_everywhere("ssh", "mosh"); + app.editor().close_find(); + app.editor().expect_code("mosh {{host}} -p {{port=22}}", "the word is replaced"); + app.editor().go_to_start(); + app.press(Shortcut::Tab); + app.editor() + .expect_code_holding(" mosh {{host}}", "a level stands before the code"); + }); + + step("a line is gone to by its number", || { + app.editor().add_to_code(" "); + app.editor().go_to_line(1); + app.type_text("#"); + app.editor() + .expect_code_holding("# mosh {{host}}", "what is typed is at the line's start"); + }); + + step("the draft survives the note expanded and its header folded", || { + app.editor().add_to_code(" # mine"); + app.editor().flip_expanded(); + app.editor().expect_expanded("the note takes the whole area"); + app.editor().expect_code_holding("# mine", "the draft is there, expanded"); + app.editor().flip_expanded(); + app.editor().fold_header(); + app.editor() + .expect_code_holding("# mine", "the draft is there, the header folded"); + app.editor().unfold_header(); + app.editor().close(); + app.notes().open(JUMP); + app.editor().expect_code_holding("# mine", "the draft was written"); + }); + + step("a title being typed is kept when another card is clicked", || { + app.editor().retype_title("Jump by mosh"); + app.notes().open(Sample::PsqlConnection); + app.editor().close(); + app.notes().expect_card("Jump by mosh", "the card wears its new title"); + }); + + step("a title being typed is kept when DevNotes quits", || { + app.notes().open("Jump by mosh"); + app.editor().retype_title(JUMP); + app.relaunch_and_unlock(); + app.notes().expect_card(JUMP, "the card wears its new title"); + }); +} + +fn from_the_keyboard(app: &mut App) { + step("the arrows walk the cards, Enter opens one, and J the next one", || { + app.notes().go_to_first_card(); + app.press(Shortcut::Down); + app.notes().expect_keyboard_on(JUMP, "the arrow went down to the snippet"); + app.press(Shortcut::Enter); + app.editor().expect_title(JUMP, "the snippet is open"); + app.press(Shortcut::CardKey(Key::J)); + app.editor().expect_another_note(JUMP, "the next note is open"); + app.press(Shortcut::CardKey(Key::K)); + app.editor().expect_title(JUMP, "K goes back to the snippet"); + app.editor().close(); + }); + + step("C on a card copies it, asking for its fields", || { + app.notes().go_to_card(JUMP); + app.press(Shortcut::CardKey(Key::C)); + app.fields().expect_open("the form asks for the fields"); + app.fields().cancel(); + app.notes().clear_search(); + }); + + step("duplicated from its card's menu, the copy is sent to another space", || { + app.rail().new_space("Work"); + app.rail().show_all_spaces(); + app.notes().duplicate(JUMP); + app.editor() + .expect_code_holding("mosh {{host}}", "the copy is open, with the same code"); + app.editor().retype_title("Jump from work"); + app.editor().close(); + app.notes().expect_card(JUMP, "the first one is still there"); + app.notes().move_to_space("Jump from work", "Work"); + app.rail().show_space("Work"); + app.notes().expect_card("Jump from work", "the copy is in the other space"); + app.notes().expect_cards(1, "and it alone"); + }); +} diff --git a/e2e/tests/03_editing_a_note.rs b/e2e/tests/03_editing_a_note.rs deleted file mode 100644 index 1def5f9eb..000000000 --- a/e2e/tests/03_editing_a_note.rs +++ /dev/null @@ -1,375 +0,0 @@ -//! Editing a snippet: title, code and context written on the way out, the footer counting what -//! the code holds, full screen and the folded header keeping the draft, Tab staying in the code -//! and the find bar finding in it. Then a drawing: drawn on its stage, shown on its card from the -//! picture kept beside it, written as a PNG, and Escape stepping back through it. Then Notes: -//! the sample opens formatted and a box ticked there is kept, one typed from the toolbar keeps -//! « 2 * 3 * 4 » as typed, a double click takes a word to type over, and a list copied keeps its -//! markers. The editor sits beside the cards: J steps to the next one, and Escape leaves full -//! screen before it closes. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -const TITLE: &str = "Rollout under edit"; -const SKETCH: &str = "Archi"; - -/// The code as the editor holds it. -fn code(tree: &Tree) -> String { - tree.find("editor-body") - .and_then(|body| body.value()) - .unwrap_or_default() - .to_owned() -} - -fn open(app: &mut App) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(TITLE); - app.eventually("the snippet alone", |tree| { - tree.count("note-card") == 1 && tree.texts("note-card").contains(&TITLE.to_owned()) - }); - app.click("note-card-open"); - app.wait_for("editor-body"); -} - -fn close(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); -} - -fn shapes(tree: &Tree) -> String { - tree.find("drawing-stage") - .and_then(|stage| stage.value()) - .unwrap_or_default() - .to_owned() -} - -fn pressed(tree: &Tree, tool: &str) -> bool { - tree.find(tool) - .is_some_and(|button| button.toggled() == Some(egui::accesskit::Toggled::True)) -} - -fn open_sketch(app: &mut App) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(SKETCH); - app.eventually("the drawing alone", |tree| { - tree.count("note-card") == 1 && tree.texts("note-card").contains(&SKETCH.to_owned()) - }); - app.click("note-card-open"); - app.wait_for("drawing-stage"); -} - -fn drawings(app: &mut App, exported: &std::path::Path) { - step("a drawing is drawn, and its card shows its picture", || { - app.click("new-note-kind"); - app.click("new-note-drawing"); - app.fill("editor-title", SKETCH); - app.click("drawing-tool-rectangle"); - app.drag_in("drawing-stage", (40.0, 40.0), (160.0, 110.0)); - app.eventually("a rectangle drawn", |tree| shapes(tree) == "1"); - app.capture("drawing-editor"); - close(app); - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(SKETCH); - app.wait_for("note-card-drawing"); - }); - - step("a drawing is written as a PNG where the dialog says", || { - open_sketch(app); - app.eventually("the scene read back", |tree| shapes(tree) == "1"); - app.click("drawing-export-png"); - app.eventually("the file written", |_| { - std::fs::read(exported).is_ok_and(|bytes| bytes.starts_with(b"\x89PNG")) - }); - }); - - step("the eraser takes shape after shape and stays in hand", || { - app.click("drawing-tool-ellipse"); - app.drag_in("drawing-stage", (200.0, 40.0), (280.0, 110.0)); - app.eventually("two shapes", |tree| shapes(tree) == "2"); - app.click("drawing-tool-eraser"); - app.drag_in("drawing-stage", (20.0, 75.0), (300.0, 75.0)); - app.eventually("both gone in one drag", |tree| shapes(tree) == "0"); - assert!(pressed(&app.tree(), "drawing-tool-eraser")); - app.click("drawing-undo"); - app.eventually("one step back", |tree| shapes(tree) == "2"); - app.drag_in("drawing-stage", (240.0, 75.0), (240.0, 75.0)); - app.eventually("one by a click", |tree| shapes(tree) == "1"); - }); - - arrow_and_look(app); - - step("Escape drops the tool, the selection, then the editor", || { - app.drag_in("drawing-stage", (100.0, 75.0), (100.0, 75.0)); - app.eventually("the stage has the keys", |tree| tree.focused().starts_with("drawing-stage")); - app.press(Key::O, Modifiers::NONE); - app.eventually("the ellipse taken", |tree| pressed(tree, "drawing-tool-ellipse")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("back to the selection", |tree| pressed(tree, "drawing-tool-select")); - app.press(Key::Escape, Modifiers::NONE); - assert!(app.has("editor-title"), "the selection went, not the editor"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - }); -} - -/// The sketch open, a rectangle on it: an arrow bound and let go, then the look moved. -fn arrow_and_look(app: &mut App) { - step("an arrow drawn from a shape, its end let go elsewhere", || { - app.click("drawing-tool-arrow"); - app.drag_in("drawing-stage", (100.0, 75.0), (320.0, 75.0)); - app.eventually("the arrow", |tree| shapes(tree) == "2"); - app.drag_in("drawing-stage", (320.0, 75.0), (320.0, 150.0)); - app.capture("drawing-arrow-end"); - assert_eq!(shapes(&app.tree()), "2", "moved, not drawn"); - app.click("drawing-undo"); - app.click("drawing-undo"); - app.eventually("the rectangle alone", |tree| shapes(tree) == "1"); - }); - - step("the drawing is zoomed, moved and shown whole again", || { - let shown = |tree: &Tree| tree.text("drawing-zoom").unwrap_or_default(); - app.eventually("as drawn", |tree| shown(tree).starts_with("100")); - app.click("drawing-zoom-in"); - app.click("drawing-zoom-in"); - app.eventually("closer", |tree| shown(tree).starts_with("156")); - app.drag(egui::pos2(700.0, 400.0), egui::pos2(640.0, 380.0), egui::PointerButton::Middle); - app.capture("drawing-zoomed"); - app.click("drawing-fit"); - app.eventually("whole again", |tree| shown(tree).starts_with("100")); - app.click("drawing-zoom-out"); - app.eventually("further", |tree| shown(tree).starts_with("80")); - app.click("drawing-zoom"); - app.eventually("as drawn again", |tree| shown(tree).starts_with("100")); - assert_eq!(shapes(&app.tree()), "1", "nothing was drawn"); - app.click("editor-close"); - app.eventually("closed", |tree| !tree.has("editor-title")); - open_sketch(app); - }); -} - -/// The title of the note open, as its field holds it. -fn open_title(tree: &Tree) -> String { - tree.find("editor-title") - .and_then(|title| title.value()) - .unwrap_or_default() - .to_owned() -} - -/// Beside the cards, J and K step through them; expanded, the cards go; Escape steps back. -fn beside_the_cards(app: &mut App) { - step("a note opens beside the cards, and J steps to the next one", || { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Delete, Modifiers::NONE); - app.eventually("every card back", |tree| tree.count("note-card") > 2); - app.click_nth("note-card-open", 0); - app.wait_for("editor-title"); - let first = open_title(&app.tree()); - app.press(Key::J, Modifiers::NONE); - app.eventually("the next card open", |tree| tree.has("editor-title") && open_title(tree) != first); - app.press(Key::F2, Modifiers::NONE); - app.eventually("F2 goes to the title", |tree| tree.focused().starts_with("editor-title")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("Escape leaves it, the note still open", |tree| { - tree.has("editor-title") && !tree.focused().starts_with("editor-title") - }); - app.capture("editor-beside-the-cards"); - }); - - step("expanded, the note takes the area; Escape steps back", || { - app.click("editor-fullscreen"); - app.eventually("the cards gone", |tree| !tree.has("note-card") && tree.has("editor-position")); - app.press(Key::Escape, Modifiers::NONE); - // Beside the cards again, or over them in a window too narrow for both. - app.eventually("out of full screen", |tree| !tree.has("editor-position") && tree.has("editor-title")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - }); -} - -/// The rich text a Note's surface holds. -fn rich(tree: &Tree) -> String { - tree.find("editor-rich") - .and_then(|surface| surface.value()) - .unwrap_or_default() - .to_owned() -} - -/// The first task's box: ticked or not. -fn first_box(tree: &Tree) -> Option { - tree.all("rich-task").first().and_then(|task| task.toggled()) -} - -/// The one card `words` finds. ⚠️ The previous search showed one card too: the count is -/// true of it until the debounce ends, so the card itself has to change. -fn search_alone(app: &mut App, words: &str) { - let before = app.tree().texts("note-card"); - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(words); - app.eventually("the note searched, alone", |tree| { - tree.count("note-card") == 1 && tree.texts("note-card") != before - }); -} - -fn notes(app: &mut App) { - step("the sample Note opens formatted, and a box ticked or unticked is kept", || { - search_alone(app, "timeout=120s"); - app.click("note-card-open"); - app.eventually("its tasks drawn", |tree| tree.count("rich-task") == 3); - assert!(!app.tree().has("editor-body"), "no code field for a Note"); - // The sample's first task is done in one language and not in the other. - let before = first_box(&app.tree()); - app.click_nth("rich-task", 0); - app.eventually("the box changed", |tree| first_box(tree) != before); - let after = first_box(&app.tree()); - app.capture("note"); - close(app); - app.click("note-card-open"); - app.eventually("kept once opened again", |tree| first_box(tree) == after); - close(app); - }); - - step("a Note typed with the toolbar keeps its stars as typed", || { - app.click("new-note-kind"); - app.click("new-note-note"); - app.click("editor-rich"); - for glyph in ["2", " ", "*", " ", "3", " ", "*", " ", "4"] { - app.type_text(glyph); - } - app.press(Key::Enter, Modifiers::NONE); - app.click("rich-bold"); - app.type_text("fort"); - app.eventually("both lines typed", |tree| rich(tree) == "2 * 3 * 4\nfort"); - close(app); - search_alone(app, "fort"); - app.click("note-card-open"); - app.eventually("written back as typed", |tree| rich(tree) == "2 * 3 * 4\nfort"); - close(app); - }); - - step("a double click in a Note takes the word under it", || { - // A click less than 0.3 s before a double click makes it a triple, for egui: the last - // one is the field's, two searches each wait out its pause, the card opens by the keys. - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("nothing matches this"); - app.eventually("nothing found", |tree| tree.has("canvas-no-results")); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("fort"); - app.eventually("the Note alone", |tree| tree.count("note-card") == 1); - app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); - app.press(Key::Enter, Modifiers::NONE); - app.wait_for("editor-rich"); - // The first word: the page's margin is 28 points, 20 above the first line. - app.double_click_in("editor-rich", (31.0, 31.0)); - app.type_text("deux"); - app.eventually("the word typed over", |tree| rich(tree) == "deux * 3 * 4\nfort"); - close(app); - }); - - step("a list copied keeps its markers, a long item whole", || { - let long = "un élément assez long pour passer à la ligne plus d’une fois ".repeat(4); - let long = long.trim_end(); - app.click("new-note-kind"); - app.click("new-note-note"); - app.click("editor-rich"); - for glyph in ["-", " "] { - app.type_text(glyph); - } - app.type_text(long); - app.press(Key::Enter, Modifiers::NONE); - app.type_text("court"); - app.eventually("both items typed", |tree| rich(tree).ends_with("court")); - app.press(Key::A, Modifiers::COMMAND); - app.copy(); - let expected = format!("- {long}\n- court"); - app.clipboard_holds("the list with its markers", |held| held == expected); - close(app); - }); -} - -#[test] -fn editing_a_note() { - let profile = tempfile::tempdir().unwrap(); - let exported = profile.path().join("export.png"); - let mut app = App::launch_answering("03_editing_a_note", profile.path(), &exported); - app.create_library(); - app.wait_for("note-card"); - - step("a snippet written from a new note", || { - app.click("new-note"); - app.fill("editor-title", TITLE); - app.click("editor-body"); - app.type_text("kubectl rollout status"); - close(&mut app); - }); - - step("title, code and context are written on the way out", || { - open(&mut app); - app.click("editor-body"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("kubectl rollout restart deployment/api"); - app.fill("editor-source", "runbooks/api.md"); - close(&mut app); - open(&mut app); - app.eventually("the code as typed", |tree| code(tree) == "kubectl rollout restart deployment/api"); - app.eventually("the context as typed", |tree| { - tree.find("editor-source").and_then(|field| field.value()) == Some("runbooks/api.md") - }); - }); - - step("the footer counts one line in the singular", || { - app.eventually("« 1 line »", |tree| { - tree.text("editor-stats") - .is_some_and(|stats| stats.contains("· 1 ligne ·") || stats.contains("· 1 line ·")) - }); - app.capture("snippet-editor"); - }); - - step("Tab stays in the code, and the find bar finds in it", || { - app.click("editor-body"); - app.press(Key::Home, Modifiers::COMMAND); - app.press(Key::Tab, Modifiers::NONE); - app.eventually("a level before the code", |tree| code(tree).starts_with(" kubectl")); - app.press(Key::F, Modifiers::COMMAND); - app.wait_for("search-field"); - app.type_text("rollout"); - app.eventually("one match, selected", |tree| tree.text("search-count").as_deref() == Some("1 / 1")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the bar is closed", |tree| !tree.has("search-field")); - }); - - step("full screen and back keep the draft", || { - app.click("editor-body"); - app.press(Key::End, Modifiers::COMMAND); - app.type_text(" --watch"); - app.click("editor-fullscreen"); - app.click("editor-fullscreen"); - close(&mut app); - open(&mut app); - app.eventually("the draft written", |tree| code(tree).ends_with("--watch")); - }); - - step("the header folds, and stays folded from note to note", || { - app.click("editor-fold-header"); - app.wait_for("editor-header-summary"); - close(&mut app); - open(&mut app); - app.wait_for("editor-header-summary"); - assert!(!app.has("editor-source")); - app.click("editor-header-summary"); - app.wait_for("editor-source"); - close(&mut app); - }); - - beside_the_cards(&mut app); - drawings(&mut app, &exported); - notes(&mut app); - - app.quit(); -} diff --git a/e2e/tests/03_keeping_a_note.rs b/e2e/tests/03_keeping_a_note.rs new file mode 100644 index 000000000..3fdc72782 --- /dev/null +++ b/e2e/tests/03_keeping_a_note.rs @@ -0,0 +1,195 @@ +//! Journey 3, « Keeping, correcting and losing a note »: pinned and dated, its files, its versions, +//! deleted and taken back. + +use e2e::{App, Key, QuickFilter, Sample, Shortcut, step}; + +const NOTE: &str = "Nightly dump"; +const SAMPLES: usize = 6; +const DIAGRAM: &[u8] = br##""##; +/// One byte past the 10 MB a file may weigh. +const TOO_HEAVY: usize = 10 * 1024 * 1024 + 1; + +#[test] +fn keeping_a_note() { + let mut app = App::open("03_keeping_a_note"); + app.window().widen(); + app.notes().write_snippet(NOTE, "pg_dump one"); + + on_top(&mut app); + with_its_files(&mut app); + and_its_versions(&mut app); + deleted_and_taken_back(&mut app); + in_the_trash(&mut app); + + app.quit(); +} + +fn on_top(app: &mut App) { + step("pinned, given a priority from its digit and a due date, it sorts on top", || { + app.notes().go_to_card(NOTE); + app.press(Shortcut::CardKey(Key::P)); + app.press(Shortcut::CardKey(Key::Num4)); + app.notes().clear_search(); + app.notes() + .expect_first_pinned_with_priority(NOTE, "it is the first card, pinned, with its priority"); + app.notes().open(NOTE); + app.editor().choose_due_tomorrow(); + app.editor().close(); + }); + + step("« Untriaged » finds it, and « Pinned » too", || { + app.notes().filter(QuickFilter::Untriaged); + app.notes().expect_cards(2, "the two notes with a due date are listed"); + app.notes().expect_card(NOTE, "this one is among them"); + app.notes().filter(QuickFilter::Pinned); + app.notes().expect_card(NOTE, "it is among the pinned ones"); + app.notes().filter(QuickFilter::All); + app.notes().expect_cards(SAMPLES + 1, "every note is back"); + }); +} + +fn with_its_files(app: &mut App) { + step("a file and a pasted picture are attached, and the card counts them", || { + app.files().put("diagram.svg", DIAGRAM); + app.notes().open(NOTE); + app.attachments().add("diagram.svg"); + app.attachments().expect(1, "the file is attached"); + app.attachments().paste_picture(); + app.attachments().expect(2, "the picture is attached"); + app.capture("attachments"); + app.editor().close(); + app.notes().expect_files_counted(NOTE, "2", "the card counts two files"); + }); + + step("the picture grows in the lightbox, and Esc takes it away", || { + app.notes().open(NOTE); + app.attachments().grow(); + app.attachments().shrink(); + }); + + step("two files of one name stay apart", || { + app.attachments().add("diagram.svg"); + app.attachments() + .expect_named("diagram.svg", 2, "both are listed under the name"); + }); + + step("a file over 10 MB is refused, and nothing is attached", || { + app.files().put("dump.sql", &vec![b' '; TOO_HEAVY]); + app.attachments().add("dump.sql"); + app.attachments().expect_refused("a banner says it is too heavy"); + app.attachments().expect(3, "the files are as they were"); + }); + + step("an attachment is saved elsewhere", || { + app.attachments().save(0, "elsewhere.svg"); + app.files() + .expect("elsewhere.svg", "its bytes are the file's", |bytes| bytes == DIAGRAM); + }); + + step("a removal needs a second click", || { + app.attachments().remove(0); + app.attachments().expect(3, "the first click asks"); + app.attachments().remove(0); + app.attachments().expect(2, "the second one removes"); + app.editor().close(); + }); +} + +fn and_its_versions(app: &mut App) { + step("each edit keeps the version before it, the newest first", || { + for code in ["pg_dump two", "pg_dump three"] { + app.notes().open(NOTE); + app.editor().retype_code(code); + app.editor().close(); + } + app.notes().open(NOTE); + app.history().open(); + app.history().expect_versions(2, "two versions are listed"); + app.history().look_at(1); + app.history() + .expect_change("pg_dump one", "pg_dump three", "going back shows what it would change"); + app.capture("history"); + }); + + step("going back drops the later ones", || { + app.history().go_back(); + app.editor().expect_code("pg_dump one", "the first version is back"); + app.history().expect_none("no version is left"); + app.editor().close(); + }); + + step("a Note keeps its versions too", || { + app.notes().write_note("Runbook", "call the team"); + app.notes().open("Runbook"); + app.editor().type_note(" first"); + app.editor().close(); + app.notes().open("Runbook"); + app.history().open(); + app.history().expect_versions(1, "one version is listed"); + app.editor().close(); + }); + + step("a todo list has none", || { + app.notes().write_todo_list("Before the dump", "stop the writes"); + app.notes().open("Before the dump"); + app.todo().add("tell the team"); + app.editor().close(); + app.notes().open("Before the dump"); + app.history().expect_none("no version is offered"); + app.editor().close(); + }); +} + +fn deleted_and_taken_back(app: &mut App) { + step("deleted from the keyboard in two presses, the undo bar takes it back", || { + app.notes().delete_from_the_keyboard(NOTE); + app.capture("undo"); + app.notes().undo(); + app.notes().clear_search(); + app.notes().expect_card(NOTE, "the note is back"); + }); + + step("once the bar has gone, Ctrl+Z still does", || { + app.notes().delete_from_the_keyboard(NOTE); + app.notes().expect_undo_gone("the bar had its time"); + app.press(Shortcut::Undo); + app.notes().clear_search(); + app.notes().expect_card(NOTE, "the note is back"); + }); +} + +fn in_the_trash(app: &mut App) { + step("the trash restores one note", || { + for title in [NOTE, "Runbook", "Before the dump"] { + app.notes().delete_from_the_keyboard(title); + app.notes().dismiss_undo(); + } + app.notes().clear_search(); + app.trash().open(); + app.trash() + .expect(&[NOTE, "Runbook", "Before the dump"], "the three notes wait there"); + app.trash().restore(NOTE); + app.trash().expect(&["Runbook", "Before the dump"], "two are left"); + app.trash().close(); + app.notes().expect_card(NOTE, "the note restored has its card"); + }); + + step("it deletes one for good, and empties the rest", || { + app.trash().open(); + app.trash().purge("Runbook"); + app.trash().expect(&["Before the dump"], "one is left"); + app.trash().empty(); + app.trash().expect(&[], "the trash says it is empty"); + app.trash().close(); + }); + + step("a relaunch finds it as left", || { + app.relaunch_and_unlock(); + app.notes().expect_card(NOTE, "the note restored is there"); + app.notes().expect_no_card("Runbook", "the one deleted for good is not"); + app.notes().expect_card(Sample::Welcome, "the others were not touched"); + app.trash().open(); + app.trash().expect(&[], "the trash is still empty"); + app.trash().close(); + }); +} diff --git a/e2e/tests/04_other_kinds.rs b/e2e/tests/04_other_kinds.rs new file mode 100644 index 000000000..4996bb627 --- /dev/null +++ b/e2e/tests/04_other_kinds.rs @@ -0,0 +1,312 @@ +//! Journey 4, « The other kinds of note »: a Note written formatted and presented, a todo list, a +//! calculation, a drawing inserted into the Note, and the kinds changed into one another. + +use e2e::{App, DrawingSize, Kind, RichTool, Sample, Shortcut, Spot, Tool, step}; + +const NOTE: &str = "Release plan"; +const LIST: &str = "Release checklist"; +const SHEET: &str = "Hosting budget"; +const SKETCH: &str = "Architecture"; + +#[test] +fn other_kinds() { + let mut app = App::open("04_other_kinds"); + app.window().widen(); + + a_note(&mut app); + a_presentation(&mut app); + a_todo_list(&mut app); + a_calculation(&mut app); + a_drawing(&mut app); + one_kind_into_another(&mut app); + + app.quit(); +} + +fn a_note(app: &mut App) { + step("a Note is written formatted, from each button of its toolbar", || { + app.press(Shortcut::NewNote); + app.editor().type_title(NOTE); + app.editor().expect_note_open("a Note is open"); + app.rich().go_to_end(); + for (tool, text) in [ + (RichTool::Heading1, "Plan"), + (RichTool::Heading2, "Before"), + (RichTool::Heading3, "Details"), + (RichTool::Bold, "fat"), + (RichTool::Italic, "slanted"), + (RichTool::Strikethrough, "gone"), + (RichTool::InlineCode, "kubectl"), + (RichTool::Quote, "said once"), + (RichTool::BulletList, "first point"), + (RichTool::NumberedList, "first step"), + (RichTool::TaskList, "first task"), + ] { + app.rich().write_line(tool, text); + } + app.rich().write_link("the site", "https://devnotes.fr"); + app.capture("note"); + }); + + step("it is kept as Markdown", || { + app.rich().copy_as_markdown(); + for markdown in [ + "# Plan", + "## Before", + "### Details", + "**fat**", + "*slanted*", + "~~gone~~", + "`kubectl`", + "> said once", + "- first point", + "1. first step", + "- [ ] first task", + "[the site](https://devnotes.fr)", + ] { + app.clipboard().expect_saying(markdown, "the Markdown holds what was written"); + } + app.editor().close(); + }); + + step("its shortcuts format too, and what looks like Markdown stays as typed", || { + app.press(Shortcut::NewNote); + app.editor().type_title("Product"); + app.editor().type_note(""); + app.rich().type_keys("2 * 3 * 4"); + app.press(Shortcut::Enter); + app.press(Shortcut::Bold); + app.type_text("strong"); + app.press(Shortcut::Bold); + app.press(Shortcut::Italic); + app.type_text(" light"); + app.rich().expect_text("2 * 3 * 4\nstrong light", "the text is as typed"); + app.editor().close(); + app.notes().open("Product"); + app.rich().expect_text("2 * 3 * 4\nstrong light", "it is read back as typed"); + app.rich().copy_as_markdown(); + app.clipboard().expect_saying("**strong**", "the word is bold"); + app.editor().close(); + }); + + step("a code block keeps its language, and the down arrow leaves it", || { + app.notes().open("Product"); + app.editor().flip_expanded(); + app.rich().go_to_end(); + app.rich().write_code("rust", "let x = 1;"); + app.press(Shortcut::Down); + app.type_text("After the code"); + app.rich().copy_as_markdown(); + app.clipboard() + .expect_saying("```rs\nlet x = 1;\n```\n\nAfter the code", "the block is Rust's"); + app.editor().flip_expanded(); + app.editor().close(); + }); + + step("a table grows by a row and a column", || { + app.notes().open(NOTE); + app.editor().flip_expanded(); + app.rich().go_to_end(); + app.rich().click(RichTool::Table); + app.type_text("Environment"); + app.rich().click(RichTool::RowBelow); + app.rich().click(RichTool::ColumnAfter); + app.rich() + .copy_table_and_expect(4, 4, "three rows of three became four of four"); + app.editor().flip_expanded(); + app.editor().close(); + }); + + step("a box ticked is kept", || { + app.notes().open(Sample::ReleaseDay); + app.rich().tick(1); + app.rich().expect_ticked(1, true, "the second task is ticked"); + app.editor().close(); + app.notes().open(Sample::ReleaseDay); + app.rich().expect_ticked(1, true, "it is still ticked"); + app.editor().close(); + }); +} + +fn a_presentation(app: &mut App) { + step("« Present » steps through the sections, opens the map, and leaves on Esc", || { + app.notes().open(Sample::ReleaseDay); + app.presentation().open(); + app.presentation() + .expect_count(1, 5, "the cover comes before the text and its sections"); + app.capture("presentation"); + app.presentation().next(); + app.presentation().expect_count(2, 5, "the text is shown"); + app.presentation().open_map(); + app.presentation() + .expect_map(4, "the map draws the Note and its three headings"); + app.presentation().leave(); + app.editor().close(); + // The window the system gives back is no larger than the screen. + app.window().widen(); + }); +} + +fn a_todo_list(app: &mut App) { + step("a list is typed a task at a time, split by Enter and pasted line by line", || { + app.press(Shortcut::NewTodoList); + app.editor().type_title(LIST); + app.todo().add("Tag the release"); + app.todo().add("Write the notes publish"); + app.todo().split_before(1, "publish"); + app.todo() + .expect(&["Tag the release", "Write the notes ", "publish"], "Enter cut the task in two"); + app.todo().add_empty(); + app.paste("- Freeze the merges\n- [x] Back the database up"); + app.todo() + .expect_ticked(&[false, false, false, false, true], "each line pasted is a task, its box read"); + }); + + step("a task moves up, and one is removed", || { + app.todo().move_up(1); + app.todo().expect( + &["Write the notes ", "Tag the release", "publish", "Freeze the merges", "Back the database up"], + "the second task is the first", + ); + app.todo().remove(2); + app.capture("list"); + app.editor().close(); + app.notes().expect_progress(LIST, "1/4", "the card counts one task done"); + }); + + step("it is ticked from its card without opening it", || { + app.notes().tick_on_card(LIST, 0); + app.notes().expect_progress(LIST, "2/4", "the card counts two"); + app.editor().expect_closed("no note is open"); + app.notes().open(LIST); + app.todo() + .expect_ticked(&[true, false, false, true], "the first task is ticked"); + app.editor().close(); + }); +} + +fn a_calculation(app: &mut App) { + step("each line is computed as it is typed, a name usable below it", || { + app.press(Shortcut::NewCalculation); + app.editor().type_title(SHEET); + app.editor() + .type_code("server = 100\ndomain = 20\nserver + domain\n20 % of 340"); + app.calc() + .expect_results(&["100", "20", "120", "68"], "each line has its result"); + }); + + step("an error is said beside its line", || { + app.editor().add_to_code("\n100 + "); + app.calc().expect_errors(1, "the line says why it has no result"); + app.capture("calculation"); + }); + + step("results picked are summed in the footer", || { + app.calc().pick(0); + app.calc().expect_sum("100", "the footer says what is picked"); + app.calc().pick_also(2); + app.calc().expect_sum("220", "the two are summed"); + app.editor().close(); + }); + + step("the card shows the last lines, and a relaunch what was written alone", || { + app.notes().expect_calculation(SHEET, "the calculation's lines are on its card"); + app.relaunch_and_unlock(); + app.notes().open(SHEET); + app.editor().expect_code( + "server = 100\ndomain = 20\nserver + domain\n20 % of 340\n100 + ", + "the text is as it was typed", + ); + app.calc() + .expect_results(&["100", "20", "120", "68"], "the results are computed again"); + app.editor().close(); + }); +} + +fn a_drawing(app: &mut App) { + step("shapes, a text and an arrow are drawn", || { + app.press(Shortcut::NewDrawing); + app.editor().type_title(SKETCH); + app.drawing().draw(Tool::Rectangle, Spot::Left); + app.drawing().draw(Tool::Ellipse, Spot::Right); + app.drawing().draw(Tool::Diamond, Spot::Middle); + app.drawing().write("queue", Spot::Below); + app.drawing().draw_arrow(Spot::Left, Spot::Right); + app.drawing().expect_shapes(5, "the five are on the drawing"); + app.capture("drawing"); + }); + + step("the arrow follows the shape it starts from", || { + app.drawing().export_svg("before.svg"); + app.drawing().move_shape(Spot::Right, Spot::Below); + app.drawing().export_svg("after.svg"); + app.drawing() + .expect_arrow_moved("before.svg", "after.svg", "its arrow is elsewhere"); + }); + + step("a shape is removed with Delete", || { + app.drawing().delete(Spot::Middle); + app.drawing().expect_shapes(4, "four are left"); + }); + + step("it is zoomed, and shown whole by F", || { + app.drawing().zoom_in(); + app.drawing().expect_zoom("125", "it is closer"); + app.drawing().show_whole(); + app.drawing().expect_zoom("100", "it is whole again"); + app.drawing().export_png("sketch.png"); + app.files() + .expect("sketch.png", "the picture is written", |bytes| bytes.starts_with(b"\x89PNG")); + app.editor().close(); + app.notes().expect_picture(SKETCH, "its card shows its picture"); + }); + + step("inserted into the Note, it is shown there and resized by its corner", || { + app.notes().open(NOTE); + app.editor().flip_expanded(); + app.rich().go_to_start(); + app.rich().insert_drawing(); + app.rich().size_drawing(DrawingSize::Whole); + let whole = app.rich().drawing_width(); + app.rich().size_drawing(DrawingSize::Quarter); + app.rich().expect_drawing_width(whole, 0.25, "it takes a quarter of the width"); + app.rich().drag_drawing_corner_out(); + app.rich().expect_drawing_width(whole, 1.0, "dragged, it takes the whole width"); + app.capture("drawing-in-a-note"); + app.editor().close(); + app.notes().open(NOTE); + app.rich().expect_drawing_width(whole, 1.0, "it was kept so"); + app.editor().flip_expanded(); + app.editor().close(); + }); +} + +fn one_kind_into_another(app: &mut App) { + step("the list becomes a Note, and so does a snippet", || { + app.notes().open(LIST); + app.editor().convert_to_note(); + app.editor().expect_note_open("the list is a Note"); + app.editor().close(); + app.press(Shortcut::NewSnippet); + app.editor().type_title("Restart"); + app.editor().type_code("systemctl restart api"); + app.editor().convert_to_note(); + app.editor().expect_note_open("the snippet is a Note"); + app.editor().close(); + }); + + step("the conversion is taken back by the undo bar", || { + app.notes().open(Sample::PsqlConnection); + app.editor().convert_to_note(); + app.editor().expect_note_open("the snippet is a Note"); + app.notes().undo(); + app.editor().expect_code_open("it is a snippet again"); + app.editor().close(); + }); + + step("a drawing offers no change", || { + app.notes().new_of_kind(Kind::Drawing); + app.editor().expect_no_kind_to_choose("its kind is said, and is no menu"); + app.editor().close(); + }); +} diff --git a/e2e/tests/04_trash_and_undo.rs b/e2e/tests/04_trash_and_undo.rs deleted file mode 100644 index bd0782f6c..000000000 --- a/e2e/tests/04_trash_and_undo.rs +++ /dev/null @@ -1,173 +0,0 @@ -//! Deleting a note does not delete it: it goes to the trash, and the undo bar, `Escape` while it -//! offers, and `Ctrl+Z` after it has gone take it back; the trash panel restores, purges and -//! empties. The samples' titles are translated: rows are counted, never read. - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; - -fn cards(app: &mut App, count: usize, what: &str) { - app.eventually(what, |tree| tree.count("note-card") == count); -} - -/// The first card, sent to the trash from the keyboard: the second press is the one that writes. -fn delete_first(app: &mut App) { - let before = app.tree().count("note-card"); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::Delete, Modifiers::NONE); - app.wait_for("note-card-arming"); - app.press(Key::Delete, Modifiers::NONE); - cards(app, before - 1, "the note is in the trash"); -} - -/// Deleted, and the offer to take it back turned down. -fn trash_first(app: &mut App) { - delete_first(app); - app.click("undo-dismiss"); -} - -fn rows(app: &mut App, count: usize, what: &str) { - app.eventually(what, |tree| tree.count("trash-row") == count); -} - -fn emptied(app: &mut App) { - app.eventually("the trash says it is empty", |tree| { - tree.has("trash-empty-state") && tree.count("trash-row") == 0 - }); -} - -#[test] -fn trash_and_undo() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("04_trash_and_undo", profile.path()); - app.create_library(); - cards(&mut app, CARDS, "the samples are drawn"); - - step("the card's menu needs the second click to delete anything", || { - app.hover("note-card-open"); - app.click("note-card-menu"); - app.click("note-card-delete"); - assert_eq!(app.tree().count("note-card"), CARDS); - app.press(Key::Escape, Modifiers::NONE); - }); - - step("the priorities of the menu come and go with the pointer, and one is picked", || { - let levels = "note-card-priority-level"; - app.hover("note-card-open"); - app.click("note-card-menu"); - app.hover("note-card-priority"); - app.eventually("the five levels", |tree| tree.count(levels) == 5); - app.hover("note-card-duplicate"); - app.eventually("closed with the pointer gone", |tree| !tree.has(levels)); - app.hover("note-card-priority"); - app.hover_nth(levels, 3); - app.eventually("open under the pointer", |tree| tree.count(levels) == 5); - app.click_nth(levels, 0); - app.eventually("a pick closes the menu", |tree| !tree.has("note-card-priority")); - }); - - step("Delete arms the card, and Escape calls it off", || { - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::Delete, Modifiers::NONE); - app.wait_for("note-card-arming"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the card is disarmed", |tree| !tree.has("note-card-arming")); - // Back to zero, not to one: the next Delete arms again rather than trashing. - app.press(Key::Delete, Modifiers::NONE); - app.wait_for("note-card-arming"); - assert_eq!(app.tree().count("note-card"), CARDS); - app.press(Key::Escape, Modifiers::NONE); - }); - - step("Escape takes the note back while the bar offers", || { - delete_first(&mut app); - app.wait_for("undo-bar"); - app.capture("undo-bar"); - app.press(Key::Escape, Modifiers::NONE); - cards(&mut app, CARDS, "the note is back"); - }); - - step("the bar's Undo takes it back", || { - delete_first(&mut app); - app.click("undo-restore"); - cards(&mut app, CARDS, "the note is back"); - assert!(!app.has("undo-bar")); - }); - - step("Ctrl+Z still takes it back once the banner has gone", || { - delete_first(&mut app); - app.wait_for("undo-bar"); - app.eventually("the banner's timer runs out", |tree| !tree.has("undo-bar")); - app.press(Key::Z, Modifiers::COMMAND); - cards(&mut app, CARDS, "the note is back"); - }); - - step("a dismissed offer is given up for good", || { - trash_first(&mut app); - app.press(Key::Z, Modifiers::COMMAND); - assert!(!app.has("undo-bar")); - assert_eq!(app.tree().count("note-card"), CARDS - 1); - }); - - trash_panel(&mut app); - app.quit(); -} - -/// Starts with one note in the trash and the others on the canvas. -fn trash_panel(app: &mut App) { - step("the trash panel restores what was deleted", || { - app.click("trash-open"); - rows(app, 1, "the deleted note is listed"); - app.capture("trash-panel"); - app.click("trash-restore"); - emptied(app); - app.click("trash-close"); - cards(app, CARDS, "the note is back"); - }); - - step("a row is purged for good on the second click", || { - trash_first(app); - app.click("trash-open"); - rows(app, 1, "the deleted note is listed"); - app.click("trash-purge"); - assert_eq!(app.tree().count("trash-row"), 1); - app.click("trash-purge"); - emptied(app); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("Escape closes the panel", |tree| !tree.has("trash-close")); - assert_eq!(app.tree().count("note-card"), CARDS - 1); - }); - - step("a search narrows the trash, and restoring reaches what it found", || { - for _ in 0..3 { - trash_first(app); - } - app.click("trash-open"); - rows(app, 3, "the three deleted notes are listed"); - app.fill("trash-search", "zz-nothing-zz"); - app.eventually("the search finds nothing", |tree| { - tree.has("trash-empty-state") && !tree.has("trash-empty") - }); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Backspace, Modifiers::NONE); - rows(app, 3, "the whole trash is back"); - app.click("trash-restore-all"); - emptied(app); - app.click("trash-close"); - cards(app, CARDS - 1, "the three notes are back"); - }); - - step("emptying says what it erases, then erases it", || { - trash_first(app); - trash_first(app); - app.click("trash-open"); - rows(app, 2, "the two deleted notes are listed"); - app.click("trash-empty"); - app.wait_for("trash-empty-warning"); - app.click("trash-empty-confirm"); - emptied(app); - app.click("trash-close"); - cards(app, CARDS - 3, "the erased notes stay gone"); - }); -} diff --git a/e2e/tests/05_finding.rs b/e2e/tests/05_finding.rs new file mode 100644 index 000000000..4c15c94b6 --- /dev/null +++ b/e2e/tests/05_finding.rs @@ -0,0 +1,289 @@ +//! Journey 5, « Finding things »: searched, filtered, sorted and grouped, by its tags, and several +//! notes at once. In a space of its own: the samples are in the machine's language. + +use e2e::{App, FilterMenu, GroupBy, Key, Kind, QuickFilter, Shortcut, SortBy, step}; + +const DEPLOY: &str = "Déploiement"; +const LIST: &str = "Before release"; +const QUERY: &str = "Alpha query"; +const PLAN: &str = "Zulu plan"; + +#[test] +fn finding() { + let mut app = App::open("05_finding"); + app.window().widen(); + four_notes(&mut app); + + searching(&mut app); + filtering(&mut app); + sorting(&mut app); + by_its_tags(&mut app); + several_at_once(&mut app); + + app.quit(); +} + +fn four_notes(app: &mut App) { + app.rail().new_space("Work"); + app.press(Shortcut::NewSnippet); + app.editor().type_title(DEPLOY); + app.editor().type_code("kubectl apply -f api.yaml"); + app.editor().type_context("runbooks/zanzibar.md"); + app.editor().add_tag("quokka"); + app.editor().close(); + app.press(Shortcut::NewTodoList); + app.editor().type_title(LIST); + app.todo().add("warn the walrus"); + app.editor().add_tag("quokka"); + app.editor().choose_due_tomorrow(); + app.editor().close(); + app.press(Shortcut::NewSnippet); + app.editor().type_title(QUERY); + app.editor().choose_language("sql"); + app.editor().type_code("select 1"); + app.editor().add_tag("narwhal"); + app.editor().close(); + app.notes().write_note(PLAN, "one thing after another"); + app.notes().go_to_card(PLAN); + app.press(Shortcut::CardKey(Key::P)); + app.notes().go_to_card(QUERY); + app.press(Shortcut::CardKey(Key::Num4)); + // Esc would take it back while the bar offers to. + app.notes().dismiss_undo(); + app.notes().clear_search(); + app.notes().expect_cards(4, "the four notes are cards"); +} + +fn searching(app: &mut App) { + step("Ctrl+K goes to the search, which reads words without their accents", || { + app.press(Shortcut::Search); + app.notes().expect_keyboard_in_search("the search has the keyboard"); + app.type_text("deploiement"); + app.notes().expect_cards(1, "one note answers"); + app.notes().expect_card(DEPLOY, "it is the one with the accents"); + }); + + step("a word of a list, of a context and of a tag is found, and quoted on the card", || { + for (word, note, quoted) in [ + ("walrus", LIST, "warn the walrus"), + ("zanzibar", DEPLOY, "zanzibar"), + ("quokk", DEPLOY, "quokka"), + ] { + app.notes().search(word); + app.notes().expect_quoting(note, quoted, "the card quotes the words found"); + } + }); + + step("nothing found says so", || { + app.notes().search("zz nothing is called this"); + app.notes().expect_nothing_found("the cards give way to a sentence"); + app.notes().clear_search(); + app.notes().expect_cards(4, "every note is back"); + }); +} + +fn filtering(app: &mut App) { + step("« All », « Pinned » and « Untriaged » keep what they say", || { + app.notes().filter(QuickFilter::Pinned); + app.notes().expect_order(&[PLAN], "the pinned note is alone"); + app.notes().filter(QuickFilter::Untriaged); + app.notes().expect_order(&[LIST], "the note with a due date is alone"); + app.notes().filter(QuickFilter::All); + app.notes().expect_cards(4, "every note is back"); + }); + + step("several values of one menu add up, and it says how many are ticked", || { + app.filters().flip_band(); + app.filters().open(FilterMenu::Type); + app.filters().tick_kind(Kind::Note); + app.notes().expect_cards(1, "the Note is alone"); + app.filters().tick_kind(Kind::TodoList); + app.notes().expect_cards(2, "the list joins it"); + app.filters().expect_menu_counting(FilterMenu::Type, 2, "the menu says two"); + app.capture("filters"); + app.filters().close_menu(); + app.filters().expect_ticked(2, "the band says two"); + app.filters().clear(); + app.notes().expect_cards(4, "every note is back"); + }); + + step("the other menus narrow too", || { + app.filters().open(FilterMenu::Priority); + app.filters().tick_urgent(); + app.notes().expect_order(&[QUERY], "the urgent note is alone"); + app.filters().close_menu(); + app.filters().clear(); + app.filters().open(FilterMenu::Tags); + app.filters().tick_tag("quokka"); + app.notes().expect_cards(2, "the two notes with the tag are left"); + app.filters().close_menu(); + app.filters().open(FilterMenu::Format); + app.filters().tick_format("SQL"); + app.notes().expect_nothing_found("none of the two is in that format"); + app.filters().close_menu(); + }); + + step("« Clear the filters » removes them with the search", || { + app.notes().search("alpha"); + app.filters().clear(); + app.notes().expect_search_empty("the search is empty"); + app.filters().expect_none("no value is ticked"); + app.notes().expect_cards(4, "every note is back"); + app.filters().flip_band(); + }); +} + +fn sorting(app: &mut App) { + step("sorted by title in one list, the pinned one first, or not", || { + app.filters().group_by(GroupBy::Nothing); + app.filters().sort_by(SortBy::Title); + app.notes() + .expect_order(&[PLAN, QUERY, LIST, DEPLOY], "the pinned one comes first"); + app.filters().expect_one_list("the cards are in one list"); + app.filters().flip_pinned_first(); + app.notes() + .expect_order(&[QUERY, LIST, DEPLOY, PLAN], "the titles alone decide"); + }); + + step("sorted by date, by priority and by format", || { + app.filters().sort_by(SortBy::Priority); + app.notes().expect_first(QUERY, "the urgent one comes first"); + app.filters().sort_by(SortBy::Format); + app.notes().expect_first(QUERY, "the snippets come first"); + app.filters().sort_by(SortBy::Modified); + app.notes().expect_first(PLAN, "the last one written comes first"); + }); + + step("grouped by date, priority and format", || { + for grouping in [GroupBy::Date, GroupBy::Priority, GroupBy::Format] { + app.filters().group_by(grouping); + app.filters().expect_several_groups("the cards are under headings"); + } + }); + + step("the choice comes back after a relaunch", || { + app.filters().group_by(GroupBy::Nothing); + app.filters().sort_by(SortBy::Title); + app.relaunch_and_unlock(); + app.notes() + .expect_order(&[QUERY, LIST, DEPLOY, PLAN], "the order is the one chosen"); + app.filters().expect_one_list("the cards are in one list"); + }); +} + +fn by_its_tags(app: &mut App) { + step("a tag is renamed on all its notes, once it has said which", || { + app.filters().flip_band(); + app.filters().open(FilterMenu::Tags); + app.filters().manage_tags(); + app.tags().tick("quokka"); + app.tags().ask_rename("wombat"); + app.tags().expect_touching(2, "two notes wear it"); + app.capture("tags"); + app.tags().give_up(); + app.tags().expect_listed("quokka", "given up, the tag is as it was"); + app.tags().ask_rename("wombat"); + app.tags().confirm(); + app.tags().expect_listed("wombat", "the tag has its new name"); + app.tags().expect_gone("quokka", "the former one is gone"); + }); + + step("it is corrected in case alone", || { + app.tags().tick("wombat"); + app.tags().ask_rename("Wombat"); + app.tags().confirm(); + app.tags().expect_listed("Wombat", "the tag is spelt as it was typed"); + }); + + step("onto an existing tag, it merges", || { + app.tags().tick("narwhal"); + app.tags().ask_rename("Wombat"); + app.tags().confirm(); + app.tags().expect_gone("narwhal", "one tag is left of the two"); + }); + + step("deleted, it leaves its notes", || { + app.tags().tick("Wombat"); + app.tags().ask_delete(); + app.tags().expect_touching(3, "three notes wear it"); + app.tags().confirm(); + app.tags().expect_gone("Wombat", "the tag is gone"); + app.tags().close(); + app.filters().flip_band(); + app.notes().expect_cards(4, "every note stays"); + }); +} + +fn several_at_once(app: &mut App) { + step("notes are ticked with X, a Ctrl-click and a Shift-click", || { + app.notes().go_to_first_card(); + app.press(Shortcut::CardKey(Key::X)); + app.selection().expect(1, "one note is ticked"); + app.selection().ctrl_click(DEPLOY); + app.selection().expect(2, "two are"); + app.selection().clear(); + app.notes().go_to_first_card(); + app.selection().shift_click(DEPLOY); + app.selection().expect(3, "the three from the one with the keyboard are"); + app.capture("selection"); + app.selection().clear(); + }); + + step("moved to another space, they are taken back", || { + app.rail().new_space("Archive"); + app.rail().show_space("Work"); + app.selection().tick(QUERY); + app.selection().tick(LIST); + app.selection().move_to("Archive"); + app.notes().expect_undo_offered("the bar says what was done"); + app.notes().expect_cards(2, "two are left here"); + app.notes().undo(); + app.notes().expect_cards(4, "both are back"); + app.selection().clear(); + }); + + step("given a priority, then a tag, they are taken back too", || { + tick_two(app); + app.selection().make_urgent(); + app.notes().expect_undo_offered("the bar says what was done"); + app.notes().expect_urgent(3, "two cards more wear the priority"); + app.notes().undo(); + app.notes().expect_urgent(1, "one does, as before"); + app.selection().clear(); + tick_two(app); + app.selection().add_tag("batch"); + app.notes().expect_undo_offered("the bar says what was done"); + app.notes().dismiss_undo(); + app.selection().clear(); + app.notes().search("batch"); + app.notes().expect_cards(2, "the two notes wear the tag, and they alone"); + app.notes().clear_search(); + }); + + step("sent to the trash, they are given back whole", || { + tick_two(app); + app.selection().delete(); + app.notes().expect_cards(2, "two are left"); + app.notes().undo(); + app.notes().expect_cards(4, "both are back"); + }); + + step("Esc steps back from the selection, then the filter", || { + app.filters().flip_band(); + app.filters().open(FilterMenu::Type); + app.filters().tick_kind(Kind::Note); + app.filters().close_menu(); + app.selection().tick(PLAN); + app.press(Shortcut::Escape); + app.selection().expect_none("the selection is let go"); + app.notes().expect_order(&[PLAN], "the filter is still there"); + app.press(Shortcut::Escape); + app.notes().expect_cards(4, "the filter is gone too"); + }); +} + +fn tick_two(app: &mut App) { + app.selection().tick(LIST); + app.selection().tick(DEPLOY); + app.selection().expect(2, "two notes are ticked"); +} diff --git a/e2e/tests/05_spaces.rs b/e2e/tests/05_spaces.rs deleted file mode 100644 index b8d72ce4f..000000000 --- a/e2e/tests/05_spaces.rs +++ /dev/null @@ -1,144 +0,0 @@ -//! Spaces from the library rail: made, renamed, pinned, chosen, remembered, and deleted with -//! their notes moved out first, or put in the trash. Only a real database proves the cascade -//! never fires. -//! -//! Nothing compares a seeded word: the samples are in the system's language. The space made -//! here is named by the scenario, and found by that name. - -use e2e::{App, step}; -use egui::accesskit::{Node, Toggled}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; -const DOOMED: &str = "Brouillon à jeter"; - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -/// A row's ⋯, by the name its label carries in any language. -fn options_of(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label().is_some_and(|label| label.contains(name)) -} - -fn is_shown(tree: &e2e::Tree, name: &str) -> bool { - tree.all("space-option") - .into_iter() - .any(|node| node.label() == Some(name) && node.toggled() == Some(Toggled::True)) -} - -fn deleted_with_its_notes(app: &mut App) { - step("a space deleted with its notes puts them in the trash", || { - app.click("space-create-open"); - app.fill("space-create-input", "Brouillons"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - is_shown(tree, "Brouillons") && tree.count("note-card") == 0 - }); - app.click("new-note"); - app.fill("editor-title", DOOMED); - app.fill("editor-body", "à jeter"); - app.click("editor-close"); - app.eventually("its note is a card", |tree| tree.count("note-card") == 1); - app.click_where("space-edit", options_of("Brouillons")); - app.click("space-delete-held"); - app.click("space-delete-held-1"); - app.click("space-delete"); - app.click("space-delete"); - app.eventually("the space is gone, its note not in the refuge", |tree| { - tree.count("space-option") == 1 && tree.count("note-card") == CARDS - }); - app.click("trash-open"); - app.eventually("the note waits in the trash", |tree| { - tree.texts("trash-row-title").contains(&DOOMED.to_owned()) - }); - app.press(Key::Escape, Modifiers::NONE); - }); -} - -#[test] -fn spaces() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("05_spaces", profile.path()); - app.create_library(); - - step("a new library has one space, and it cannot be deleted", || { - app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); - assert_eq!(app.tree().count("space-option"), 1); - app.click("space-edit"); - app.wait_for("space-delete-blocked"); - assert!(!app.has("space-delete")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the panel is closed", |tree| !tree.has("space-delete-blocked")); - }); - - step("a space made from the rail is the one shown", || { - app.click("space-create-open"); - app.fill("space-create-input", "Veille"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is listed and shown", |tree| { - is_shown(tree, "Veille") && tree.count("note-card") == 0 - }); - app.capture("rail-new-space"); - }); - - step("a space renamed in its panel", || { - app.click_where("space-edit", options_of("Veille")); - app.wait_for("space-rename-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("Lectures"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the space comes back under its new name", |tree| { - let names = tree.texts("space-option"); - names.contains(&"Lectures".to_owned()) && !names.contains(&"Veille".to_owned()) - }); - }); - - step("pinned, it heads the list whatever its name, and falls back", || { - app.click_where("space-edit", options_of("Lectures")); - app.click("space-pin"); - app.eventually("the pinned space is first", |tree| { - tree.texts("space-option").first().map(String::as_str) == Some("Lectures") - }); - app.click("space-pin"); - app.eventually("the unpinned space is back in its name's order", |tree| { - let names = tree.texts("space-option"); - names.len() == 2 && names.contains(&"Lectures".to_owned()) - }); - app.click_where("space-edit", options_of("Lectures")); - app.eventually("the panel is closed", |tree| !tree.has("space-pin")); - }); - - step("« all spaces » shows every note, a space its own", || { - app.click("space-option-all"); - app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); - app.click_where("space-option", named("Lectures")); - app.eventually("the canvas narrowed to the space", |tree| tree.count("note-card") == 0); - }); - - let mut app = app.relaunch(); - - step("a relaunch opens on the space it was left on", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("the space chosen before is shown", |tree| { - is_shown(tree, "Lectures") && tree.count("note-card") == 0 - }); - }); - - step("deleting a space says where its notes go, then moves them", || { - app.click_where("space-edit", options_of("Lectures")); - app.wait_for("space-delete-consequence"); - app.capture("rail-space-panel"); - app.click("space-delete"); - app.click("space-delete"); - app.eventually("the space is gone, its refuge shown", |tree| { - tree.count("space-option") == 1 && tree.count("note-card") == CARDS - }); - }); - - deleted_with_its_notes(&mut app); - - app.quit(); -} diff --git a/e2e/tests/06_search_and_filters.rs b/e2e/tests/06_search_and_filters.rs deleted file mode 100644 index dbc9c5373..000000000 --- a/e2e/tests/06_search_and_filters.rs +++ /dev/null @@ -1,270 +0,0 @@ -//! The search, the quick filter and the order, over the first launch's samples. Filtering, -//! grouping and folding run in Rust; what is proved here is the query the window sends. -//! -//! Nothing compares a seeded word: the samples are in the system's language. What is searched -//! is in their code, which no translation touches. - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; -/// Groupings in the menu's order: date, priority, format, none. -const NO_GROUPING: usize = 3; -/// Quick filters in the switch's order. -const ALL: &str = "quick-filter-0"; -const PINNED: &str = "quick-filter-1"; -const UNTRIAGED: &str = "quick-filter-2"; - -/// The header's controls, left to right as they are drawn. -const HEADER: [&str; 13] = [ - "library-rail-toggle", - "trash-open", - "space-switcher", - "view-list", - "folder-switcher", - "search-input", - "quick-filter-0", - "quick-filter-2", - "sort-trigger", - "facets-toggle", - "new-note", - "new-note-kind", - "area-notes", -]; - -/// How many rows the header's controls sit on, each one's row, and whether any runs past the -/// notes area. Rows are told apart by their middles, as the controls differ in height. -struct Layout { - rows: usize, - row_of: Vec<(&'static str, usize)>, - overflowing: bool, -} - -fn layout(tree: &e2e::Tree) -> Layout { - let area = tree.find("area-notes").and_then(egui::accesskit::Node::bounds); - let boxes: Vec<(&'static str, egui::accesskit::Rect)> = HEADER[..HEADER.len() - 1] - .iter() - .filter_map(|id| Some((*id, tree.find(id)?.bounds()?))) - .collect(); - let mut middles: Vec = boxes.iter().map(|(_, b)| f64::midpoint(b.y0, b.y1)).collect(); - middles.sort_by(f64::total_cmp); - let starts: Vec = middles - .iter() - .enumerate() - .filter(|(at, middle)| *at == 0 || **middle - middles[at - 1] > 12.0) - .map(|(_, middle)| *middle) - .collect(); - let row_of = boxes - .iter() - .map(|(id, b)| { - let middle = f64::midpoint(b.y0, b.y1); - (*id, starts.iter().filter(|start| **start <= middle + 12.0).count()) - }) - .collect(); - let overflowing = - area.is_none_or(|area| boxes.iter().any(|(_, b)| b.x0 < area.x0 - 1.0 || b.x1 > area.x1 + 1.0)); - Layout { rows: starts.len(), row_of, overflowing } -} - -fn row(layout: &Layout, id: &str) -> usize { - layout.row_of.iter().find(|(each, _)| *each == id).map_or(0, |(_, row)| *row) -} - -fn search(app: &mut App, words: &str) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(words); -} - -#[test] -fn search_and_filters() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("06_search_and_filters", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); - - step("a search finds a note by its body, past the debounce", || { - search(&mut app, "withRetry"); - app.eventually("one card, and its count", |tree| { - tree.count("note-card") == 1 && tree.has("search-matched") - }); - }); - - step("down from the field to the card it found", || { - app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); - }); - - step("it folds case the way Rust does", || { - search(&mut app, "WITHRETRY"); - app.eventually("the same card", |tree| tree.count("note-card") == 1); - }); - - step("nothing found says so, and still counts", || { - search(&mut app, "nothing matches this"); - app.eventually("the canvas says nothing matches", |tree| { - tree.has("canvas-no-results") && tree.text("search-matched").is_some_and(|said| !said.is_empty()) - }); - app.capture("search-nothing"); - }); - - step("the cross empties the field, and the count goes", || { - app.click("search-clear"); - app.eventually("every card is back", |tree| { - tree.count("note-card") == CARDS && !tree.has("search-matched") - }); - }); - - step("the quick filter keeps one pinned note, then one with a deadline", || { - app.click(PINNED); - app.eventually("the pinned welcome", |tree| tree.count("note-card") == 1); - app.click(UNTRIAGED); - app.eventually("the list with a deadline", |tree| tree.count("note-card") == 1); - app.click(ALL); - app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); - }); - - step("Ctrl+K puts the caret in the search", || { - app.press(Key::K, Modifiers::COMMAND); - app.eventually("the search has the focus", |tree| tree.focused().starts_with("search-input")); - }); - - step("no grouping lays the cards out as one list", || { - app.click("sort-trigger"); - app.click_nth("sort-grouping", NO_GROUPING); - app.eventually("the date sections are gone", |tree| { - tree.count("note-section") <= 1 && tree.count("note-card") == CARDS - }); - app.capture("sort-no-grouping"); - app.press(Key::Escape, Modifiers::NONE); - }); - - rails_and_header(&mut app); - - let mut app = app.relaunch(); - - step("the arrangement is the library's, found again", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("still one list", |tree| { - tree.count("note-card") == CARDS && tree.count("note-section") <= 1 - }); - }); - - step("the board waits for its own phase", || { - assert!(app.tree().find("view-board").is_some_and(egui::accesskit::Node::is_disabled)); - }); - - read_text(&mut app); - app.quit(); -} - -fn read_text(app: &mut App) { - step("a Note is found by the words it shows, across its bold", || { - app.click("new-note-kind"); - app.click("new-note-note"); - app.click("editor-rich"); - app.type_text("ask about the "); - app.click("rich-bold"); - app.type_text("rollout"); - app.click("rich-bold"); - app.type_text(" window"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - search(app, "rollout window"); - app.eventually("the Note alone", |tree| tree.count("note-card") == 1 && tree.has("search-matched")); - }); -} - -/// The filters' menus and their way out, side by side. -fn band_on_one_line(tree: &e2e::Tree) -> bool { - let middles: Vec = ["facet-menu-kind", "facet-menu-tag", "clear-filters"] - .iter() - .filter_map(|id| tree.find(id)?.bounds()) - .map(|b| f64::midpoint(b.y0, b.y1)) - .collect(); - middles.len() == 3 && middles.windows(2).all(|pair| (pair[0] - pair[1]).abs() < 2.0) -} - -/// The filters' menus over the samples, then the header at three widths. -fn rails_and_header(app: &mut App) { - step("a kind from its menu narrows the cards, and « All » gives them back", || { - app.click("facets-toggle"); - app.click("facet-menu-kind"); - app.click("kind-chip-note"); - app.eventually("the Notes alone, and the toggle counts one value", |tree| { - let cards = tree.count("note-card"); - cards > 0 && cards < CARDS && tree.text("facets-count").as_deref() == Some("1") - }); - assert!( - app.tree().find("facets-toggle").is_some_and(egui::accesskit::Node::is_disabled), - "it refuses to fold while a value is ticked" - ); - assert!(app.tree().has("kind-chip-all"), "the menu stays open"); - app.capture("facets-kind"); - app.click("kind-chip-all"); - app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the menu closed", |tree| !tree.has("kind-chip-all")); - }); - - step("a tag and a format narrow too, and one click clears them", || { - app.click("facet-menu-tag"); - app.click("tag-pill"); - app.eventually("fewer cards", |tree| tree.count("note-card") < CARDS); - app.click("facet-menu-language"); - app.click_nth("language-chip", 0); - app.eventually("two values ticked", |tree| tree.text("facets-count").as_deref() == Some("2")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the band on one line", band_on_one_line); - app.click("clear-filters"); - app.eventually("every card is back, and the way out goes", |tree| { - tree.count("note-card") == CARDS && !tree.has("clear-filters") && !tree.has("facets-count") - }); - }); - - step("Escape closes the menu, then lets the value go", || { - app.click("facet-menu-kind"); - app.click("kind-chip-note"); - app.eventually("fewer cards", |tree| tree.count("note-card") < CARDS); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the menu closed, the value still ticked", |tree| { - !tree.has("kind-chip-all") && tree.count("note-card") < CARDS - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); - app.click("facets-toggle"); - app.eventually("the band folds", |tree| !tree.has("facet-menu-kind")); - }); - - step("the header holds one row at 1,100 with the rail open", || { - app.resize(1_100, 720); - let shown = layout(&app.tree()); - assert!(!shown.overflowing); - assert_eq!(shown.rows, 1); - }); - - step("the rail put away, one row at 1,330, two at 640", || { - app.click("library-rail-toggle"); - app.wait_for("space-switcher"); - app.resize(1_330, 720); - app.eventually("one row, inside the window", |tree| { - let shown = layout(tree); - shown.rows == 1 && !shown.overflowing - }); - app.resize(1_100, 720); - app.eventually("nothing overflows", |tree| !layout(tree).overflowing); - app.resize(640, 720); - app.eventually("two rows, « New note » ending the first", |tree| { - let shown = layout(tree); - shown.rows == 2 - && !shown.overflowing - && row(&shown, "new-note") == row(&shown, "library-rail-toggle") - && row(&shown, "search-input") == 2 - }); - app.capture("header-two-rows"); - app.resize(1_100, 720); - app.click("library-rail-toggle"); - }); -} diff --git a/e2e/tests/06_spaces_and_board.rs b/e2e/tests/06_spaces_and_board.rs new file mode 100644 index 000000000..2c7645cc2 --- /dev/null +++ b/e2e/tests/06_spaces_and_board.rs @@ -0,0 +1,264 @@ +//! Journey 6, « Spaces, folders and the board »: a space made and chosen, its folders filed into, +//! dragged and deleted, its board arranged by hand, a folder opened. + +use e2e::{App, Sample, Shortcut, step}; + +const SPACE: &str = "Workshop"; +const QUERY: &str = "Slow query"; +const DUMP: &str = "Nightly export"; +const INDEX: &str = "Partial index"; +const CACHE: &str = "Cache ratio"; +const SAMPLES: usize = 6; + +#[test] +fn spaces_and_board() { + let mut app = App::open("06_spaces_and_board"); + app.window().widen(); + + spaces(&mut app); + folders(&mut app); + folders_moved(&mut app); + the_board(&mut app); + a_folder_opened(&mut app); + a_space_deleted(&mut app); + + app.quit(); +} + +fn spaces(app: &mut App) { + step("the last space cannot be deleted", || { + let only = app.rail().other_space(""); + app.rail().open_space_panel(&only); + app.rail().expect_no_deletion("the panel says why"); + app.rail().close_space_panel(&only); + }); + + step("a space is made, renamed, and pinned above the others", || { + app.rail().new_space("Zebra"); + app.rail().rename_space("Zebra", SPACE); + app.rail().pin_space(SPACE); + app.rail().expect_first_space(SPACE, "the pinned one heads the list"); + }); + + step("« All spaces » shows every note, a space its own", || { + app.rail().show_all_spaces(); + app.notes().expect_cards(SAMPLES, "every note is listed"); + app.rail().show_space(SPACE); + app.notes().write_snippet(QUERY, "SELECT 1;"); + app.notes().write_snippet(DUMP, "pg_dump prod"); + app.notes().expect_cards(2, "the space has its own two"); + }); + + step("the one chosen is remembered", || { + app.relaunch_and_unlock(); + app.rail().expect_space_shown(SPACE, "the space left is shown"); + app.notes().expect_cards(2, "its two notes are listed"); + }); +} + +fn folders(app: &mut App) { + step("a folder is made, and a second one of the same name refused", || { + app.rail().new_folder("Bases"); + app.rail().ask_folder("Bases"); + app.rail().expect_folder_refused("a banner says it is taken"); + app.rail().expect_folders_named("Bases", 1, "one folder has the name"); + }); + + step("a sub-folder is made, renamed, and given a colour", || { + app.rail().new_sub_folder("Bases", "Indices"); + app.rail().rename_folder("Indices", "Indexes"); + app.rail().recolour_folder("Indexes"); + app.rail().new_folder("Reports"); + }); + + step("a selection is filed into it, and taken back out", || { + app.selection().tick(QUERY); + app.selection().tick(DUMP); + app.selection().move_to("Indexes"); + app.notes().expect_chip(QUERY, "Bases › Indexes", "the card says its folder"); + app.notes().expect_chips(2, "both cards wear the chip"); + app.notes().dismiss_undo(); + app.selection().take_out_of_folders(); + app.notes().expect_chips(0, "no card wears a chip any more"); + app.notes().dismiss_undo(); + app.selection().clear(); + }); + + step("a note filed from its card wears the folder's chip", || { + app.notes().file_into(QUERY, "reports"); + app.notes().expect_chip(QUERY, "Reports", "the card says its folder"); + app.notes().dismiss_undo(); + }); + + step("deleting a folder leaves its notes in its parent", || { + app.notes().file_into(DUMP, "indexes"); + app.notes() + .expect_chip(DUMP, "Bases › Indexes", "the note is in the sub-folder"); + app.notes().dismiss_undo(); + app.rail().delete_folder("Indexes"); + app.notes().expect_chip(DUMP, "Bases", "the note is in the folder that held it"); + app.notes().expect_cards(2, "both notes stay"); + }); +} + +fn folders_moved(app: &mut App) { + step("a folder dragged onto another goes inside it, and Alt+← takes it out", || { + app.rail().drag_folder_onto("Reports", "Bases"); + app.rail().expect_inside("Reports", "Bases", "it is drawn inside"); + app.capture("rail"); + app.notes().dismiss_undo(); + app.rail().move_folder_out("Reports"); + app.rail().expect_beside("Reports", "Bases", "it is beside it again"); + app.rail().show_space(SPACE); + }); + + step("dragged onto another space, it goes there with its notes, and comes back", || { + let samples = app.rail().other_space(SPACE); + app.rail().drag_folder_onto_space("Reports", &samples); + app.notes().expect_undo_offered("the bar says where it went"); + app.rail().show_space(&samples); + app.notes().expect_card(QUERY, "its note came with it"); + app.notes().undo(); + app.rail().show_space(SPACE); + app.notes().expect_card(QUERY, "its note is back"); + }); + + step("deleted with its notes, they wait in the trash", || { + app.rail().new_folder("Drafts"); + app.rail().open_folder("Drafts"); + app.notes().write_snippet("To throw", "echo throw"); + app.rail().delete_folder_with_its_notes("Drafts"); + app.trash().open(); + app.trash().expect(&["To throw"], "the note is in the trash"); + app.trash().empty(); + app.trash().close(); + }); +} + +fn the_board(app: &mut App) { + step("on the board, the folders are zones holding their notes", || { + app.rail().show_space(SPACE); + app.board().show(); + app.board().expect_zones(&["Bases", "Reports"], "each folder is a zone"); + app.board().expect_in_zone("Bases", &[DUMP], "its note is in it"); + app.board().expect_in_zone("Reports", &[QUERY], "its note is in it"); + app.capture("board"); + }); + + step("a card is dragged out of its zone, into another, and onto a folder of the rail", || { + app.board().drag_card_out(DUMP); + app.board().expect_loose(&[DUMP], "it stands loose on the ground"); + app.board().drag_card_into(DUMP, "Reports"); + app.board().expect_in_zone("Bases", &[], "its first zone is empty"); + app.board().expect_holding("Reports", DUMP, "the other one holds it"); + app.board().drag_card_out(DUMP); + app.board().expect_loose(&[DUMP], "it is loose again"); + app.board().drag_card_onto_folder(DUMP, "Bases"); + app.board().expect_in_zone("Bases", &[DUMP], "it is filed again"); + }); + + step("« File into » is the keyboard's twin", || { + app.selection().tick(DUMP); + app.selection().move_to("Reports"); + app.board().expect_holding("Reports", DUMP, "the note is in the other zone"); + app.notes().undo(); + app.board().expect_in_zone("Bases", &[DUMP], "and back"); + app.selection().clear(); + }); + + step("a zone's cards are ticked together", || { + app.board().tick_zone("Bases"); + app.selection().expect(1, "its card is ticked"); + app.selection().clear(); + }); + + step("a zone is moved, then widened, and keeps its notes", || { + let before = app.board().place_of("Bases"); + app.board().move_zone("Bases"); + app.board() + .expect_moved("Bases", before, "the zone is elsewhere, of the same size"); + let moved = app.board().place_of("Bases"); + app.board().widen_zone("Bases"); + app.board().expect_wider("Bases", moved, "the zone is wider, where it was"); + app.board().expect_in_zone("Bases", &[DUMP], "its note is in it"); + }); + + step("a folder is drawn on the ground", || { + app.board().draw_folder("Sketches"); + app.board() + .expect_zones(&["Bases", "Reports", "Sketches"], "it is a zone of the board"); + }); + + step("« Align » and the other arrangements are taken back", || { + app.board().align(); + let aligned = app.board().place_of("Bases"); + app.board().reorganise(); + app.board() + .expect_moved_anywhere("Bases", aligned, "everything is put back in order"); + app.notes().expect_undo_offered("the bar offers it back"); + app.notes().undo(); + app.board().expect_place("Bases", aligned, "the hand's own is back"); + }); + + step("a search dims what it leaves out", || { + app.notes().search("pg_dump"); + app.board().expect_dimmed(QUERY, "the other note is dimmed"); + app.notes().clear_search(); + }); + + step("a relaunch finds the layout, and the view of each space", || { + let left = app.board().place_of("Bases"); + app.relaunch_and_unlock(); + app.board().expect("the board is back"); + app.board().expect_place("Bases", left, "its zones are as they were"); + let samples = app.rail().other_space(SPACE); + app.rail().show_space(&samples); + app.board().expect_list("the other space is a list"); + app.rail().show_space(SPACE); + app.board().expect("this one is a board again"); + }); +} + +fn a_folder_opened(app: &mut App) { + step("empty, a folder offers the card a note is made from", || { + app.board().open_zone("Sketches"); + app.rail().expect_folder_open("Sketches", "the breadcrumb names it"); + app.notes().expect_ghost("the card offers a note"); + app.notes().write_from_the_ghost(INDEX, "CREATE INDEX;"); + app.notes().leave_folder(); + app.board() + .expect_in_zone("Sketches", &[INDEX], "the note made inside is filed there"); + }); + + step("a folder that holds folders is a board one level down", || { + app.rail().new_sub_folder("Bases", "Indexes"); + app.board().open_zone("Bases"); + app.rail().expect_folder_open("Bases", "the breadcrumb names it"); + app.board().expect_zones(&["Indexes"], "its sub-folder is the one zone"); + app.notes().write_snippet(CACHE, "SELECT ratio;"); + app.board().expect_loose(&[CACHE, DUMP], "its notes are beside it"); + }); + + step("Esc gives the search back, then leaves the folder", || { + app.notes().search("ratio"); + app.press(Shortcut::Escape); + app.notes().expect_search_empty("the search is given back"); + app.rail().expect_folder_open("Bases", "the folder is still open"); + app.press(Shortcut::Escape); + app.rail().expect_no_folder_open("the space's board is back"); + app.board().expect_zone("Bases", "its zones are there"); + }); +} + +fn a_space_deleted(app: &mut App) { + step("deleting a space asks where its notes go, and moves them", || { + app.rail().open_space_panel(SPACE); + app.rail().expect_notes_destination("the panel says where they would go"); + app.capture("space-panel"); + app.rail().delete_space(); + app.rail().expect_spaces(1, "one space is left"); + app.rail().show_all_spaces(); + app.notes().expect_card(QUERY, "its notes are in the other one"); + app.notes().expect_card(Sample::Welcome, "with those it already had"); + }); +} diff --git a/e2e/tests/07_checklists.rs b/e2e/tests/07_checklists.rs deleted file mode 100644 index 8bd42d043..000000000 --- a/e2e/tests/07_checklists.rs +++ /dev/null @@ -1,133 +0,0 @@ -//! Todo lists: made from the kind menu, typed a row at a time, split by Enter, pasted line by -//! line, ticked from the editor and from the card, reordered by Alt+arrows — the twin of the -//! grip's drag — and a row removed. A list's position is all the identity an item has. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -const TITLE: &str = "Release checklist"; - -/// The rows' words, top to bottom: a row's value, not its name. -fn rows(tree: &Tree) -> Vec { - tree.all("checklist-text") - .into_iter() - .map(|row| row.value().unwrap_or_default().to_owned()) - .collect() -} - -fn ticks(tree: &Tree) -> Vec { - tree.all("checklist-check") - .into_iter() - .map(|tick| tick.toggled() == Some(egui::accesskit::Toggled::True)) - .collect() -} - -/// The list found by its title and opened from the keyboard: a list's card is mostly its ticks. -fn open(app: &mut App) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(TITLE); - app.eventually("the list alone", |tree| tree.count("note-card") == 1); - app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); - app.press(Key::Enter, Modifiers::NONE); - app.wait_for("checklist-add"); -} - -fn close(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); -} - -/// A new row, typed in. -fn add(app: &mut App, words: &str) { - let before = app.tree().count("checklist-text"); - app.click("checklist-add"); - app.eventually("a new row has the focus", |tree| { - tree.count("checklist-text") == before + 1 && tree.focused().starts_with("checklist-text") - }); - app.type_text(words); -} - -#[test] -fn checklists() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("07_checklists", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - step("a list is made from the kind menu, its rows typed", || { - app.click("new-note-kind"); - app.click("new-note-checklist"); - app.fill("editor-title", TITLE); - add(&mut app, "Tag the release"); - add(&mut app, "Write the changelog"); - add(&mut app, "Publish the binaries"); - close(&mut app); - open(&mut app); - app.eventually("the rows in the order added", |tree| { - rows(tree) == ["Tag the release", "Write the changelog", "Publish the binaries"] - }); - app.capture("checklist-editor"); - }); - - step("Enter cuts a row at the caret, Backspace joins it back", || { - app.click_nth("checklist-text", 2); - app.press(Key::End, Modifiers::NONE); - for _ in 0.."binaries".len() { - app.press(Key::ArrowLeft, Modifiers::NONE); - } - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the row cut in two", |tree| { - rows(tree).get(2..) == Some(&["Publish the ".to_owned(), "binaries".to_owned()][..]) - }); - app.press(Key::Backspace, Modifiers::NONE); - app.eventually("joined back", |tree| rows(tree).len() == 3); - }); - - step("lines pasted into a row are as many items, their boxes read", || { - add(&mut app, ""); - app.paste("- Freeze the merges\n- [x] Back the database up"); - app.eventually("two rows from the paste", |tree| { - rows(tree).get(3..) - == Some(&["Freeze the merges".to_owned(), "Back the database up".to_owned()][..]) - }); - app.eventually("the box pasted ticked", |tree| ticks(tree) == [false, false, false, false, true]); - }); - - step("a row is ticked, moved up by Alt+↑ and removed", || { - app.click_nth("checklist-check", 0); - app.eventually("the first row ticked", |tree| ticks(tree).first() == Some(&true)); - app.click_nth("checklist-text", 1); - app.press(Key::ArrowUp, Modifiers::ALT); - app.eventually("the second row first", |tree| { - rows(tree).first().map(String::as_str) == Some("Write the changelog") - }); - app.click_nth("checklist-remove", 4); - app.eventually("the last row gone", |tree| rows(tree).len() == 4); - close(&mut app); - }); - - step("the order and the ticks are written", || { - open(&mut app); - app.eventually("as left", |tree| { - rows(tree) - == ["Write the changelog", "Tag the release", "Publish the binaries", "Freeze the merges"] - && ticks(tree) == [false, true, false, false] - }); - close(&mut app); - }); - - step("a row is ticked from the card without opening it", || { - app.click_nth("note-card-item", 0); - app.eventually("the editor stayed closed", |tree| !tree.has("editor-title")); - app.eventually("the card's progress counts it", |tree| { - tree.text("note-card-progress").as_deref() == Some("2/4") - }); - open(&mut app); - app.eventually("the first open row ticked", |tree| ticks(tree).first() == Some(&true)); - close(&mut app); - }); - - app.quit(); -} diff --git a/e2e/tests/07_reaching_from_anywhere.rs b/e2e/tests/07_reaching_from_anywhere.rs new file mode 100644 index 000000000..ee4db9cf4 --- /dev/null +++ b/e2e/tests/07_reaching_from_anywhere.rs @@ -0,0 +1,226 @@ +//! Journey 7, « Reaching DevNotes from anywhere »: a second launch, the palette, the clipboard, the +//! keys of the whole machine and the tray, with the window in sight, put away or minimised — the +//! same on every system. + +use e2e::{App, Area, Global, Sample, Switch, TrayEntry, step}; + +const SNIPPET: &str = "Jump host"; +const NOTHING: &str = "zq nothing is called this"; +const WORDS: &str = "captured from elsewhere"; +/// macOS keeps its own buttons, its « minimise » among them, out of a journey's reach: closing with +/// « Close to tray » is what minimises there. +const OWN_BUTTONS: bool = !cfg!(target_os = "macos"); + +#[test] +fn reaching_from_anywhere() { + let mut app = App::open_with_a_tray("07_reaching_from_anywhere"); + app.notes().write_snippet(SNIPPET, "ssh {{host}} -p {{port=22}}"); + app.window().go_to(Area::Http); + app.http().new_collection("Shop"); + app.http().new_request("Shop", "Checkout"); + app.window().go_to(Area::Notes); + + a_second_launch(&mut app); + the_palette(&mut app); + from_the_machine(&mut app); + put_away(&mut app); + the_tray(&mut app); + without_the_tray(app); +} + +fn a_second_launch(app: &mut App) { + step("a second launch hands over to the running window, and ends", || { + app.window().start_again(); + app.window().expect_in_sight("the one window is on the screen"); + app.notes().expect_card(SNIPPET, "the library is as it was, still open"); + }); +} + +fn the_palette(app: &mut App) { + step("the palette opens from the window's key, narrows, and opens a note on Enter", || { + app.palette().open(); + app.palette().expect_answers("the recent notes are listed"); + app.capture("palette"); + app.palette().search("withRetry"); + app.palette().expect_one_answer("one note answers"); + app.palette().choose_first(); + app.editor().expect_code_open("the note is open"); + app.editor().close(); + }); + + step("it copies a note, asking for its fields", || { + app.press_global(Global::Palette); + app.palette().expect_open("a second launch opens it too"); + app.palette().search(SNIPPET); + app.palette().expect_only(SNIPPET, "the snippet alone answers"); + app.palette().copy_first(); + app.fields().expect_open("the form asks for the fields"); + app.fields().type_value(0, "db.internal"); + app.fields().copy(); + app.clipboard().expect("ssh db.internal -p 22", "the snippet is copied, filled"); + }); + + step("a name nothing has becomes a new note", || { + app.palette().open(); + app.palette().search(NOTHING); + app.palette().expect_creation_offered("a note of that name is offered"); + app.palette().choose_first(); + app.editor().expect_title(NOTHING, "the note is open, named so"); + app.editor().close(); + app.notes().expect_card(NOTHING, "it has its card"); + }); + + step("« > » lists the commands", || { + app.palette().open(); + app.palette().search(">"); + app.palette().expect_commands("the commands are listed"); + app.palette().close(); + }); + + step("« @ » chooses where to search, the notes of one space included", || { + app.rail().new_space("Annex"); + app.notes().write_snippet("Annex door", "open sesame"); + app.rail().show_all_spaces(); + app.palette().open(); + app.palette().narrow_to("@Annex"); + app.palette().expect_only("Annex door", "the space's one note is listed"); + app.palette().close(); + }); + + step("« # » lists the notes of a tag", || { + app.notes().open(SNIPPET); + app.editor().add_tag("quokka"); + app.editor().close(); + app.palette().open(); + app.palette().narrow_to("#quokka"); + app.palette().expect_only(SNIPPET, "the one note with the tag is listed"); + app.palette().close(); + }); + + step("it finds requests, tools and spaces too", || { + app.palette().open(); + app.palette().search("Checkout"); + app.palette().expect_found("Checkout", "the request is found"); + app.palette().search("base64"); + app.palette().expect_found("Base64", "the tool is found"); + app.palette().search("Annex"); + app.palette().expect_found("Annex", "the space is found, with its note"); + app.palette().close(); + }); +} + +fn from_the_machine(app: &mut App) { + step("the clipboard is captured into a note", || { + app.notes().write_snippet("Source", WORDS); + app.notes().copy("Source"); + app.clipboard().expect(WORDS, "the words are on the clipboard"); + app.press_global(Global::PasteFromClipboard); + app.rich().expect_text(WORDS, "a note holds them"); + app.editor().close(); + }); + + step("a new empty note opens", || { + app.press_global(Global::NewNote); + app.editor().expect_title("", "an empty note is open"); + app.editor().close(); + }); +} + +fn put_away(app: &mut App) { + step("closed with « Close to tray » on, DevNotes stays, and a second launch brings it back", || { + app.window().close_to_tray(); + app.window().start_again(); + app.window().expect_back("the window went away once, and is back"); + app.notes().expect_card(SNIPPET, "the library is still open"); + }); + + step("the keys of the machine answer with the window put away", || { + app.window().close_to_tray(); + app.press_global(Global::Palette); + app.window().expect_back("the window is back"); + app.palette().expect_open("the palette over it"); + app.palette().close(); + app.window().close_to_tray(); + app.press_global(Global::NewNote); + app.window().expect_back("the window is back"); + app.editor().expect_title("", "an empty note is open"); + app.editor().close(); + app.window().close_to_tray(); + app.press_global(Global::PasteFromClipboard); + app.window().expect_back("the window is back"); + app.rich().expect_text(WORDS, "a note holds the clipboard"); + app.editor().close(); + }); + + if !OWN_BUTTONS { + step("macOS has its own « minimise »: closing minimised, and the keys answered", || { + app.window().expect_system_buttons("DevNotes draws none of its own"); + }); + return; + } + + step("they answer with it minimised", || { + app.window().minimize(); + app.press_global(Global::Palette); + app.window().expect_back("the window is back"); + app.palette().expect_open("the palette over it"); + app.palette().close(); + app.window().minimize(); + app.press_global(Global::NewNote); + app.window().expect_back("the window is back"); + app.editor().leave_by_escape(); + }); + + step("with « Minimize to tray » on, minimising puts it away too", || { + app.prefs().change(|prefs| prefs.flip(Switch::MinimizeToTray)); + app.window().minimize_to_tray(); + app.window().start_again(); + app.window().expect_back("a second launch brings it back"); + app.prefs().change(|prefs| prefs.flip(Switch::MinimizeToTray)); + }); +} + +fn the_tray(app: &mut App) { + step("« Palette », « New note » and « Paste from clipboard » do what they say", || { + app.window().close_to_tray(); + app.tray().choose(TrayEntry::Palette); + app.window().expect_back("the window is back"); + app.palette().expect_open("the palette over it"); + app.palette().close(); + app.window().close_to_tray(); + app.tray().choose(TrayEntry::NewNote); + app.window().expect_back("the window is back"); + app.editor().expect_title("", "an empty note is open"); + app.editor().close(); + app.window().close_to_tray(); + app.tray().choose(TrayEntry::PasteFromClipboard); + app.window().expect_back("the window is back"); + app.rich().expect_text(WORDS, "a note holds the clipboard"); + }); + + step("« Open DevNotes » brings the window back as it was", || { + app.window().close_to_tray(); + app.tray().choose(TrayEntry::Open); + app.window().expect_back("the window is back"); + app.rich().expect_text(WORDS, "the note is still open"); + app.editor().close(); + }); +} + +fn without_the_tray(mut app: App) { + step("« Quit » ends DevNotes, its window out of sight", || { + app.window().close_to_tray(); + app.tray().choose(TrayEntry::Quit); + app.start_after_the_end(); + app.notes().expect_card(SNIPPET, "the library is as it was left"); + }); + + step("with « Close to tray » off, closing ends it, and the library is found as it was", || { + app.prefs().change(|prefs| prefs.flip(Switch::CloseToTray)); + app.window().close_for_good(); + app.start_after_the_end(); + app.notes().expect_card(Sample::Welcome, "the library is as it was left"); + }); + + app.quit(); +} diff --git a/e2e/tests/08_placeholder_fields.rs b/e2e/tests/08_placeholder_fields.rs deleted file mode 100644 index b2302e070..000000000 --- a/e2e/tests/08_placeholder_fields.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! `{{fields}}` in a snippet: copied, the note asks for them first, from the card as from the -//! keyboard; what is typed is kept, what is cancelled is not. In the editor the panel counts them, -//! folds and shows the body filled. The sample used is found by its code, which no translation -//! touches. - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -/// What the first field holds: its value, not its name. -fn first_value(tree: &e2e::Tree) -> String { - tree.all("placeholder-input") - .first() - .and_then(|field| field.value()) - .unwrap_or_default() - .to_owned() -} - -/// The card's fill button, which a note with fields shows instead of a plain copy. -fn open_from_card(app: &mut App) { - app.hover("note-card-open"); - app.click("note-card-fill"); - app.wait_for("placeholder-form-hint"); -} - -fn open_editor(app: &mut App) { - app.click("note-card-open"); - app.wait_for("editor-title"); -} - -fn close_editor(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); -} - -/// `1/4`: what the panel's head counts. -fn counted(tree: &e2e::Tree) -> String { - tree.all("placeholder-panel-toggle") - .first() - .and_then(|toggle| toggle.value()) - .unwrap_or_default() - .to_owned() -} - -fn closed(app: &mut App) { - app.eventually("the form is closed", |tree| !tree.has("placeholder-form-hint")); -} - -#[test] -fn placeholder_fields() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("08_placeholder_fields", profile.path()); - app.create_library(); - app.wait_for("note-card"); - app.fill("search-input", "5432"); - app.eventually("the snippet with fields, alone", |tree| tree.count("note-card") == 1); - - step("the keyboard asks for the fields too, in the first one", || { - app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); - app.press(Key::C, Modifiers::NONE); - app.eventually("the form, typing in its first field", |tree| { - tree.focused().starts_with("placeholder-input") - }); - app.capture("placeholder-form"); - app.press(Key::Escape, Modifiers::NONE); - closed(&mut app); - }); - - step("the card offers the fields instead of a plain copy", || { - app.hover("note-card-open"); - app.wait_for("note-card-fill"); - assert!(!app.has("note-card-copy")); - }); - - step("what is typed is copied filled, and kept", || { - open_from_card(&mut app); - app.type_text("db.internal"); - app.press(Key::Enter, Modifiers::NONE); - closed(&mut app); - app.wait_for("status-toast"); - open_from_card(&mut app); - app.eventually("the value typed comes back", |tree| first_value(tree) == "db.internal"); - }); - - step("cancelled, the form writes nothing", || { - app.click_nth("placeholder-input", 0); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("db.discarded"); - app.click("placeholder-cancel"); - closed(&mut app); - open_from_card(&mut app); - app.eventually("the value kept is still there", |tree| first_value(tree) == "db.internal"); - }); - - step("« copy as is » copies and closes", || { - app.click("placeholder-copy-raw"); - closed(&mut app); - app.wait_for("status-toast"); - }); - - step("the editor's panel counts what is kept, default aside", || { - open_editor(&mut app); - app.eventually("one field filled of four", |tree| counted(tree) == "1/4"); - app.capture("fields-panel"); - }); - - step("the body is shown filled, and given back", || { - app.click("placeholder-panel-preview"); - app.eventually("the code gives way", |tree| !tree.has("editor-body")); - app.capture("fields-preview"); - app.click("placeholder-panel-preview"); - app.wait_for("editor-body"); - }); - - step("folded, the panel stays so for the next note opened", || { - app.click("placeholder-panel-toggle"); - app.eventually("the fields gone", |tree| !tree.has("placeholder-input")); - close_editor(&mut app); - open_editor(&mut app); - app.wait_for("placeholder-panel-toggle"); - assert!(!app.has("placeholder-input")); - app.click("placeholder-panel-toggle"); - app.wait_for("placeholder-input"); - close_editor(&mut app); - }); - - app.quit(); -} diff --git a/e2e/tests/08_tools.rs b/e2e/tests/08_tools.rs new file mode 100644 index 000000000..c2e116357 --- /dev/null +++ b/e2e/tests/08_tools.rs @@ -0,0 +1,207 @@ +//! Journey 8, « The tools »: the home and its search, the whole catalogue walked as one table, what +//! is remembered of it, an answer kept as a note, and the tools that read or write files. + +use e2e::{App, Area, Copied, Given, Language, step}; + +/// A row per tool and reference: its name, what it is given, what it answers, and how that copies. +/// A tool added to the application is a row added here. +const CATALOGUE: &[(&str, Given, &str, Copied)] = &[ + ("Case converter", Given::Example, "parse_url_and_http_server", Copied::Shown("snake_case")), + ("Line breaks", Given::Example, "2 lines trimmed", Copied::Shown("Result")), + ("Text statistics", Given::Example, "34 distinct characters", Copied::Nothing), + ("Diff", Given::Example, "+ 4 lines", Copied::Nothing), + ("Hash / HMAC", Given::Example, MD5, Copied::Shown("MD5")), + ("Passwords", Given::Example, "bits of entropy", Copied::Shown("#1")), + ("Identifiers", Given::Example, "ULID · 26 characters, base32", Copied::Shown("every identifier")), + ("JWT", Given::Example, "Valid signature.", Copied::Shown("Payload")), + ("URL", Given::Example, "caf%C3%A9%20cr%C3%A8me", Copied::Shown("Encoded")), + ("Base64 and other bases", Given::Example, "Q2Fmw6k=", Copied::Shown("Base64")), + ("JSON ↔ YAML ↔ TOML ↔ XML", Given::Example, "codePostal = \"75001\"", Copied::Shown("Result")), + ("Colours", Given::Example, "oklch(65.2% 0.19 253.2)", Copied::Shown("OKLCH")), + ("JSON", Given::Example, "\"createdAt\"", Copied::Shown("Documents")), + ( + "Fictitious identity", + Given::Example, + "the same person comes back", + Copied::Shown("Document number (made up)"), + ), + ("Lorem ipsum", Given::Example, "Lorem ipsum dolor sit amet", Copied::Shown("Lorem ipsum")), + ("QR code", Given::Example, "25 × 25 modules", Copied::Nothing), + ("Dates and durations", Given::Example, "2023-11-14T22:13:20Z", Copied::Shown("ISO 8601 · UTC")), + ("Time zones", Given::Example, "UTC+09:00", Copied::Holding("Asia/Tokyo", "+09:00")), + ("Cron", Given::Example, "Every 15 minutes, from 9:00 to 18:00", Copied::Nothing), + ("Sizes and transfer", Given::Example, "4,700,000,000", Copied::Raw("B", "4700000000")), + ("Unix permissions", Given::Example, "chmod 754 file", Copied::Shown("chmod")), + ( + "Luhn and IBAN", + Given::Example, + "FR76 3000 6000 0112 3456 7890 189", + Copied::Raw("IBAN", "FR7630006000011234567890189"), + ), + ("CIDR subnets", Given::Example, "255.255.248.0", Copied::Shown("Mask")), + ("HTTP status codes", Given::Search("teapot"), "418", Copied::Shown("418")), + ("HTTP headers", Given::Search("etag"), "ETag", Copied::Shown("ETag")), + ("MIME types", Given::Search("svg"), "image/svg+xml", Copied::Shown("image/svg+xml")), + ("Common ports", Given::Search("postgres"), "5432", Copied::Shown("5432")), + ("Unix signals", Given::Search("sigterm"), "SIGTERM", Copied::Shown("SIGTERM")), + ("ASCII table", Given::Search("0x26"), "38", Copied::Shown("&")), + ("Regex cheat sheet", Given::Search("lookahead"), "(?=…)", Copied::Shown("(?=…)")), + ("Markdown cheat sheet", Given::Search("footnote"), "[^1]", Copied::Shown("[^1]")), + ("Mustache cheat sheet", Given::Search("partial"), "{{> partial}}", Copied::Shown("{{> partial}}")), +]; + +/// Of « hello world », in the Example and in a file. +const MD5: &str = "5eb63bbbe01eeed093cb22bb8f5acdc3"; +/// A favourite is not said again among the last ones opened. +const RECENT: [&str; 2] = ["Colours", "Mustache cheat sheet"]; +const SPACE: &str = "Workshop"; +const FOLDER: &str = "Digests"; + +#[test] +fn tools() { + let mut app = App::open("08_tools"); + app.prefs().change(|prefs| prefs.choose_language(Language::English)); + app.window().widen(); + app.rail().new_space(SPACE); + app.rail().new_folder(FOLDER); + + the_home(&mut app); + the_catalogue(&mut app); + what_is_remembered(&mut app); + with_the_notes(&mut app); + with_files(&mut app); + app.quit(); +} + +fn the_home(app: &mut App) { + step("from the notes, the shortcut goes to the tools and their search", || { + app.tools().go_to_search(); + app.tools().expect_catalogue_of(CATALOGUE.len(), "the home lists every tool"); + app.capture("home"); + }); + + step("a keyword finds the tool it is for, and Enter opens it", || { + app.tools().search("crlf"); + app.tools().expect_listed("Line breaks", "the tool answers"); + app.tools().expect_not_listed("Hash / HMAC", "the others are gone"); + app.tools().open_first(); + app.tools().expect_open("Line breaks", "its tool opens"); + }); + + step("what no tool answers is found in the references", || { + app.tools().go_to_search(); + app.tools().search("418"); + app.tools().expect_answer("teapot", "the reference's row is shown"); + app.tools().open_first(); + app.tools().expect_open("HTTP status codes", "its reference opens"); + }); + + step("the home is sorted by category", || { + app.tools().go_to_search(); + app.tools().clear_search(); + app.tools().choose_category("Time"); + app.tools().expect_listed("Cron", "the category's tools are listed"); + app.tools().expect_not_listed("Hash / HMAC", "the others are not"); + app.tools().show_all(); + app.tools().expect_listed("Hash / HMAC", "every tool is back"); + }); +} + +fn the_catalogue(app: &mut App) { + for &(tool, given, answer, copied) in CATALOGUE { + step(&format!("{tool}: opened from the keyboard, it answers, and its answer is copied"), || { + app.tools().open_from_the_keyboard(tool); + app.tools().give(given); + app.tools().expect_answer(answer, "it answers"); + app.tools().expect_copied(copied, "the answer is copied"); + }); + } +} + +fn what_is_remembered(app: &mut App) { + step("a star makes a favourite, and the last ones opened are listed, over a relaunch", || { + app.tools().open_from_the_keyboard("Cron"); + app.tools().flip_star(); + app.tools().open_from_the_keyboard("Colours"); + app.tools().go_to_search(); + app.tools().clear_search(); + app.tools().expect_favourite("Cron", "the starred one is a favourite"); + app.tools().expect_recent(&RECENT, "the last ones opened are listed"); + app.relaunch_and_unlock(); + app.tools().expect_favourite("Cron", "it still is"); + app.tools().expect_recent(&RECENT, "they still are"); + app.capture("remembered"); + }); +} + +fn with_the_notes(app: &mut App) { + step("*Save as note* files the answer where it is told, never what was typed", || { + app.tools().open_from_the_keyboard("Hash / HMAC"); + app.tools().give(Given::Example); + app.tools().expect_answer(MD5, "it answers"); + app.tools().save_as_note("Digests of a greeting", (SPACE, FOLDER), "checksum"); + app.window().go_to(Area::Notes); + app.rail().open_folder(FOLDER); + app.notes().open("Digests of a greeting"); + app.editor().expect_code_holding(MD5, "the note holds the answer"); + app.editor().expect_code_without("hello world", "and not what was typed"); + app.editor().expect_tag("checksum", "with its tag"); + app.editor().close(); + }); + + step("a tool's text is filled from a note", || { + app.notes().write_snippet("Search address", "a b&c"); + app.tools().open_from_the_keyboard("URL"); + app.tools().fill_from_note("Search address"); + app.tools().expect_answer("a%20b%26c", "it answers the note"); + }); +} + +fn with_files(app: &mut App) { + step("a file is hashed", || { + app.files().put("greeting.txt", b"hello world"); + app.files().answer("greeting.txt"); + app.tools().open_from_the_keyboard("Hash / HMAC"); + app.tools().hash_file(); + app.tools().expect_answer(MD5, "the file's digest is the text's"); + app.tools().expect_copied(Copied::Shown("MD5"), "it is copied"); + }); + + step("a picture is read into Base64, decoded into what it shows, and saved back", || { + app.files().put_picture("dot.png"); + app.files().answer("dot.png"); + app.tools().open_from_the_keyboard("Base64 and other bases"); + app.tools().encode_file(); + app.tools().expect_copied(Copied::Shown("Base64"), "its Base64 is copied"); + app.tools().decode_what_was_copied(); + app.tools().expect_picture("1 × 1", "the picture is shown, with its size"); + app.capture("base64"); + app.files().answer("back.png"); + app.tools().save_decoded(); + app.files() + .expect_same("back.png", "dot.png", "the bytes saved are the picture's"); + }); + + step("a QR code is saved as PNG and as SVG", || { + app.tools().open_from_the_keyboard("QR code"); + app.tools().give(Given::Example); + app.tools().expect_answer("25 × 25 modules", "the code is drawn"); + app.files().answer("code.png"); + app.tools().save_code_as_png(); + app.files() + .expect("code.png", "the PNG is written", |bytes| bytes.starts_with(b"\x89PNG")); + app.files().answer("code.svg"); + app.tools().save_code_as_svg(); + app.files() + .expect("code.svg", "the SVG is written", |bytes| bytes.starts_with(b"<")); + }); + + step("fictitious people are saved", || { + app.tools().open_from_the_keyboard("Fictitious identity"); + app.tools().give(Given::Example); + app.files().answer("people.json"); + app.tools().export_people(); + app.files() + .expect("people.json", "the people are written", |bytes| bytes.starts_with(b"[")); + }); +} diff --git a/e2e/tests/09_calling_an_api.rs b/e2e/tests/09_calling_an_api.rs new file mode 100644 index 000000000..c38608171 --- /dev/null +++ b/e2e/tests/09_calling_an_api.rs @@ -0,0 +1,381 @@ +//! Journey 9, « Calling an API »: a collection and its requests, what a request is written with and +//! what its answer says, the environments it is sent with, the code it becomes and what is kept of +//! it. Everything is sent to a server of the journey's own. + +use e2e::{App, Area, Auth, Body, BodyView, Method, Part, Shortcut, step}; + +const COLLECTION: &str = "Shop"; +const FOLDER: &str = "Accounts"; + +#[test] +fn calling_an_api() { + let mut app = App::open("09_calling_an_api"); + let api = app.serve_api(); + app.window().widen(); + app.window().go_to(Area::Http); + + the_rail(&mut app); + the_tabs(&mut app); + what_a_request_is_made_of(&mut app, &api); + what_the_answer_says(&mut app, &api); + other_kinds_of_requests(&mut app, &api); + the_environments(&mut app, &api); + as_code(&mut app); + what_is_kept(&mut app, &api); + app.quit(); +} + +fn the_rail(app: &mut App) { + step("a collection, a folder and its requests are made from the empty rail", || { + app.http().new_collection(COLLECTION); + app.http().new_folder(COLLECTION, FOLDER); + app.http().new_request(FOLDER, "Login"); + app.http().new_socket(FOLDER, "Feed"); + app.http() + .expect_rows(&[COLLECTION, FOLDER, "GET Login", "WS Feed"], "each is where it was made"); + }); + + step("a request is moved by the keys, out of its folder and back into it", || { + app.http().take_row("Feed"); + app.press(Shortcut::MoveUp); + app.http() + .expect_rows(&[COLLECTION, FOLDER, "WS Feed", "GET Login"], "it is before the other"); + app.http().expect_move_said("Login", "what it passed is said"); + app.press(Shortcut::MoveOut); + app.http() + .expect_rows(&[COLLECTION, FOLDER, "GET Login", "WS Feed"], "it is out of the folder"); + app.press(Shortcut::MoveIn); + app.http().expect_move_said(FOLDER, "it is back in the folder"); + }); + + step("a request is renamed in place, by F2 and from its menu", || { + app.http().rename("Feed", "Live feed"); + app.http().rename_from_the_menu("Live feed", "Orders feed"); + }); + + step("a request and a folder are deleted once the rail has said what goes with them", || { + app.http().new_folder(COLLECTION, "Old"); + app.http().new_request("Old", "Forgotten"); + app.http().new_request(COLLECTION, "Spare"); + app.http().ask_deletion("Old"); + app.http().expect_deletion_counted("the rail says what is in the folder"); + app.http().cancel_deletion(); + app.http().ask_deletion("Old"); + app.http().confirm_deletion(); + app.http().ask_deletion("Spare"); + app.http().confirm_deletion(); + app.http() + .expect_rows(&[COLLECTION, FOLDER, "GET Login", "WS Orders feed"], "both are gone"); + }); +} + +fn the_tabs(app: &mut App) { + step("each request opens in its tab, and a draft asks before it closes", || { + app.http().open("Login"); + app.http().open("Orders feed"); + app.http().new_draft(); + app.http().close_last_tab_discarding(); + app.http().new_draft(); + app.http().close_last_tab_with_the_middle_button(); + app.capture("rail"); + }); + + step("a tab is dragged past the other, the folder folded, and both found over a relaunch", || { + app.http() + .expect_tabs_in_order(&["Login", "Orders feed"], "the tabs are as they were opened"); + app.http().drag_first_tab(); + app.http() + .expect_tabs_in_order(&["Orders feed", "Login"], "the first went past the other"); + app.http().fold(FOLDER); + app.http().expect_rows(&[COLLECTION, FOLDER], "the folder is folded"); + app.relaunch_and_unlock(); + app.http().expect_rows(&[COLLECTION, FOLDER], "it still is"); + app.http() + .expect_tabs_in_order(&["Orders feed", "Login"], "the tabs are in their order"); + app.http().fold(FOLDER); + }); +} + +fn what_a_request_is_made_of(app: &mut App, api: &str) { + step("the address and its parameters are kept in step", || { + app.http().open("Login"); + app.request().type_url(&format!("{api}/echo?page=2&q=x")); + app.request().expect_params(&["page", "q"], "the table follows the address"); + app.request().flip_param(0); + app.request() + .expect_url(&format!("{api}/echo?q=x"), "the address follows the table"); + }); + + step("a header is typed as it is read", || { + app.request().type_header("X-Trace: abc"); + app.request() + .expect_first_header("X-Trace", "abc", "it is split into its two cells"); + app.request().send(); + app.response().expect_body("x-trace: abc", "it was sent"); + }); + + step("the auth and the headers of the collection go with its requests", || { + app.http().set_below(COLLECTION, "from-the-shop", ("X-Tenant", "north")); + app.request() + .expect_inherited_from(COLLECTION, "the auth says where it is from"); + app.request().send(); + app.response() + .expect_body("Bearer from-the-shop", "the collection's token was sent"); + app.response().expect_body("x-tenant: north", "and its header"); + }); + + step("a request has an auth of its own: Basic, Bearer and an API key", || { + app.request().choose_auth(Auth::Basic { name: "ada", password: "secret" }); + app.request().send(); + app.response().expect_body("Basic YWRhOnNlY3JldA==", "Basic was sent"); + app.request().choose_auth(Auth::Bearer("own-token")); + app.request().expect_secret_masked("own-token", "the token is masked"); + app.request().flip_secret(); + app.request().expect_secret("own-token", "and shown when asked"); + app.request().send(); + app.response().expect_body("Bearer own-token", "Bearer was sent"); + app.request().choose_auth(Auth::ApiKey { name: "X-Api-Key", value: "k3y" }); + app.request().send(); + app.response().expect_body("x-api-key: k3y", "the key was sent"); + app.request().choose_auth(Auth::Inherited); + }); + + step("a body is written in JSON, as a form, in parts, and taken from a file", || { + app.files().put("invoice.txt", b"one invoice"); + app.files().answer("invoice.txt"); + app.request().choose_method(Method::Post); + app.request().type_body(Body::Json("{\"amount\": 4900}")); + app.request().expect_json_valid("the body reads, and its type is said"); + app.request().send(); + app.response().expect_body("{\"amount\": 4900}", "it left as it was written"); + app.request().type_body(Body::Form("city", "Lyon")); + app.request().send(); + app.response().expect_body("city=Lyon", "the form was sent"); + app.request().type_body(Body::Multipart(("city", "Lyon"), "invoice")); + app.request().send(); + app.response().expect_body("name=\"city\"", "the part was sent"); + app.response().expect_body("one invoice", "and the file"); + app.request().type_body(Body::File); + app.request().send(); + app.response().expect_body("one invoice", "the file alone was sent"); + app.capture("body-file"); + }); +} + +fn what_the_answer_says(app: &mut App, api: &str) { + step("the answer has its status, its time and its size, and its body four ways", || { + app.request().choose_method(Method::Get); + app.request().send_to(&format!("{api}/json")); + app.response().expect_status("200 OK", "the status is shown"); + app.response().expect_time_and_size("with how long it took and what it weighs"); + app.response().expect_body("Ada", "the body is formatted"); + app.response().show_as(BodyView::Raw); + app.response().expect_body("\"admin\":true", "it is read as it came"); + app.response().show_as(BodyView::Graph); + app.json().expect_nodes(2, "it is drawn as a graph"); + app.response().show_as(BodyView::Tree); + app.json().expect_listed("$.name", "it is a tree"); + app.capture("answer"); + }); + + step("its headers, its cookies and the exchange are read beside it, redirects too", || { + app.response().go_to(Part::Headers); + app.response().expect_saying("set-cookie", "its headers are listed"); + app.response().go_to(Part::Cookies); + app.response().expect_cookie("session", "its cookie is listed"); + app.request().send_to(&format!("{api}/redirect/3")); + app.response().go_to(Part::Timeline); + app.response().expect_redirects(3, "each redirect is shown"); + app.response() + .expect_sent(&format!("GET {api}/redirect/3"), "with what was sent"); + app.response().go_to(Part::Body); + app.request().send_to(&format!("{api}/png")); + app.response().expect_picture("a picture is shown"); + }); + + step("a slow send is cancelled", || { + app.request().send_to(&format!("{api}/slow")); + app.request().cancel_send(); + app.response().expect_cancelled("the send is over"); + }); + + step("Ctrl+S saves the request, and a draft into the collection", || { + app.request().save(); + app.http().new_draft(); + app.request().type_url(&format!("{api}/json")); + app.request().save_as("Health"); + app.http().expect_rows( + &[COLLECTION, FOLDER, "GET Login", "WS Orders feed", "GET Health"], + "the draft is in the collection", + ); + app.http().show_tab("Login"); + }); + + step("a value of the answer is kept in a variable by a rule, and the next request uses it", || { + app.request().send_to(&format!("{api}/json")); + app.response().show_as(BodyView::Tree); + app.json().select_in_the_tree("$.name"); + app.response().extract_to("who"); + app.request().send(); + app.response().expect_status("200 OK", "the rule is followed"); + app.request().send_to(&format!("{api}/echo?who={{{{who}}}}")); + app.response().expect_body("/echo?who=Ada", "the value was sent"); + }); + + step("the cookies the server set are listed, and thrown away", || { + app.http().open_cookies(); + app.http().expect_cookie("session", "the cookie is in the jar"); + app.http().throw_cookies_away(); + }); +} + +fn other_kinds_of_requests(app: &mut App, api: &str) { + step("a GraphQL request names the variables it lacks, and is sent", || { + app.http().new_graphql_draft(); + app.request().type_name("Products"); + app.request() + .type_query("query One($code: ID!) { product(code: $code) { id } }"); + app.request().expect_missing_variable("$code", "the variable is named"); + app.request().add_missing_variables(); + app.request().expect_no_missing_variable("it is added"); + app.request().send_to(&format!("{api}/echo")); + app.response().expect_body("query One", "the query was sent"); + app.http().close_last_tab_discarding(); + }); + + step("a WebSocket connects, its log shows what goes and comes, and a message kept is sent again", || { + let socket = app.serve_socket(); + app.http().open("Orders feed"); + app.request().type_url(&socket); + app.socket().flip_connection(); + app.socket().expect_log(1, "it is connected"); + app.socket().send("ping"); + app.socket().expect_logged("ping", 2, "the message went, and came back"); + app.socket().keep(); + app.socket().send_kept(); + app.socket().expect_logged("ping", 4, "it went again, and came back"); + app.capture("socket"); + app.socket().flip_connection(); + app.socket().expect_log(6, "it is disconnected"); + app.request().save(); + }); +} + +fn the_environments(app: &mut App, api: &str) { + step("two environments are made, each with its colour and its secret", || { + app.environments().open(); + app.environments().create("Local"); + app.environments().choose_colour(3); + app.environments().add_variable("base_url", api); + app.environments().add_secret("api_key", "l0cal"); + app.environments().create("Production"); + app.environments().choose_colour(4); + app.environments().add_variable("base_url", api); + app.environments().add_secret("api_key", "pr0d"); + app.environments().protect(); + app.capture("environments"); + app.environments().leave(); + }); + + step("a variable takes the value of the environment chosen, and its card says from where", || { + app.environments().choose("Local"); + app.http().open("Login"); + app.request().type_url("{{base_url}}/echo?key={{api_key}}"); + app.request().point_at_variable("base_url"); + app.request().expect_variable_value(api, "the card says its value"); + app.request().expect_variable_from("Local", "and where it is from"); + app.request().point_at_variable("api_key"); + app.request().expect_variable_masked("the secret is masked"); + app.request().reveal_variable(); + app.request().expect_variable_value("l0cal", "and shown when asked"); + app.request().send(); + app.response().expect_body("/echo?key=l0cal", "both were sent"); + }); + + step("a name set nowhere stops the send, and *Set in…* leads to where it goes", || { + app.request().type_url("{{base_url}}/echo?{{nowhere}}"); + app.request().send(); + app.response().expect_refused("nowhere", "the send is refused, the name said"); + app.request().point_at_variable("nowhere"); + app.request().define_variable(); + app.environments().type_value_of("nowhere", "found"); + app.environments().leave(); + app.request().send(); + app.response().expect_body("/echo?found", "it is set, and sent"); + }); + + step("a protected environment asks before a POST, not before a GET", || { + app.environments().choose("Production"); + app.request().type_url("{{base_url}}/echo?key={{api_key}}"); + app.request().send(); + app.response().expect_body("/echo?key=pr0d", "the GET left at once"); + app.request().choose_method(Method::Post); + app.request().send(); + app.request().expect_asked_before_sending("the POST waits for a yes"); + app.request().do_not_send(); + app.request().send(); + app.request().send_anyway(); + app.response().expect_body("POST /echo?key=pr0d", "the yes let it leave"); + }); +} + +fn as_code(app: &mut App) { + step("the request is written as code, its secret left as a variable until a yes", || { + app.code().open(); + app.code().expect("/echo?key=", "the address is there"); + app.code().expect_without("pr0d", "the secret is not"); + app.code().choose("fetch", "JavaScript · fetch"); + app.code().expect("await fetch(", "it is written for a browser"); + app.code().choose("elixir", "Elixir · Req"); + app.code().expect("Req.request!(", "and for Elixir"); + app.code().ask_secrets(); + app.code().include_secrets(); + app.code().expect("pr0d", "the secret is there"); + app.capture("code"); + app.code().copy(); + app.clipboard().expect_saying("Req.request!(", "the code is copied"); + app.code().close(); + }); +} + +fn what_is_kept(app: &mut App, api: &str) { + step("the history holds what was sent, its secrets masked", || { + app.sends().open(); + app.sends().read_last_of("Login"); + app.sends().expect_masked("pr0d", "the secret is nowhere"); + app.capture("history"); + }); + + step("a send is reopened in its request, another as a draft, and they are erased", || { + app.sends().reopen(); + app.request() + .expect_url(&format!("{api}/echo?key={{{{api_key}}}}"), "its request holds what was sent"); + app.request().save(); + app.sends().open(); + app.sends().read_last_of("Products"); + app.sends().reopen(); + app.http().expect_tabs(4, "a draft is open beside the requests"); + app.http().close_last_tab_discarding(); + app.sends().open(); + app.sends().erase_first(); + app.sends().erase_all(); + app.sends().leave(); + }); + + step("an answer is saved to a file, and another kept as a note", || { + app.environments().choose("Local"); + app.request().choose_method(Method::Get); + app.files().answer("large.txt"); + app.request().send_to(&format!("{api}/large")); + app.response().save_to_file(); + app.files() + .expect("large.txt", "the whole answer is in the file", |bytes| bytes.len() > 1024 * 1024); + app.request().send_to(&format!("{api}/json")); + app.response().save_as_note("Who is there"); + app.request().save(); + app.window().go_to(Area::Notes); + app.notes().open("Who is there"); + app.editor().expect_code_holding("Ada", "the note holds the answer"); + app.editor().close(); + }); +} diff --git a/e2e/tests/09_quick_palette.rs b/e2e/tests/09_quick_palette.rs deleted file mode 100644 index ced1d665b..000000000 --- a/e2e/tests/09_quick_palette.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! The palette, opened from a second launch as the global shortcut will open it, and from its -//! key in the window: it narrows to what is typed, opens on Enter, offers to create a note named -//! after a query that finds nothing, and lists the commands after `>`. What is searched is in the -//! samples' code, which no translation touches. - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; -const NOTHING: &str = "zq query matching nothing at all"; - -fn opened(app: &mut App) { - app.eventually("the palette is open, typing in its field", |tree| { - tree.focused().starts_with("palette-input") - }); -} - -/// What the field holds, then the palette's answer, past its pause. -fn search(app: &mut App, words: &str) { - app.press(Key::A, Modifiers::COMMAND); - app.type_text(words); -} - -fn editor_title(tree: &e2e::Tree) -> Option { - tree.find("editor-title").and_then(|field| field.value()).map(str::to_owned) -} - -#[test] -fn quick_palette() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("09_quick_palette", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); - - step("a second launch opens it, on the recent notes", || { - app.act("palette"); - opened(&mut app); - app.eventually("recent notes, and nothing said empty", |tree| { - tree.count("palette-option") > 0 && !tree.has("palette-empty") - }); - app.capture("palette-recent"); - }); - - step("it narrows to what is typed, and Enter opens the note", || { - search(&mut app, "withRetry"); - app.eventually("one note answers", |tree| tree.count("palette-option") == 1); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the editor is open on it, the palette gone", |tree| { - tree.has("editor-title") && !tree.has("palette-input") - }); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - }); - - step("a query that finds nothing offers a note named after it", || { - app.press(Key::P, Modifiers::COMMAND | Modifiers::ALT); - opened(&mut app); - search(&mut app, NOTHING); - app.eventually("the offer replaces the list, and says nothing matched", |tree| { - tree.has("palette-create") && tree.has("palette-empty") && tree.count("palette-option") == 0 - }); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the note opens titled, already written", |tree| { - editor_title(tree).as_deref() == Some(NOTHING) - }); - app.click("editor-close"); - app.eventually("one card more", |tree| tree.count("note-card") == CARDS + 1); - }); - - step("`>` lists the commands, and Escape closes", || { - app.press(Key::P, Modifiers::COMMAND | Modifiers::ALT); - opened(&mut app); - app.type_text(">"); - app.eventually("the commands", |tree| tree.count("palette-option") >= 5 && tree.has("palette-group")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the palette is closed", |tree| !tree.has("palette-input")); - }); - - app.quit(); -} diff --git a/e2e/tests/10_library_transfer.rs b/e2e/tests/10_library_transfer.rs deleted file mode 100644 index 16915ee8c..000000000 --- a/e2e/tests/10_library_transfer.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! Import, export and share from the File menu. Every operation reports, including when it -//! changed nothing; a sealed file opens only with its phrase; an export of nothing asks nothing -//! and leaves no file behind. -//! -//! Every dialog of the run answers the one path the scenario fixed. Nothing compares a word of -//! the reports: they are in the system's language, so what they name and the cards are read. - -use std::path::Path; - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; -const TITLE: &str = "Worth exporting"; -const FILE: &str = "library.devnotes"; -const PHRASE: &str = "an export passphrase"; -/// What an export before the archive looks like, from a version with a language unknown here; -/// its drawing carries a scene and no picture, as every export's. -const NEWER: &str = r#"{ - "version": 1, - "exportedAt": "2026-11-06T09:00:00Z", - "spaces": [{ "id": "elsewhere", "name": "Ailleurs" }], - "notes": [{ - "id": "written-by-a-newer-devnotes", - "spaceId": "elsewhere", - "title": "Ahead of this build", - "language": "from-the-future", - "content": "echo later", - "source": "", - "tags": [], - "pinned": false, - "createdAt": "2026-11-06T09:00:00Z", - "updatedAt": "2026-11-06T09:00:00Z", - "lifecycle": { "kind": "permanent" } - }, { - "id": "a-drawing-imported", - "spaceId": "elsewhere", - "title": "Imported sketch", - "kind": "drawing", - "language": "txt", - "content": "{\"version\":1,\"scene\":{\"objects\":[{\"type\":\"Rect\",\"left\":60,\"top\":45,\"width\":100,\"height\":50}]}}", - "source": "", - "tags": [], - "pinned": false, - "createdAt": "2026-11-06T09:00:00Z", - "updatedAt": "2026-11-06T09:00:00Z", - "lifecycle": { "kind": "permanent" } - }] -}"#; - -fn cards(app: &mut App, count: usize, what: &str) { - app.eventually(what, |tree| tree.count("note-card") == count); -} - -fn menu(app: &mut App, entry: &str) { - app.click("file-menu"); - app.click(&format!("file-option-{entry}")); -} - -/// The report of the last operation, left off the screen for the next one to be seen. -fn report(app: &mut App) -> String { - app.wait_for("status-toast"); - let said = app.tree().text("status-toast").unwrap_or_default(); - app.click("status-dismiss"); - app.eventually("the report is dismissed", |tree| !tree.has("status-toast")); - said -} - -fn write(app: &mut App, title: &str) { - app.click("new-note"); - app.fill("editor-title", title); - app.fill("editor-body", "echo hello"); - app.click("editor-close"); - app.eventually("the note is a card", |tree| !tree.has("editor-title")); -} - -/// The first card, purged: the second press of Delete writes, then the trash forgets it. -fn purge_first(app: &mut App) { - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::Delete, Modifiers::NONE); - app.wait_for("note-card-arming"); - app.press(Key::Delete, Modifiers::NONE); - app.click("undo-dismiss"); - app.click("trash-open"); - app.wait_for("trash-row"); - app.click("trash-purge"); - app.click("trash-purge"); - app.eventually("the trash is empty", |tree| tree.has("trash-empty-state")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the panel is closed", |tree| !tree.has("trash-close")); -} - -fn is_archive(file: &Path) -> bool { - std::fs::read(file).is_ok_and(|bytes| bytes.starts_with(b"PK\x03\x04")) -} - -/// The one file the library's key does not protect carries a key of its own. -fn sealed_file(app: &mut App, file: &Path) { - step("a sealed file does not show what it holds", || { - menu(app, "exportAll"); - app.fill("passphrase-prompt-field", PHRASE); - app.fill("passphrase-prompt-confirmation", PHRASE); - app.click("passphrase-prompt-submit"); - let said = report(app); - assert!(said.contains(FILE), "{said}"); - let bytes = std::fs::read(file).unwrap(); - let readable = bytes.windows(TITLE.len()).any(|at| at == TITLE.as_bytes()); - assert!(!readable, "the title is readable in the file"); - }); - - step("it opens with its phrase, and only with it", || { - menu(app, "import"); - app.fill("passphrase-prompt-field", "not the phrase"); - app.click("passphrase-prompt-submit"); - app.eventually("the prompt says the phrase is wrong", |tree| { - tree.text("passphrase-prompt-problem").is_some_and(|said| !said.is_empty()) - }); - app.eventually("the prompt is open again", |tree| { - tree.find("passphrase-prompt-field").is_some_and(|field| !field.is_disabled()) - }); - app.fill("passphrase-prompt-field", PHRASE); - app.click("passphrase-prompt-submit"); - report(app); - app.eventually("the prompt closed", |tree| !tree.has("passphrase-prompt")); - }); -} - -#[test] -fn library_transfer() { - let profile = tempfile::tempdir().unwrap(); - let directory = tempfile::tempdir().unwrap(); - let file = directory.path().join(FILE); - let mut app = App::launch_answering("10_library_transfer", profile.path(), &file); - app.create_library(); - cards(&mut app, CARDS, "the samples are drawn"); - write(&mut app, TITLE); - cards(&mut app, CARDS + 1, "the note is drawn"); - - step("the menu greys what has nothing to act on", || { - app.click("file-menu"); - app.wait_for("file-option-exportSelection"); - let tree = app.tree(); - assert!(tree.find("file-option-exportSelection").unwrap().is_disabled()); - assert!(tree.find("file-option-copyMarkdown").unwrap().is_disabled()); - assert!(!tree.find("file-option-exportAll").unwrap().is_disabled()); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the menu is closed", |tree| !tree.has("file-option-exportAll")); - }); - - step("an export in the clear writes an archive and names it", || { - menu(&mut app, "exportAll"); - app.wait_for("passphrase-prompt"); - app.capture("protect-prompt"); - app.click("passphrase-prompt-plain"); - let said = report(&mut app); - assert!(said.contains(FILE), "{said}"); - assert!(said.contains(&(CARDS + 1).to_string()), "{said}"); - assert!(is_archive(&file)); - }); - - step("importing what is there adds nothing, and says so", || { - menu(&mut app, "import"); - assert!(!report(&mut app).is_empty()); - cards(&mut app, CARDS + 1, "nothing came in"); - }); - - step("a note gone for good comes back from the file", || { - purge_first(&mut app); - cards(&mut app, CARDS, "the note is gone"); - menu(&mut app, "import"); - report(&mut app); - cards(&mut app, CARDS + 1, "the note is back"); - }); - - sealed_file(&mut app, &file); - - step("a file from a newer version comes in rather than failing", || { - std::fs::write(&file, NEWER).unwrap(); - menu(&mut app, "import"); - report(&mut app); - // In its own space: a list draws only what is in view, and the window's size is the - // machine's. - app.click_where("space-option", |node| node.label() == Some("Ailleurs")); - app.eventually("the note from the future is drawn", |tree| { - tree.texts("note-card-title").contains(&"Ahead of this build".to_owned()) - }); - app.eventually("the drawing imported shows its picture", |tree| { - tree.has("note-card-drawing") && !tree.has("note-card-drawing-empty") - }); - }); - - step("Escape gives a prompt up, and nothing is written", || { - std::fs::remove_file(&file).unwrap(); - menu(&mut app, "exportAll"); - app.wait_for("passphrase-prompt"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the prompt closed", |tree| !tree.has("passphrase-prompt")); - assert!(!file.exists()); - }); - - step("an empty space says so before any place is asked", || { - app.click("space-create-open"); - app.fill("space-create-input", "Rien dedans"); - app.press(Key::Enter, Modifiers::NONE); - cards(&mut app, 0, "the empty space is shown"); - menu(&mut app, "exportSpace"); - report(&mut app); - assert!(!app.has("passphrase-prompt")); - assert!(!file.exists()); - }); - - app.quit(); -} diff --git a/e2e/tests/10_scripts_and_runs.rs b/e2e/tests/10_scripts_and_runs.rs new file mode 100644 index 000000000..9b40e01b1 --- /dev/null +++ b/e2e/tests/10_scripts_and_runs.rs @@ -0,0 +1,164 @@ +//! Journey 10, « Scripts, tests and runs »: what a request's scripts do before and after it is sent, +//! what its tests say, what stops a send or waits for a yes, and a collection run as a whole. + +use e2e::{App, Area, Part, Script, step}; + +const COLLECTION: &str = "Shop"; +const THROWS: &str = "\nthrow new Error('no stock');"; +const TEST: &str = "test('found', () => { expect(res.status).toBe(200); });"; + +#[test] +fn scripts_and_runs() { + let mut app = App::open("10_scripts_and_runs"); + let api = app.serve_api(); + app.window().widen(); + app.window().go_to(Area::Http); + app.http().new_collection(COLLECTION); + + scripts_and_tests(&mut app, &api); + what_stops_a_send(&mut app); + a_run(&mut app, &api); + what_is_left(app); +} + +fn scripts_and_tests(app: &mut App, api: &str) { + step("a script before the send adds a header, and the console hears it", || { + app.http().new_request(COLLECTION, "Order"); + app.request().type_url(&format!("{api}/echo")); + app.request() + .type_script(Script::Before, "req.headers.set('X-Order', '42');\nconsole.log('order prepared');"); + app.request().send(); + app.response().expect_body("x-order: 42", "the header was sent"); + app.response().open_console(); + app.response().expect_console("order prepared", "the console heard the script"); + app.response().expect_console(&format!("GET {api}/echo"), "and the send"); + }); + + step("a script after the answer keeps a value of it, which the next request uses", || { + app.request() + .type_script(Script::After, "env.set('who', res.json().name);\nconsole.log('value kept');"); + app.response().clear_console(); + app.request().send_to(&format!("{api}/json")); + app.response().expect_console("value kept", "the console heard it"); + app.request().type_script(Script::After, ""); + app.request().send_to(&format!("{api}/echo?who={{{{who}}}}")); + app.response().expect_body("/echo?who=Ada", "the value was sent"); + }); + + step("a test reads the answer, and says what it expected and what it received", || { + app.request().type_script(Script::Tests, TEST); + app.request().send_to(&format!("{api}/json")); + app.response().go_to(Part::Tests); + app.response().expect_test_passed("found", "the test passed"); + app.request().send_to(&format!("{api}/missing")); + app.response().go_to(Part::Tests); + app.response() + .expect_test_failed("found", ("200", "404"), "the test failed on the status"); + app.capture("tests"); + }); +} + +fn what_stops_a_send(app: &mut App) { + step("a script that throws stops the send, and leads back to its line", || { + app.request().type_script(Script::Before, THROWS); + app.request().show_script(Script::Tests); + app.request().send(); + app.response().expect_stopped("no stock", "the stop is said, and where"); + app.capture("stopped"); + app.response().open_script(); + app.request().expect_script(THROWS, "its script is shown"); + }); + + step("a file a script asks to send waits for a yes", || { + let key = app.files().put_apart("id_ed25519", b"not a key"); + app.request().type_script( + Script::Before, + &format!("pm.request.body.update({{ mode: 'file', file: {{ src: '{key}' }} }});"), + ); + app.request().send(); + app.response() + .expect_file_asked("id_ed25519", "the file is named, nothing left"); + app.capture("file-asked"); + app.response().refuse_file(); + app.request().send(); + app.response().expect_file_asked("id_ed25519", "it is asked again"); + app.response().allow_file(); + app.response().expect_status("404 Not Found", "the yes let it leave"); + app.request().type_script(Script::Before, ""); + app.request().save(); + }); +} + +fn a_run(app: &mut App, api: &str) { + step("a collection of three requests, two of them with a test", || { + for (name, path) in [("Login", "/json"), ("Client", "/missing")] { + app.http().new_request(COLLECTION, name); + app.request().type_url(&format!("{api}{path}")); + app.request().type_script(Script::Tests, TEST); + app.request().save(); + } + app.sends().open(); + app.sends().erase_all(); + app.sends().leave(); + }); + + step("it runs twice over, one request left out by Space, what failed open", || { + app.runner().open(COLLECTION); + app.runner().set_iterations("2"); + app.runner().flip_request("Order"); + app.runner().run(); + app.runner().expect_results(2, (2, 2), "each iteration ran the two others"); + app.runner().expect_not_run("Order", "the one left out did not run"); + app.runner() + .expect_assertion("found", "404", "what failed is open on its assertion"); + app.capture("run"); + app.runner().show_failed(); + app.runner().expect_results(2, (0, 2), "the failed are shown alone"); + app.runner().show_all(); + }); + + step("a data file gives it an iteration a row", || { + app.files().put("clients.csv", b"customer\ncus_1\ncus_2\ncus_3\n"); + app.files().answer("clients.csv"); + app.runner().choose_data(); + app.runner().run(); + app.runner().expect_results(3, (3, 3), "it ran once a row"); + }); + + step("a run writes nothing in the history", || { + app.sends().open(); + app.sends().expect_none("nothing is listed"); + app.sends().leave(); + }); + + step("the order is arranged, and *Stop at the first failure* ends the run", || { + app.runner().open(COLLECTION); + app.runner() + .expect_order(&["Order", "Login", "Client"], "they are in the collection's order"); + app.runner().move_down("Login"); + app.runner() + .expect_order(&["Order", "Client", "Login"], "the order is arranged"); + app.runner().flip_request("Order"); + app.runner().flip_stop(); + app.runner().run(); + app.runner().expect_results(1, (0, 1), "the first failure ended the run"); + }); +} + +fn what_is_left(mut app: App) { + step("the order arranged is kept over a relaunch", || { + app.relaunch_and_unlock(); + app.runner().open(COLLECTION); + app.runner() + .expect_order(&["Order", "Client", "Login"], "the order is the one arranged"); + }); + + step("quitting with a request left changed asks first", || { + app.http().open("Login"); + app.request().add_to_url("/changed"); + app.http().ask_to_quit(); + app.http().cancel_leaving(); + app.http().ask_to_quit(); + app.http().save_and_quit(); + }); +} diff --git a/e2e/tests/11_attachments.rs b/e2e/tests/11_attachments.rs deleted file mode 100644 index c8da31c88..000000000 --- a/e2e/tests/11_attachments.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! Attachments: an empty strip that says so, a file chosen and kept under its name, an image shown -//! at once and grown in the lightbox, the card counting them, two files of one name, a removal -//! on the second click, a file over the limit refused, and the plain copies swept. The system's -//! dialog is the one step no driver reaches: the scenario answers it. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -const TITLE: &str = "Note with a file"; -const IMAGE: &str = r##""##; - -fn files(tree: &Tree) -> usize { - tree.count("attachment-open") -} - -fn open(app: &mut App) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(TITLE); - app.eventually("the note alone", |tree| tree.count("note-card") == 1); - app.click("note-card-open"); - app.wait_for("editor-title"); -} - -fn close(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); -} - -#[test] -fn attachments() { - let profile = tempfile::tempdir().unwrap(); - let folder = tempfile::tempdir().unwrap(); - let file = folder.path().join("diagram.svg"); - std::fs::write(&file, IMAGE).unwrap(); - let mut app = App::launch_answering("11_attachments", profile.path(), &file); - app.create_library(); - app.wait_for("note-card"); - - step("the strip says it is empty", || { - app.click("new-note"); - app.fill("editor-title", TITLE); - app.click("editor-body"); - app.type_text("step one"); - close(&mut app); - open(&mut app); - app.wait_for("attachment-empty"); - app.wait_for("attachment-add"); - }); - - step("a file is kept, and an image shown at once", || { - app.click("attachment-add"); - app.eventually("the file listed", |tree| files(tree) == 1); - app.wait_for("attachment-zoom"); - assert!(!app.has("attachment-empty")); - app.capture("attachment-strip"); - }); - - step("the lightbox grows it and Escape takes it away", || { - app.click("attachment-zoom"); - app.wait_for("lightbox-image"); - app.capture("lightbox"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the lightbox gone", |tree| !tree.has("lightbox-image")); - assert!(app.has("editor-title"), "only the lightbox went"); - }); - - step("the card counts it and a reopen lists it", || { - close(&mut app); - app.wait_for("note-card-clip"); - open(&mut app); - app.eventually("the file listed again", |tree| files(tree) == 1); - }); - - step("two files of one name are two records", || { - app.click("attachment-add"); - app.eventually("both listed", |tree| files(tree) == 2); - }); - - step("a file goes on the second click, and only then", || { - app.click_nth("attachment-remove", 0); - assert_eq!(app.tree().count("attachment-open"), 2); - app.click_nth("attachment-remove", 0); - app.eventually("one left", |tree| files(tree) == 1); - }); - - step("a file over the limit is refused and says so", || { - std::fs::write(&file, vec![b' '; 10 * 1024 * 1024 + 1]).unwrap(); - app.click("attachment-add"); - app.wait_for("error-banner"); - assert_eq!(app.tree().count("attachment-open"), 1); - }); - - let copies = profile.path().join("open"); - let leave_a_copy = || { - std::fs::create_dir_all(&copies).unwrap(); - std::fs::write(copies.join("left.txt"), "plain").unwrap(); - }; - leave_a_copy(); - app.quit(); - assert!(!copies.exists(), "swept at the exit"); - - leave_a_copy(); - let mut app = App::launch("11_attachments", profile.path()); - app.wait_for("vault-passphrase"); - assert!(!copies.exists(), "swept at the launch, before the unlock"); - app.quit(); -} diff --git a/e2e/tests/11_libraries_and_transfer.rs b/e2e/tests/11_libraries_and_transfer.rs new file mode 100644 index 000000000..aa9027902 --- /dev/null +++ b/e2e/tests/11_libraries_and_transfer.rs @@ -0,0 +1,210 @@ +//! Journey 11, « Several libraries, and moving notes between them »: a second library and its own +//! phrase, what a switch and a deletion ask, and the files notes leave and come in by. + +use e2e::{App, Area, Export, PASSPHRASE, step}; + +const FIRST: &str = "Personal"; +const SECOND: &str = "Office"; +const SECOND_PHRASE: &str = "another end-to-end passphrase"; +const FILE_PHRASE: &str = "a passphrase for a file"; +/// Only the first library holds it. +const SPACE: &str = "Travel"; +const FOLDER: &str = "Perf"; +const FILED: &str = "Slow query"; +const LOOSE: &str = "Nightly dump"; + +#[test] +fn libraries_and_transfer() { + let mut app = App::open("11_libraries_and_transfer"); + app.window().widen(); + + two_libraries(&mut app); + what_is_asked_first(&mut app); + leaving(&mut app); + coming_in(&mut app); + app.quit(); +} + +fn two_libraries(app: &mut App) { + step("a library alone is renamed, and cannot be deleted", || { + app.rail().new_space(SPACE); + app.libraries().open(); + app.libraries().expect_listed(1, "it is the only one"); + app.libraries().expect_open_one_kept("it offers no deletion"); + app.libraries().rename_the_open_one(FIRST); + app.capture("libraries"); + }); + + step("a second one is made, with its own phrase and its own samples, and renamed", || { + app.libraries().create("Work"); + app.gate().create_library(SECOND_PHRASE); + app.notes().expect_samples("it has its own samples"); + app.rail().expect_no_space(SPACE, "and nothing of the first"); + app.libraries().open(); + app.libraries().expect_listed(2, "both are listed"); + app.libraries().rename_the_open_one(SECOND); + app.libraries().close(); + }); + + step("the gate lists both, each opened by its own phrase", || { + app.relaunch(); + app.gate().expect_library(SECOND, "it asks for the last one open"); + app.gate().choose_library(FIRST); + app.gate().try_phrase(SECOND_PHRASE); + app.gate().expect_wrong_phrase("the other's phrase is refused"); + app.gate().choose_library(SECOND); + app.gate().unlock(SECOND_PHRASE); + app.rail().expect_no_space(SPACE, "the second is open"); + }); +} + +fn what_is_asked_first(app: &mut App) { + step("a switch asks before it loses a request left changed", || { + app.window().go_to(Area::Http); + app.http().new_draft(); + app.window().go_to(Area::Notes); + app.libraries().open(); + app.libraries().switch_to(FIRST); + app.http().expect_asked_about_changes(1, "the request is named"); + app.http().cancel_leaving(); + app.libraries().switch_to(FIRST); + app.http().leave_without_saving(); + app.gate().expect_library(FIRST, "the gate asks for the other library"); + app.gate().unlock(PASSPHRASE); + app.rail().expect_one_space(SPACE, "its own spaces are there"); + }); + + step("a deletion is named before it runs, and the open library has none", || { + app.libraries().open(); + app.libraries().create("Old"); + app.gate().create_library(SECOND_PHRASE); + app.libraries().open(); + app.libraries().expect_open_one_kept("the open one offers no deletion"); + app.libraries().switch_to(FIRST); + app.gate().unlock(PASSPHRASE); + app.libraries().open(); + app.libraries().ask_deletion("Old"); + app.libraries().cancel_deletion(); + app.libraries().expect_listed(3, "nothing went"); + app.libraries().ask_deletion("Old"); + app.libraries().confirm_deletion(); + app.libraries().close(); + }); +} + +fn leaving(app: &mut App) { + step("a space with a folder, its note, a note outside and a folder of nothing", || { + app.rail().show_space(SPACE); + app.rail().new_folder("Unused"); + app.rail().new_folder(FOLDER); + app.notes().write_snippet(LOOSE, "pg_dump shop"); + app.rail().open_folder(FOLDER); + app.notes().write_snippet(FILED, "EXPLAIN SELECT 1;"); + app.notes().leave_folder(); + }); + + step("everything is exported, under a phrase and in the clear", || { + app.transfer().expect_selection_waiting("a selection's entries wait for one"); + app.files().answer("sealed.devnotes"); + app.transfer().export_sealed(Export::Everything, FILE_PHRASE); + app.transfer().expect_reported("sealed.devnotes", "the report names the file"); + app.files() + .expect("sealed.devnotes", "nothing is read in it", |bytes| !holds(bytes, FILED)); + app.files().answer("everything.devnotes"); + app.transfer().export(Export::Everything); + app.transfer() + .expect_reported("everything.devnotes", "the report names the file"); + app.files() + .expect("everything.devnotes", "it is an archive", |bytes| bytes.starts_with(b"PK")); + }); + + step("a space is exported under a phrase, and a selection in the clear", || { + app.files().answer("space.devnotes"); + app.transfer().export_sealed(Export::Space, FILE_PHRASE); + app.transfer().expect_reported("space.devnotes", "the report names the file"); + app.selection().tick(LOOSE); + app.files().answer("selection.devnotes"); + app.transfer().export(Export::Selection); + app.transfer() + .expect_reported("selection.devnotes", "the report names the file"); + }); + + step("*Copy selection as Markdown* copies the note with all that says it", || { + app.transfer().copy_selection_as_markdown(); + app.clipboard().expect_saying(LOOSE, "its title"); + app.clipboard().expect_saying(SPACE, "its space"); + app.clipboard().expect_saying("pg_dump shop", "and its content"); + app.selection().clear(); + app.notes().clear_toasts(); + }); + + step("an export given up, or of nothing, asks nothing more and leaves no file", || { + app.files().answer("none.devnotes"); + app.transfer().ask(Export::Everything); + app.transfer().give_up(); + app.files().expect_none("none.devnotes", "nothing was written"); + app.rail().new_space("Empty"); + app.transfer().ask(Export::Space); + app.transfer().expect_reported("", "an empty space is said to be"); + app.transfer().expect_nothing_asked("no phrase is asked"); + app.files().expect_none("none.devnotes", "nothing was written"); + }); +} + +fn coming_in(app: &mut App) { + step("in the other library, a protected file opens with its phrase alone, arranged as it was", || { + app.libraries().open(); + app.libraries().switch_to(SECOND); + app.gate().unlock(SECOND_PHRASE); + app.files().answer("space.devnotes"); + app.transfer().import(); + app.transfer().try_phrase("not the file's phrase"); + app.transfer().expect_wrong_phrase("another phrase is refused"); + app.transfer().try_phrase(FILE_PHRASE); + app.transfer().expect_reported("2", "the two notes are said to have come in"); + app.rail().show_space(SPACE); + app.notes().expect_cards(2, "they are in their space"); + app.rail().expect_no_folder("Unused", "a folder of nothing did not come"); + app.rail().open_folder(FOLDER); + app.notes().expect_cards(1, "the folder holds its note"); + app.notes().expect_card(FILED, "the one it held"); + app.capture("imported"); + }); + + step("the same file again adds nothing, and says so", || { + app.transfer().import(); + app.transfer().try_phrase(FILE_PHRASE); + app.transfer().expect_reported("", "the import reports"); + app.rail().show_space(SPACE); + app.notes().expect_cards(2, "nothing came in"); + app.rail().expect_folders_named(FOLDER, 1, "nor a second folder"); + }); + + step("everything comes in, spaces merged by name", || { + app.files().answer("everything.devnotes"); + app.transfer().import(); + app.transfer().expect_reported("", "the import reports"); + app.rail().expect_one_space(SPACE, "the space is the same one"); + app.files().answer("selection.devnotes"); + app.transfer().import(); + app.transfer().expect_reported("", "the selection reports too"); + app.rail().show_space(SPACE); + app.notes().expect_cards(2, "its notes were there already"); + }); + + step("a note gone for good comes back from the file", || { + app.notes().delete_from_the_keyboard(LOOSE); + app.notes().dismiss_undo(); + app.notes().clear_search(); + app.trash().open(); + app.trash().empty(); + app.trash().close(); + app.transfer().import(); + app.transfer().expect_reported("", "the import reports"); + app.notes().expect_card(LOOSE, "the note is back"); + }); +} + +fn holds(bytes: &[u8], words: &str) -> bool { + bytes.windows(words.len()).any(|window| window == words.as_bytes()) +} diff --git a/e2e/tests/12_looking_after_the_library.rs b/e2e/tests/12_looking_after_the_library.rs new file mode 100644 index 000000000..8a90c8c95 --- /dev/null +++ b/e2e/tests/12_looking_after_the_library.rs @@ -0,0 +1,93 @@ +//! Journey 12, « Looking after the library »: its phrase changed, a copy put back, a damaged file +//! set aside and a forgotten phrase. It ends on a profile with no library. + +use e2e::{App, PASSPHRASE, Sample, step}; + +const NEXT: &str = "a second end-to-end passphrase"; +const LATER: &str = "Written after the copy"; + +#[test] +fn looking_after_the_library() { + let mut app = App::open("12_looking_after_the_library"); + app.window().widen(); + + step("a copy is taken at the first launch of the day, and no other", || { + app.relaunch_and_unlock(); + app.window().widen(); + app.security().open_copies(); + app.security().expect_copies(1, "the launch's copy is listed"); + app.capture("copies"); + app.prefs().close(); + app.relaunch_and_unlock(); + app.window().widen(); + app.security().open_copies(); + app.security().expect_copies(1, "a second launch took no other"); + app.prefs().close(); + }); + + step("the passphrase is changed, and the session carries on", || { + app.security().ask_change(); + app.security().try_change("not the current one", NEXT); + app.security().expect_refused("a wrong phrase changes nothing"); + app.security().try_change(PASSPHRASE, NEXT); + app.security().expect_changed("the phrase is changed"); + }); + + step("after a quit, the old phrase is refused and the new one opens", || { + app.relaunch(); + app.gate().try_phrase(PASSPHRASE); + app.gate().expect_wrong_phrase("the old phrase is refused"); + app.gate().unlock(NEXT); + app.window().widen(); + }); + + step("the copy taken before the change is put back, what it replaces set aside", || { + let gone = app.notes().title_of(Sample::SnippetToFormat); + app.notes().delete_from_the_keyboard(&gone); + app.notes().dismiss_undo(); + app.notes().clear_search(); + app.trash().open(); + app.trash().empty(); + app.trash().close(); + app.notes().write_snippet(LATER, "echo later"); + app.security().open_copies(); + app.security().ask_restore(); + app.capture("restore"); + app.security().cancel_restore(); + app.security().ask_restore(); + app.security().confirm_restore(); + app.gate() + .expect_place_told("replaced", "the place of the library it replaced is told"); + app.capture("restored"); + }); + + step("the copy opens with the new phrase, the library as it was", || { + app.gate().unlock(NEXT); + app.window().widen(); + app.notes().expect_samples("the note erased is back, what came after is gone"); + }); + + step("a damaged database is said, set aside, and the phrase unchanged", || { + app.relaunch_damaged(); + app.gate().try_phrase(NEXT); + app.gate().expect_damaged("the gate says so, and starts nothing on it"); + app.capture("damaged"); + app.gate().set_aside(); + app.gate().expect_place_told("damaged", "its place is told"); + app.gate().unlock(NEXT); + app.notes().expect_samples("a fresh library opens"); + }); + + step("a forgotten phrase archives the library, and the gate asks for a new one", || { + app.relaunch(); + app.gate().forget(); + app.capture("forgotten"); + app.gate().keep_trying(); + app.gate().forget(); + app.gate().archive(); + app.gate().expect_new_phrase_asked("a new library would begin"); + app.gate().expect_place_told("archived", "the place of the old one is told"); + }); + + app.quit(); +} diff --git a/e2e/tests/12_preferences.rs b/e2e/tests/12_preferences.rs deleted file mode 100644 index 767ca1499..000000000 --- a/e2e/tests/12_preferences.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! A preference applies on a button; only the theme and the density show while chosen. The -//! language is established here, never assumed: `system` is the machine's. - -use e2e::{App, step}; -use egui::accesskit::{Node, Rect}; -use egui::{Key, Modifiers}; - -const THEME_LIGHT: &str = "setting-theme-2"; -const THEME_DARK: &str = "setting-theme-1"; -const COMPACT: &str = "setting-density-1"; -const COMFORTABLE: &str = "setting-density-0"; -const FRENCH: &str = "setting-locale-1"; -const ENGLISH: &str = "setting-locale-2"; -const NOTE_KIND_NOTE: &str = "setting-note-kind-0"; -const NOTE_KIND_SNIPPET: &str = "setting-note-kind-1"; -const FIVE_LINES: &str = "setting-preview-lines-2"; - -fn open(app: &mut App) { - app.click("file-menu"); - app.click("file-preferences"); - app.wait_for("settings-dialog"); -} - -fn closed(app: &mut App) { - app.eventually("the panel is closed", |tree| !tree.has("settings-dialog")); -} - -fn locale(app: &mut App, choice: &str) { - app.click("setting-locale"); - app.click(choice); -} - -/// What the theme control offers, which names the theme it would switch to: it reads the window's. -fn theme_word(app: &mut App) -> String { - app.tree().text("theme-toggle").unwrap_or_default() -} - -/// A card's height, in the window's own units. -fn card_height(app: &mut App) -> f64 { - let tree = app.tree(); - tree.find("note-card") - .and_then(Node::bounds) - .map_or(0.0, |card| card.y1 - card.y0) -} - -/// Taller by the ratio of a 160 px card to a 140 px one: the window's scale aside. -fn one_line_taller(card: f64, four: f64) -> bool { - (card / four - 160.0 / 140.0).abs() < 0.02 -} - -fn still_five_lines(app: &mut App, four: f64) { - app.wait_for("note-card"); - let five = card_height(app); - assert!(one_line_taller(five, four), "{five} for {four}"); -} - -fn five_lines(app: &mut App, four: f64) { - open(app); - app.click(FIVE_LINES); - app.click("settings-apply"); - app.click("settings-close"); - closed(app); - app.eventually("the cards grew by a line", |tree| { - tree.find("note-card") - .and_then(Node::bounds) - .is_some_and(|card: Rect| one_line_taller(card.y1 - card.y0, four)) - }); -} - -fn file_word(app: &mut App) -> String { - app.tree().text("file-menu").unwrap_or_default() -} - -#[test] -fn preferences() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("12_preferences", profile.path()); - app.create_library(); - - step("the theme shows as it is chosen, and Cancel takes it back", || { - open(&mut app); - app.capture("preferences"); - app.click(THEME_DARK); - app.click("settings-apply"); - let dark = theme_word(&mut app); - - app.click(THEME_LIGHT); - app.eventually("the window previews the light theme", |tree| { - tree.text("theme-toggle").is_some_and(|word| word != dark) - }); - app.click("settings-cancel"); - closed(&mut app); - app.eventually("the theme is back", |tree| { - tree.text("theme-toggle").as_deref() == Some(dark.as_str()) - }); - }); - - step("the language waits for the button", || { - open(&mut app); - locale(&mut app, FRENCH); - app.click("settings-apply"); - app.eventually("the window speaks French", |tree| { - tree.text("file-menu").as_deref() == Some("Fichier") - }); - - locale(&mut app, ENGLISH); - assert_eq!(file_word(&mut app), "Fichier", "nothing before the button"); - app.click("settings-apply"); - app.eventually("the window speaks English", |tree| tree.text("file-menu").as_deref() == Some("File")); - app.click("settings-close"); - closed(&mut app); - }); - - step("Escape says what is waiting instead of closing", || { - open(&mut app); - app.click(COMPACT); - app.press(Key::Escape, Modifiers::NONE); - app.wait_for("settings-unapplied"); - assert!(app.has("settings-dialog")); - app.click("settings-discard"); - closed(&mut app); - - open(&mut app); - app.click(COMPACT); - app.press(Key::Escape, Modifiers::NONE); - app.click("settings-apply-close"); - closed(&mut app); - }); - - step("Escape with nothing waiting just closes", || { - open(&mut app); - app.press(Key::Escape, Modifiers::NONE); - closed(&mut app); - }); - - step("« New note » opens the kind the preference says", || { - open(&mut app); - app.click(NOTE_KIND_NOTE); - app.click("settings-close"); - closed(&mut app); - app.click("new-note"); - app.wait_for("editor-rich"); - assert!(!app.has("editor-body")); - app.click("editor-close"); - app.eventually("the editor closed", |tree| !tree.has("editor-rich")); - - open(&mut app); - app.click(NOTE_KIND_SNIPPET); - app.click("settings-close"); - closed(&mut app); - app.click("new-note"); - app.wait_for("editor-body"); - app.click("editor-close"); - app.eventually("the editor closed", |tree| !tree.has("editor-body")); - }); - - let four = card_height(&mut app); - step("five preview lines make every card 160 px rather than 140", || five_lines(&mut app, four)); - - let theme = theme_word(&mut app); - let mut app = app.relaunch(); - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - - step("what was applied is what the next launch opens with", || { - assert_eq!(file_word(&mut app), "File"); - assert_eq!(theme_word(&mut app), theme); - still_five_lines(&mut app, four); - open(&mut app); - app.click(COMFORTABLE); - app.click("settings-cancel"); - closed(&mut app); - }); - - app.quit(); -} diff --git a/e2e/tests/13_making_it_mine.rs b/e2e/tests/13_making_it_mine.rs new file mode 100644 index 000000000..4196a4830 --- /dev/null +++ b/e2e/tests/13_making_it_mine.rs @@ -0,0 +1,313 @@ +//! Journey 13, « Making it mine »: what is chosen in the preferences and seen where it acts, the +//! keys, the areas, the window, and a new version offered. + +use e2e::{ + App, Area, CardKey, DefaultKind, Density, Indent, Key, Kind, Language, Page, Sample, Shortcut, Switch, + Theme, step, +}; + +#[test] +fn making_it_mine() { + let mut app = App::open_before_an_update("13_making_it_mine"); + + the_look(&mut app); + where_they_act(&mut app); + a_global_variable(&mut app); + the_keys(&mut app); + the_areas(&mut app); + the_window(&mut app); + what_the_about_menu_says(&mut app); + + step("*File → Quit* asks for a second click, and ends DevNotes", || { + app.quit_from_the_menu(); + }); +} + +fn the_look(app: &mut App) { + let apart = app.notes().cards_apart(); + + step("the theme and the density show while chosen, and Cancel takes them back", || { + app.prefs().open(); + app.prefs().choose_theme(Theme::Dark); + app.prefs().apply(); + app.prefs().expect_stored("theme", "dark", "what was applied is on the disk"); + let dark = app.window().theme_offered(); + app.prefs().choose_theme(Theme::Light); + app.prefs().choose_density(Density::Compact); + app.window().expect_theme_changed(&dark, "the window previews the light theme"); + app.notes().expect_cards_closer(apart, "the cards preview the density"); + app.prefs() + .expect_stored("theme", "dark", "nothing is written before « Apply »"); + app.prefs().cancel(); + app.window().expect_theme(&dark, "the dark theme is back"); + app.notes().expect_cards_apart(apart, "the cards are as far apart as before"); + }); + + step("« Apply » keeps them, one text a setting on the disk", || { + app.prefs().open(); + app.prefs().choose_density(Density::Compact); + app.prefs().apply(); + app.prefs().expect_stored("density", "compact", "the density is on the disk"); + app.prefs().expect_stored_as_texts("the file holds one text per setting"); + app.capture("preferences"); + app.prefs().close(); + app.notes().expect_cards_closer(apart, "the cards stand closer"); + }); + + step("the language is switched by « Apply »", || { + app.prefs().open(); + app.prefs().choose_language(Language::French); + app.prefs().apply(); + app.window().expect_file_menu("Fichier", "the window speaks French"); + app.prefs().choose_language(Language::English); + app.prefs().apply(); + app.window().expect_file_menu("File", "the window speaks English"); + app.prefs().expect_stored("locale", "en", "the language is on the disk"); + app.prefs().close(); + }); + + step("the title bar switches the theme in one click", || { + let dark = app.window().theme_offered(); + app.window().switch_theme(); + app.window().expect_theme_changed(&dark, "the light theme is on"); + app.prefs().expect_stored("theme", "light", "it is kept"); + }); +} + +fn where_they_act(app: &mut App) { + step("« New note » makes the kind chosen", || { + app.prefs().change(|prefs| prefs.choose_default_kind(DefaultKind::Note)); + app.notes().new_note(); + app.editor().expect_note_open("a Note is open"); + app.editor().close(); + app.prefs().change(|prefs| prefs.choose_default_kind(DefaultKind::Snippet)); + app.notes().new_note(); + app.editor().expect_code_open("a snippet is open"); + app.editor().close(); + }); + + step("a card previews as many lines as chosen", || { + let four = app.notes().card_height(); + app.prefs().change(|prefs| prefs.choose_preview_lines(5)); + app.notes().expect_one_line_taller(four, "the cards grew by a line"); + }); + + step("Tab writes what was chosen", || { + app.prefs().change(|prefs| prefs.choose_indent(Indent::FourSpaces)); + app.notes().new_note(); + app.editor().type_code("indented"); + app.editor().go_to_start(); + app.press(Shortcut::Tab); + app.editor().expect_code(" indented", "four spaces stand before the code"); + app.editor().close(); + }); + + step("a long line is wrapped, or goes on, as chosen", || { + let line = "echo ".repeat(60); + app.notes().new_note(); + app.editor().type_code(&line); + app.editor().go_to_start(); + app.editor().expect_line_unwrapped("the line goes on past the edge"); + app.editor().close(); + app.prefs().change(|prefs| prefs.flip(Switch::WrapLines)); + app.notes().new_note(); + app.editor().type_code(&line); + app.editor().go_to_start(); + app.editor().expect_line_wrapped("the line is laid out over several rows"); + app.editor().close(); + }); + + step("a calculation has the decimals chosen", || { + app.prefs().change(|prefs| prefs.choose_decimals(2)); + app.notes().new_of_kind(Kind::Calculation); + app.editor().type_code("10 / 3"); + app.calc().expect_results(&["333"], "the result has two decimals"); + app.editor().close(); + }); + + step("a copy is acknowledged, or not, as chosen", || { + app.notes().copy(Sample::SnippetToFormat); + app.notes().expect_acknowledged("a toast says the copy was done"); + app.prefs().change(|prefs| prefs.flip(Switch::CopyAcknowledged)); + app.notes().copy(Sample::ApiResponse); + app.clipboard().expect_saying("billing", "the second one is copied"); + app.notes().expect_no_acknowledgement("no toast this time"); + }); +} + +fn a_global_variable(app: &mut App) { + step("a global variable is offered to the fields of its name", || { + app.prefs().open(); + app.prefs().go_to(Page::Variables); + app.prefs().add_variable("host", "db.global"); + app.prefs().close(); + app.notes().write_snippet("Ping", "ping {{host}}"); + app.notes().copy_filled("Ping"); + app.fields().copy(); + app.clipboard() + .expect("ping db.global", "the variable fills the field left as it was"); + }); + + step("what is typed on the note comes first", || { + app.notes().copy_filled("Ping"); + app.fields().type_value(0, "db.mine"); + app.fields().copy(); + app.clipboard().expect("ping db.mine", "the value typed is the one copied"); + }); +} + +fn the_keys(app: &mut App) { + step("a key another action holds is flagged", || { + app.prefs().open(); + app.prefs().go_to(Page::Shortcuts); + app.prefs().take_key(CardKey::Check, Key::P); + app.prefs() + .expect_key_flagged(CardKey::Check, "the panel says the key is taken"); + }); + + step("a free key is taken, and the cards answer to it", || { + app.prefs().take_key(CardKey::Check, Key::J); + app.prefs().expect_key(CardKey::Check, "J", "the panel shows the new key"); + app.prefs().close(); + app.notes().go_to_first_card(); + app.press(Shortcut::CardKey(Key::J)); + app.selection().expect(1, "the first card is selected"); + app.press(Shortcut::Escape); + }); + + step("« Reset » goes back to the first key", || { + app.prefs().open(); + app.prefs().go_to(Page::Shortcuts); + app.prefs().reset_key(CardKey::Check); + app.prefs() + .expect_key(CardKey::Check, "X", "the panel shows the first key again"); + app.prefs().close(); + }); + + step("the areas' keys are read by their place, whatever is printed on them", || { + app.press_on_another_layout(Shortcut::ToolsArea); + app.window().expect_area(Area::Tools, "the tools are on the screen"); + app.press_on_another_layout(Shortcut::NotesArea); + app.window().expect_area(Area::Notes, "the notes are on the screen"); + }); +} + +fn the_areas(app: &mut App) { + step("each area is left as it is and found again, by its key", || { + app.notes().search("zz nothing is called this"); + app.notes().expect_nothing_found("nothing answers the search"); + app.press(Shortcut::ToolsArea); + app.tools().open("case"); + app.press(Shortcut::HttpArea); + app.http().new_draft(); + app.press(Shortcut::NotesArea); + app.notes().expect_nothing_found("the search is as it was"); + app.press(Shortcut::ToolsArea); + app.tools().expect_tool_open("the tool is as it was"); + app.press(Shortcut::HttpArea); + app.http().expect_tabs(1, "the draft is as it was"); + app.http().close_last_tab_discarding(); + }); + + step("the switch of the areas leads there too", || { + app.window().go_to(Area::Notes); + app.window().expect_area(Area::Notes, "the notes are on the screen"); + app.notes().clear_search(); + app.window().go_to(Area::Http); + app.window().expect_area(Area::Http, "the HTTP area is on the screen"); + app.window().go_to(Area::Tools); + app.window().expect_area(Area::Tools, "the tools are on the screen"); + }); + + step("the side rail is put away in every area at once, and taken back", || { + app.press(Shortcut::SideRail); + app.window().expect_rail_away("the areas' switch went up to the title bar"); + app.press(Shortcut::NotesArea); + app.window().expect_rail_away("the rail is away in the notes too"); + app.press(Shortcut::SideRail); + app.window().expect_rail("the rail is back"); + app.press(Shortcut::ToolsArea); + app.window().expect_rail("it is back in the tools too"); + }); + + step("the window reopens on the area it was left in, as it was set", || { + app.relaunch_and_unlock(); + app.window().expect_area(Area::Tools, "the tools are on the screen"); + app.window().expect_file_menu("File", "the window still speaks English"); + app.window().go_to(Area::Notes); + }); +} + +/// macOS keeps its own three buttons: the steps that press DevNotes' own say what it shows instead. +fn the_window(app: &mut App) { + if cfg!(target_os = "macos") { + step("the window wears the system's own buttons", || { + app.window().expect_system_buttons("DevNotes draws none of its own"); + }); + return; + } + let maximize = app.window().maximize_offered(); + + step("maximised by its control, the window is found so at the next launch", || { + app.window().maximize_or_restore(); + app.window().expect_maximized(&maximize, "the window is maximised"); + app.relaunch_and_unlock(); + app.window().expect_maximized(&maximize, "the window is still maximised"); + }); + + step("a double click on the title bar restores it, and it is found so", || { + app.window().double_click_title_bar(); + app.window().expect_restored(&maximize, "the window is restored"); + app.relaunch_and_unlock(); + app.window().expect_restored(&maximize, "the window is still restored"); + }); + + step("minimised, it goes out of sight, and a new launch brings it back", || { + app.window().minimize(); + app.window().start_again(); + app.window().expect_back("the window went out of sight and is back"); + }); + + step("closed, with « Close to tray » off, it ends DevNotes", || { + app.prefs().change(|prefs| prefs.flip(Switch::CloseToTray)); + app.window().close_for_good(); + app.start_after_the_end(); + }); +} + +fn what_the_about_menu_says(app: &mut App) { + step("the version, the shortcuts and the changelog are read from the menu", || { + app.help().open_about(); + app.help().expect_version("the version is said"); + app.help().close(); + app.help().open_shortcuts(); + app.help().expect_shortcuts("the shortcuts are listed, group by group"); + app.help().close(); + app.help().open_whats_new(); + app.help().expect_changelog("the changelog is read, release by release"); + app.help().close(); + }); + + step("a new version is offered, and « Later » closes the offer", || { + app.help().expect_update_known("the menu says a version waits"); + app.help().check_for_updates(); + app.help().expect_update_offered("the version is offered with its notes"); + app.capture("update"); + app.help().update_later(); + }); + + step("« Do not offer this version again » silences it over a relaunch", || { + app.help().check_for_updates(); + app.help().skip_update(); + app.relaunch(); + app.gate() + .expect_no_update("the gate says nothing of it, once the check has answered"); + app.gate().unlock(e2e::PASSPHRASE); + }); + + step("asked from the menu, it is found again", || { + app.help().check_for_updates(); + app.help().expect_update_offered("the version is offered again"); + app.help().update_later(); + }); +} diff --git a/e2e/tests/13_multiple_selection.rs b/e2e/tests/13_multiple_selection.rs deleted file mode 100644 index 9aefc9dbb..000000000 --- a/e2e/tests/13_multiple_selection.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! Several notes at once: ticked from the keyboard, tagged and deleted together, and only them. -//! What is searched is a tag the scenario gives, which no translation touches. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; - -fn tick_two(app: &mut App) { - for key in [Key::X, Key::ArrowRight, Key::X] { - app.press(key, Modifiers::NONE); - } - app.eventually("two cards are ticked", |tree| { - tree.text("selection-count").is_some_and(|said| said.contains('2')) - }); -} - -/// Where each card's box is: one per card, in the tree's order. -fn boxes(tree: &Tree) -> Vec<(f64, f64)> { - tree.all("note-card-check") - .iter() - .filter_map(|node| node.bounds()) - .map(|bounds| (bounds.x0, bounds.y0)) - .collect() -} - -/// A box ticked by the pointer, and every card's box where it was before. -fn ticked_by_its_box(app: &mut App) { - let before = boxes(&app.tree()); - assert_eq!(before.len(), CARDS, "every card shows its box"); - app.click_nth("note-card-check", 1); - app.wait_for("selection-count"); - assert_eq!(boxes(&app.tree()), before, "no box moved"); - app.click_nth("note-card-check", 1); - app.eventually("the bar is gone", |tree| !tree.has("selection-count")); -} - -#[test] -fn multiple_selection() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("13_multiple_selection", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); - - step("a card is ticked by its box, which stays put", || { - ticked_by_its_box(&mut app); - }); - - step("no bar until a card is ticked, then it counts them", || { - assert!(!app.has("selection-count")); - app.press(Key::ArrowDown, Modifiers::NONE); - tick_two(&mut app); - app.capture("selection-bar"); - }); - - step("a tag reaches every ticked note, and only those", || { - app.fill("selection-tag", "batchtag"); - app.press(Key::Enter, Modifiers::NONE); - // While the bar offers the tagging back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| !tree.has("selection-count")); - app.click("search-input"); - app.type_text("batchtag"); - app.eventually("the two tagged notes are found", |tree| tree.count("note-card") == 2); - }); - - step("deleting the selection takes two clicks", || { - app.press(Key::ArrowDown, Modifiers::NONE); - tick_two(&mut app); - app.click("selection-delete"); - assert_eq!(app.tree().count("note-card"), 2); - app.click("selection-delete"); - app.eventually("both are in the trash, and the bar is gone", |tree| { - tree.has("canvas-no-results") && !tree.has("selection-count") - }); - app.click("search-clear"); - app.eventually("the others are untouched", |tree| tree.count("note-card") == CARDS - 2); - }); - - app.quit(); -} diff --git a/e2e/tests/14_tag_manager.rs b/e2e/tests/14_tag_manager.rs deleted file mode 100644 index ed11b8b3d..000000000 --- a/e2e/tests/14_tag_manager.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! The library's tags managed from the tag rail: a ticked tag's name filled in the field, renamed, -//! merged onto an existing tag, corrected in case alone, deleted — each said before it runs. The tags are the scenario's own, given -//! from the selection bar: the samples' are in the system's language. - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; - -/// The cards at `positions` ticked from their boxes, then given `tag` from the selection bar. -fn tag(app: &mut App, positions: &[usize], tag: &str) { - for at in positions { - app.click_nth("note-card-check", *at); - } - app.eventually("the cards are ticked", |tree| { - tree.text("selection-count") - .is_some_and(|said| said.contains(&positions.len().to_string())) - }); - app.fill("selection-tag", tag); - app.press(Key::Enter, Modifiers::NONE); - app.click("undo-dismiss"); - app.click("selection-clear"); - app.eventually("the selection is let go", |tree| !tree.has("selection-count")); -} - -fn listed(tree: &e2e::Tree, tag: &str) -> bool { - let name = format!("#{tag}"); - tree.texts("tag-item").contains(&name) -} - -fn tick(app: &mut App, tag: &str) { - let name = format!("#{tag}"); - app.click_where("tag-item", |node| node.label() == Some(name.as_str())); -} - -fn target(tree: &e2e::Tree) -> String { - let field = tree.find("tag-target"); - field.and_then(|node| node.value()).unwrap_or_default().to_owned() -} - -/// The ticked tags under `into`, typed over what the field holds, proposed then confirmed. -fn rename(app: &mut App, into: &str) { - app.fill("tag-target", ""); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(into); - app.click("tag-apply"); - app.click("tag-confirm-apply"); -} - -#[test] -fn tag_manager() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("14_tag_manager", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); - tag(&mut app, &[0, 1], "staging"); - tag(&mut app, &[0], "urgent"); - tag(&mut app, &[2], "preprod"); - - step("the tags' menu opens the manager, which lists every tag", || { - app.click("facets-toggle"); - app.click("facet-menu-tag"); - app.click("tag-manage"); - app.eventually("the scenario's tags are listed", |tree| { - ["staging", "urgent", "preprod"].iter().all(|tag| listed(tree, tag)) - }); - assert!( - app.tree().find("tag-apply").is_some_and(egui::accesskit::Node::is_disabled), - "nothing ticked, nothing to apply" - ); - }); - - step("a rename says what it touches, and cancelling writes nothing", || { - tick(&mut app, "staging"); - app.eventually("its name fills the field, which has the focus", |tree| { - target(tree) == "staging" && tree.focused().starts_with("tag-target") - }); - assert!( - app.tree().find("tag-apply").is_some_and(egui::accesskit::Node::is_disabled), - "its own name changes nothing" - ); - assert!(app.tree().has("tag-target-reason")); - // Selected: what is typed replaces it. - app.type_text("recette"); - app.eventually("edited in place", |tree| target(tree) == "recette"); - app.click("tag-apply"); - app.eventually("two notes carry it, and the sentence says so", |tree| { - tree.text("tag-confirm-text").is_some_and(|said| said.contains('2')) - }); - app.capture("tag-confirm"); - app.click("tag-confirm-cancel"); - assert!(listed(&app.tree(), "staging")); - }); - - step("confirmed, the rename reaches every note", || { - app.click("tag-apply"); - app.click("tag-confirm-apply"); - app.eventually("recette replaces staging", |tree| { - listed(tree, "recette") && !listed(tree, "staging") - }); - }); - - step("onto an existing tag it merges", || { - tick(&mut app, "preprod"); - rename(&mut app, "recette"); - app.eventually("preprod is gone into recette", |tree| { - listed(tree, "recette") && !listed(tree, "preprod") - }); - }); - - step("a change of case alone is written", || { - tick(&mut app, "recette"); - rename(&mut app, "Recette"); - app.eventually("the new spelling", |tree| listed(tree, "Recette")); - }); - - step("a deleted tag leaves its notes", || { - tick(&mut app, "urgent"); - app.click("tag-delete"); - app.click("tag-confirm-apply"); - app.eventually("urgent is gone", |tree| !listed(tree, "urgent")); - app.click("tag-manager-close"); - app.eventually("the manager is closed", |tree| !tree.has("tag-manager-close")); - // The band takes room from the cards: how many are drawn under it depends on the window. - app.click("facets-toggle"); - app.eventually("every note stays", |tree| tree.count("note-card") == CARDS); - }); - - app.quit(); -} diff --git a/e2e/tests/15_preferences_on_disk.rs b/e2e/tests/15_preferences_on_disk.rs deleted file mode 100644 index 5de9343a5..000000000 --- a/e2e/tests/15_preferences_on_disk.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! The file itself, read from outside the application: one key per setting, each a string, and -//! nothing written before the draft is applied. - -use std::path::Path; - -use e2e::{App, step}; -use serde_json::Value; - -const THEME_DARK: &str = "setting-theme-1"; -const THEME_LIGHT: &str = "setting-theme-2"; - -fn stored(profile: &Path) -> serde_json::Map { - let Ok(text) = std::fs::read_to_string(profile.join("preferences.json")) else { - return serde_json::Map::new(); - }; - serde_json::from_str(&text).unwrap_or_default() -} - -fn says(profile: &Path, key: &str) -> Option { - stored(profile).get(key).and_then(Value::as_str).map(str::to_owned) -} - -/// Read again through the window: a write answers frames later, on the core's queue. -fn settled(app: &mut App, profile: &Path, key: &str, want: &str) { - app.eventually(&format!("{key} reaches the file"), |_| says(profile, key).as_deref() == Some(want)); -} - -fn open(app: &mut App) { - app.click("file-menu"); - app.click("file-preferences"); - app.wait_for("settings-dialog"); -} - -#[test] -fn preferences_on_disk() { - let directory = tempfile::tempdir().unwrap(); - let profile = directory.path(); - let mut app = App::launch("15_preferences_on_disk", profile); - app.create_library(); - - step("the file is written, one key per setting", || { - open(&mut app); - app.click(THEME_DARK); - app.click("settings-close"); - settled(&mut app, profile, "devnotes.theme", "dark"); - }); - - step("the file waits for the draft to be applied", || { - open(&mut app); - app.click(THEME_LIGHT); - // The window has drawn the choice, and with it any write it would have asked for. - app.wait_for("settings-apply"); - assert_eq!(says(profile, "devnotes.theme").as_deref(), Some("dark"), "a preview is not a write"); - app.click("settings-close"); - settled(&mut app, profile, "devnotes.theme", "light"); - }); - - step("the locale the panel applied is stored", || { - open(&mut app); - app.click("setting-locale"); - app.click("setting-locale-2"); - app.click("settings-close"); - settled(&mut app, profile, "devnotes.locale", "en"); - }); - - step("every value is a string", || { - let file = stored(profile); - let others: Vec<&String> = file - .iter() - .filter(|(_, value)| !value.is_string()) - .map(|(key, _)| key) - .collect(); - assert!(others.is_empty(), "{others:?}"); - }); - - app.quit(); -} diff --git a/e2e/tests/16_passphrase_change.rs b/e2e/tests/16_passphrase_change.rs deleted file mode 100644 index 52e1adf78..000000000 --- a/e2e/tests/16_passphrase_change.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! What it proves is the shape of the change: the key file is rewritten, the notes are not, and -//! the session carries on. Read from the file rather than from what the application says of it. - -use std::path::{Path, PathBuf}; - -use e2e::{App, PASSPHRASE, step}; - -const NEXT: &str = "a second end-to-end passphrase"; - -/// The one key file of a profile, wherever its library lives. -fn key_file(directory: &Path) -> Option { - for entry in std::fs::read_dir(directory).ok()?.flatten() { - let path = entry.path(); - if path.is_dir() { - if path.ends_with("backups") { - continue; - } - if let Some(found) = key_file(&path) { - return Some(found); - } - } else if path.file_name().is_some_and(|name| name == "vault.json") { - return Some(path); - } - } - None -} - -fn security(app: &mut App) { - app.click("file-menu"); - app.click("file-preferences"); - app.click("settings-page-security"); - app.click("setting-change-passphrase"); - app.wait_for("change-passphrase"); -} - -fn fill_change(app: &mut App, current: &str) { - app.fill("change-passphrase-current", current); - app.fill("change-passphrase-next", NEXT); - app.fill("change-passphrase-confirmation", NEXT); - app.click("change-passphrase-submit"); -} - -#[test] -fn passphrase_change() { - let directory = tempfile::tempdir().unwrap(); - let profile = directory.path(); - let mut app = App::launch("16_passphrase_change", profile); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - let file = key_file(profile).expect("the library has its key file"); - let first = std::fs::read(&file).unwrap(); - - step("a change that cannot name the phrase rewrites nothing", || { - security(&mut app); - fill_change(&mut app, "not the current one"); - app.eventually("the phrase is refused", |tree| { - tree.text("change-passphrase-problem").is_some_and(|said| !said.is_empty()) - }); - assert_eq!(std::fs::read(&file).unwrap(), first); - assert!(app.has("change-passphrase"), "the dialog stays"); - }); - - step("the right phrase rewraps the key and leaves the notes", || { - app.eventually("the fields are free again", |tree| { - tree.find("change-passphrase-current").is_some_and(|field| !field.is_disabled()) - }); - fill_change(&mut app, PASSPHRASE); - app.eventually("the dialog closed", |tree| !tree.has("change-passphrase")); - // It stands over the dialog's buttons in a small window. - app.wait_for("status-toast"); - app.click("status-dismiss"); - app.eventually("the report is dismissed", |tree| !tree.has("status-toast")); - assert_ne!(std::fs::read(&file).unwrap(), first); - app.click("settings-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - assert!(app.has("note-card"), "the session carries on"); - }); - - let mut app = app.relaunch(); - step("the new phrase opens the library, and the old one no longer", || { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.eventually("the old phrase is refused", |tree| { - tree.text("vault-problem").is_some_and(|said| !said.is_empty()) - }); - app.fill("vault-passphrase", NEXT); - app.click("vault-submit"); - app.wait_for("area-notes"); - }); - - app.quit(); -} diff --git a/e2e/tests/17_folders.rs b/e2e/tests/17_folders.rs deleted file mode 100644 index ed5461b6c..000000000 --- a/e2e/tests/17_folders.rs +++ /dev/null @@ -1,305 +0,0 @@ -//! Folders: made from the rail, refused twice under one name, a selection filed and taken back -//! out, the chip a card wears, a note filed from its card, the notes left standing when the -//! folder goes — then folders inside folders: dragged onto another in the rail and offered back, -//! the list of an opened folder gathering its sub-tree, its own board one level down, a -//! sub-folder made from its panel, the folder dragged onto another space with its notes, and one -//! deleted with its notes, which wait in the trash. -//! -//! A space of its own, made here: the samples are in the system's language. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers, PointerButton, Pos2}; - -const SPACE: &str = "Dossiers"; -const FIRST: &str = "Requête lente"; -const SECOND: &str = "Plan d'exécution"; -const NESTED: &str = "Index partiel sur jobs"; -const DOOMED: &str = "Brouillon à jeter"; - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -fn titles(tree: &Tree) -> Vec { - tree.all("note-card-title") - .into_iter() - .map(|node| node.label().or(node.value()).unwrap_or_default().to_owned()) - .collect() -} - -/// How many rows of the rail are named `name`: the samples' folders are listed too. -fn rows_named(tree: &Tree, name: &str) -> usize { - tree.texts("folder-option").iter().filter(|row| *row == name).count() -} - -fn crumb(tree: &Tree) -> Option { - tree.text("folder-breadcrumb-name") -} - -fn centre(node: &Node) -> Pos2 { - let rect = node.bounds().expect("a place on screen"); - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - Pos2::new(f64::midpoint(rect.x0, rect.x1) as f32, f64::midpoint(rect.y0, rect.y1) as f32) -} - -fn write(app: &mut App, title: &str) { - app.click("new-note"); - app.fill("editor-title", title); - app.fill("editor-body", "SELECT 1;"); - app.click("editor-close"); - app.eventually("the note is a card", |tree| { - !tree.has("editor-title") && titles(tree).contains(&title.to_owned()) - }); -} - -fn make_folder(app: &mut App, name: &str) { - app.click("folder-create-open"); - app.fill("folder-create-input", name); - app.press(Key::Enter, Modifiers::NONE); -} - -fn file_into(app: &mut App, name: &str) { - app.click("selection-move"); - app.click_where("selection-move-place", ends_with(name)); -} - -/// The first place offered, whatever the language calls it: out of every folder. -fn unfile(app: &mut App) { - app.click("selection-move"); - app.wait_for("selection-move-place"); - app.click("selection-move-place"); -} - -/// A folder's place: its path ends with its name. -fn ends_with(name: &str) -> impl Fn(&Node) -> bool { - let end = format!(" › {name}"); - move |node| node.label().is_some_and(|label| label.ends_with(&end)) -} - -fn tick_all(app: &mut App) { - app.click("search-input"); - app.press(Key::ArrowDown, Modifiers::NONE); - for key in [Key::X, Key::ArrowRight, Key::X] { - app.press(key, Modifiers::NONE); - } - app.eventually("two cards are ticked", |tree| { - tree.text("selection-count").is_some_and(|said| said.contains('2')) - }); -} - -fn space_of_its_own(app: &mut App) { - step("a space of its own, two notes, a folder made from the rail", || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") - }); - write(app, FIRST); - write(app, SECOND); - make_folder(app, "Perf"); - app.eventually("the folder is listed", |tree| rows_named(tree, "Perf") == 1); - }); - - step("a second folder of the same name is refused", || { - make_folder(app, "Perf"); - app.eventually("the refusal is said", |tree| tree.has("error-banner")); - assert_eq!(rows_named(&app.tree(), "Perf"), 1); - app.click("error-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - }); -} - -fn filing(app: &mut App) { - step("a whole selection is filed in one gesture, and says where", || { - tick_all(app); - file_into(app, "Perf"); - app.eventually("both cards wear the folder's chip", |tree| tree.count("note-card-folder") == 2); - // While the bar offers the filing back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| !tree.has("selection-count")); - }); - - step("the folder narrows the canvas, and the space opens it back", || { - app.click_where("folder-option", named("Perf")); - app.eventually("its notes alone, no chip naming it", |tree| { - crumb(tree).as_deref() == Some("Perf") && titles(tree).len() == 2 && !tree.has("note-card-folder") - }); - app.click_where("space-option", named(SPACE)); - app.eventually("the whole space", |tree| crumb(tree).is_none()); - }); - - step("a selection taken back out wears no chip at all", || { - tick_all(app); - unfile(app); - app.eventually("no card wears a chip", |tree| !tree.has("note-card-folder")); - // While the bar offers the filing back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - }); - - step("a note is filed from its card's menu", || { - app.hover("note-card"); - app.click("note-card-menu"); - app.click("note-card-move"); - app.fill("note-card-move-filter", "perf"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("one card wears the chip", |tree| tree.count("note-card-folder") == 1); - }); - - step("deleting the folder leaves every note standing", || { - app.click_where("folder-edit", |node| node.label().is_some_and(|label| label.contains("Perf"))); - app.click("folder-delete"); - app.click("folder-delete"); - app.eventually("the folder is gone, both notes kept", |tree| { - rows_named(tree, "Perf") == 0 && titles(tree).len() == 2 && !tree.has("note-card-folder") - }); - }); -} - -fn nested(app: &mut App) { - step("a folder dragged onto another goes inside it, offered back", || { - make_folder(app, "Bases"); - app.eventually("listed", |tree| rows_named(tree, "Bases") == 1); - make_folder(app, "Index"); - app.eventually("listed", |tree| rows_named(tree, "Index") == 1); - app.click_where("folder-option", named("Index")); - app.wait_for("folder-breadcrumb-name"); - write(app, NESTED); - app.click_where("space-option", named(SPACE)); - app.eventually("the space", |tree| crumb(tree).is_none()); - let tree = app.tree(); - let index = tree - .all("folder-option") - .into_iter() - .find(|node| node.label() == Some("Index")) - .map(centre) - .unwrap(); - let bases = tree - .all("folder-option") - .into_iter() - .find(|node| node.label() == Some("Bases")) - .map(centre) - .unwrap(); - app.drag(index, bases, PointerButton::Primary); - app.eventually("« Index » is drawn inside « Bases », and offered back", |tree| { - let rows = tree.all("folder-option"); - let left = |name: &str| { - rows.iter() - .find(|node| node.label() == Some(name)) - .and_then(|node| node.bounds()) - .map(|bounds| bounds.x0) - }; - left("Index") > left("Bases") && tree.has("undo-restore") - }); - app.capture("rail-nested"); - app.click("undo-dismiss"); - app.eventually("the bar is gone", |tree| !tree.has("undo-bar")); - }); - - step("an opened folder lists its whole sub-tree, each card naming its own", || { - app.click_where("folder-option", named("Bases")); - app.eventually("the note of « Index » is listed", |tree| { - crumb(tree).as_deref() == Some("Bases") && titles(tree).contains(&NESTED.to_owned()) - }); - // The chip shows the deepest folder and says its path from the top. - assert_eq!(app.tree().text("note-card-folder").as_deref(), Some("Bases › Index")); - }); - - step("on the board, a folder that holds folders is a board one level down", || { - app.click("folder-breadcrumb-back"); - app.eventually("the space", |tree| crumb(tree).is_none()); - app.click("view-board"); - app.click_where("board-zone-open", named("Bases")); - app.eventually("« Index » is its one zone, holding its note", |tree| { - crumb(tree).as_deref() == Some("Bases") && tree.texts("board-zone-open") == ["Index"] - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the space's board, « Index » inside « Bases »'s zone", |tree| { - crumb(tree).is_none() - && tree.texts("board-zone-open").contains(&"Bases".to_owned()) - && tree.texts("board-zone-child").contains(&"Index".to_owned()) - }); - app.click("view-list"); - }); - - step("a folder made inside another from its panel", || { - app.click_where("folder-edit", |node| node.label().is_some_and(|label| label.contains("Index"))); - app.click("folder-subfolder-open"); - app.fill("folder-subfolder-input", "Partiels"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("listed under « Index », the field gone", |tree| { - tree.texts("folder-option").contains(&"Partiels".to_owned()) - && !tree.has("folder-subfolder-input") - }); - }); -} - -/// « Bases », holding « Index » and its note, dropped onto the samples' space: the note is found -/// there, and the undo bar brings everything back. -fn to_another_space(app: &mut App) { - step("a folder dragged onto another space goes there with its notes, offered back", || { - let tree = app.tree(); - let samples = tree - .texts("space-option") - .into_iter() - .find(|name| name != SPACE) - .expect("the samples' space"); - let at = |author_id: &str, name: &str| { - tree.all(author_id) - .into_iter() - .find(|node| node.label() == Some(name)) - .map_or_else(|| panic!("no row {name}"), centre) - }; - let (bases, other) = (at("folder-option", "Bases"), at("space-option", &samples)); - app.drag(bases, other, PointerButton::Primary); - app.wait_for("undo-restore"); - app.click_where("space-option", named(&samples)); - app.eventually("the note of « Index » is in the samples' space", |tree| { - titles(tree).contains(&NESTED.to_owned()) - }); - app.click("undo-restore"); - app.click_where("space-option", named(SPACE)); - app.eventually("back in its space, with its note", |tree| titles(tree).contains(&NESTED.to_owned())); - }); -} - -fn deleted_with_its_notes(app: &mut App) { - step("a folder deleted with its notes puts them in the trash", || { - make_folder(app, "Jetable"); - app.eventually("the folder is listed", |tree| rows_named(tree, "Jetable") == 1); - app.click_where("folder-option", named("Jetable")); - app.wait_for("folder-breadcrumb-name"); - write(app, DOOMED); - app.click_where("folder-edit", |node| node.label().is_some_and(|label| label.contains("Jetable"))); - app.click("folder-delete-held"); - app.click("folder-delete-held-1"); - app.click("folder-delete"); - app.click("folder-delete"); - app.eventually("the folder is gone, its note with it", |tree| { - rows_named(tree, "Jetable") == 0 && !titles(tree).contains(&DOOMED.to_owned()) - }); - app.click("trash-open"); - app.eventually("the note waits in the trash", |tree| { - tree.texts("trash-row-title").contains(&DOOMED.to_owned()) - }); - app.press(Key::Escape, Modifiers::NONE); - }); -} - -#[test] -fn folders() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("17_folders", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - space_of_its_own(&mut app); - filing(&mut app); - nested(&mut app); - to_another_space(&mut app); - deleted_with_its_notes(&mut app); - app.quit(); -} diff --git a/e2e/tests/18_board.rs b/e2e/tests/18_board.rs deleted file mode 100644 index 434bbda01..000000000 --- a/e2e/tests/18_board.rs +++ /dev/null @@ -1,280 +0,0 @@ -//! The board: a space's folders drawn as zones holding their notes, the loose ones beside, the -//! same card the list draws, a first layout that comes back unchanged after a relaunch, and the -//! view remembered space by space. Only a real database proves the first layout is written. -//! -//! A space of its own, made here: the samples are in the system's language. - -use e2e::{App, Tree, step}; -use egui::accesskit::{Node, Rect, Toggled}; -use egui::{Key, Modifiers}; - -const SPACE: &str = "Tableau"; -const FILED: &str = "EXPLAIN lent sur join"; -const LOOSE: &str = "Dump nocturne"; -const LIST: &str = "Avant la release"; - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -fn is_on(tree: &Tree, author_id: &str) -> bool { - tree.find(author_id).is_some_and(|node| node.toggled() == Some(Toggled::True)) -} - -fn frame_of(tree: &Tree, zone: &str) -> Option { - tree.all("board-zone") - .into_iter() - .find(|node| node.label() == Some(zone)) - .and_then(Node::bounds) -} - -/// The titles drawn inside `zone`, in reading order. -fn titles_in(tree: &Tree, zone: &str) -> Vec { - let Some(frame) = frame_of(tree, zone) else { - return Vec::new(); - }; - tree.all("note-card-title") - .into_iter() - .filter(|node| { - node.bounds().is_some_and(|card| { - card.x0 >= frame.x0 && card.x1 <= frame.x1 && card.y0 >= frame.y0 && card.y1 <= frame.y1 - }) - }) - .map(|node| node.label().or(node.value()).unwrap_or_default().to_owned()) - .collect() -} - -fn frames(tree: &Tree) -> Vec { - tree.all("board-zone").into_iter().filter_map(Node::bounds).collect() -} - -/// A note written from the editor in whatever space or folder is shown. -fn write(app: &mut App, title: &str) { - app.click("new-note"); - app.fill("editor-title", title); - app.fill("editor-body", "SELECT 1;"); - app.click("editor-close"); - app.eventually("the note is a card", |tree| { - !tree.has("editor-title") && tree.texts("note-card").contains(&title.to_owned()) - }); -} - -fn choose_space(app: &mut App, name: &str) { - app.click_where("space-option", named(name)); - app.eventually("the space is shown", |tree| { - tree.all("space-option") - .into_iter() - .any(|node| node.label() == Some(name) && node.toggled() == Some(Toggled::True)) - }); -} - -/// A space of its own: two folders, a note filed in the first, one loose. -fn seed(app: &mut App) { - step("a space of its own: two folders, a note filed, one loose", || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown, empty", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") - }); - for name in ["Perf", "Migrations"] { - app.click("folder-create-open"); - app.fill("folder-create-input", name); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| { - tree.texts("folder-option").contains(&name.to_owned()) - }); - } - app.click_where("folder-option", named("Perf")); - app.wait_for("folder-breadcrumb-name"); - write(app, FILED); - choose_space(app, SPACE); - write(app, LOOSE); - }); -} - -/// What a card on the board still does: tick its items, take the selection, take the arrows. -fn on_the_board(app: &mut App) { - step("a todo list is ticked on the board, and shown ticked", || { - app.click("new-note-kind"); - app.click("new-note-checklist"); - app.fill("editor-title", LIST); - app.click("checklist-add"); - app.eventually("the new row has the focus", |tree| tree.focused().starts_with("checklist-text")); - app.type_text("Tag"); - app.click("editor-close"); - app.eventually("the list is a loose card", |tree| { - tree.texts("board-loose-card").contains(&LIST.to_owned()) - }); - app.click_nth("note-card-item", 0); - app.eventually("the item is ticked", |tree| { - tree.find("note-card-item") - .is_some_and(|node| node.toggled() == Some(Toggled::True)) - }); - }); - - step("the corner is the selection tick's", || { - let title = app.tree().texts("board-loose-card")[0].clone(); - let its_tick = |node: &Node| node.label().is_some_and(|label| label.contains(&title)); - app.hover("board-loose-card"); - app.click_where("note-card-check", its_tick); - app.wait_for("selection-count"); - app.click_where("note-card-check", its_tick); - app.eventually("the bar is gone", |tree| !tree.has("selection-count")); - }); - - step("from one open note to the next, the panel stays", || { - panel_kept(app); - }); - - step("the arrows walk the cards as the board lays them out", || { - app.click("search-input"); - app.press(Key::ArrowDown, Modifiers::NONE); - for _ in 0..3 { - app.press(Key::ArrowLeft, Modifiers::NONE); - } - app.eventually("the first card of the board has the focus", |tree| tree.focused().contains(FILED)); - app.press(Key::ArrowRight, Modifiers::NONE); - app.eventually("then the next", |tree| !tree.focused().contains(FILED)); - app.press(Key::Escape, Modifiers::NONE); - }); -} - -fn open_title(tree: &Tree) -> Option<&str> { - tree.find("editor-title").and_then(Node::value) -} - -/// One note open, then the next one by J: the zones never move while the second is read. J -/// rather than a click: the panel may cover the next card. -fn panel_kept(app: &mut App) { - app.click_where("note-card-open", named(FILED)); - app.eventually("the first note is open, no field focused", |tree| { - open_title(tree) == Some(FILED) && !tree.focused().starts_with("editor-title") - }); - let beside = frames(&app.tree()); - app.press(Key::J, Modifiers::NONE); - app.eventually("the next is open, the zones where they were", |tree| { - assert_eq!(frames(tree), beside, "the board moved"); - open_title(tree).is_some_and(|title| title != FILED) - }); - app.click("editor-close"); - app.eventually("the editor closed", |tree| !tree.has("editor-title")); -} - -/// Whether the card titled `title` is drawn lit: a dimmed one keeps its seat, disabled. -fn lit(tree: &Tree, title: &str) -> Option { - tree.all("board-loose-card") - .into_iter() - .chain(tree.all("board-zone-card")) - .find(|node| node.label() == Some(title)) - .map(|node| !node.is_disabled()) -} - -/// A search dims on the board, and the tidy names what it would touch. -fn dimmed(app: &mut App) { - step("a search dims what it does not match, and drops nothing", || { - app.click("search-input"); - app.type_text("EXPLAIN"); - app.eventually("the loose card is dimmed", |tree| lit(tree, LOOSE) == Some(false)); - let tree = app.tree(); - assert_eq!(lit(&tree, FILED), Some(true)); - assert_eq!(titles_in(&tree, "Perf"), [FILED]); - app.capture("board-dimmed"); - app.click("search-clear"); - app.eventually("the card is lit again", |tree| lit(tree, LOOSE) == Some(true)); - }); - - step("reorganising says how many folders and cards it moves", || { - app.click("board-tidy-more"); - app.eventually("the entry counts two of each", |tree| { - tree.text("board-tidy-everything") - .is_some_and(|said| said.matches('2').count() == 2) - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the menu is closed", |tree| !tree.has("board-tidy-everything")); - }); -} - -#[test] -fn board() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("18_board", profile.path()); - app.create_library(); - app.wait_for("note-card"); - let samples = app.tree().texts("space-option")[0].clone(); - - seed(&mut app); - - step("the list is the default, and there is no board across every space", || { - assert!(is_on(&app.tree(), "view-list")); - assert!(!app.has("board")); - app.click("space-option-all"); - app.eventually("the board is offered disabled", |tree| { - tree.find("view-board").is_some_and(Node::is_disabled) - }); - choose_space(&mut app, SPACE); - }); - - step("each folder is a zone holding its notes, the loose ones beside", || { - app.click("view-board"); - app.eventually("the zones are drawn", |tree| tree.count("board-zone") == 2); - let tree = app.tree(); - let mut zones = tree.texts("board-zone-open"); - zones.sort(); - assert_eq!(zones, ["Migrations", "Perf"]); - assert_eq!(titles_in(&tree, "Perf"), [FILED]); - assert!(titles_in(&tree, "Migrations").is_empty()); - assert_eq!(tree.texts("board-loose-card"), [LOOSE]); - // The same card as the list's: its title, and the layer that opens it. - assert_eq!(tree.count("note-card-open"), 2); - let [first, second] = frames(&tree)[..] else { - panic!("two zones"); - }; - assert!(first.x1 <= second.x0 || second.x1 <= first.x0, "side by side"); - app.capture("board"); - }); - - on_the_board(&mut app); - dimmed(&mut app); - - let before = frames(&app.tree()); - let mut app = app.relaunch(); - - step("a relaunch comes back on the board, its layout unchanged", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.eventually("the board is back", |tree| tree.count("board-zone") == 2); - assert_eq!(frames(&app.tree()), before); - }); - - step("the view is remembered space by space", || { - choose_space(&mut app, &samples); - app.eventually("the samples are listed", |tree| !tree.has("board") && tree.has("note-card")); - choose_space(&mut app, SPACE); - app.eventually("the board is back", |tree| tree.has("board")); - }); - - step("the list is left exactly as it was", || { - app.click("view-list"); - app.eventually("the three notes are listed", |tree| { - !tree.has("board") && tree.count("note-card") == 3 - }); - app.click("view-board"); - app.wait_for("board"); - }); - - step("a window larger than the board is pointer ground all over", || { - app.resize(1600, 1000); - app.eventually("the surface covers the ground", |tree| { - let (Some(ground), Some(surface)) = ( - tree.find("board").and_then(Node::bounds), - tree.find("board-surface").and_then(Node::bounds), - ) else { - return false; - }; - surface.x1 >= ground.x1 && surface.y1 >= ground.y1 - }); - }); - - app.quit(); -} diff --git a/e2e/tests/19_board_gesture.rs b/e2e/tests/19_board_gesture.rs deleted file mode 100644 index feaaccef4..000000000 --- a/e2e/tests/19_board_gesture.rs +++ /dev/null @@ -1,306 +0,0 @@ -//! Arranging the board by hand: a card dragged into a zone and back out, a zone moved and -//! resized, a folder drawn on the ground, a right-button sweep, a whole zone ticked, and the -//! tidy — each checked against what a relaunch reads back from the database. The keyboard twin -//! of a drop is the selection bar's « File into ». -//! -//! A space of its own, made here: the samples are in the system's language. - -use e2e::{App, Tree, step}; -use egui::accesskit::{Node, Rect}; -use egui::{Key, Modifiers, PointerButton, Pos2}; - -const SPACE: &str = "Gestes"; -const FILED: &str = "EXPLAIN lent sur join"; -const LOOSE: &str = "Dump nocturne"; -/// `folders::board::ZONE_HEADER`: every control of a zone's header holds in it. -const ZONE_HEADER: f64 = 38.0; - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -fn bounds_of(tree: &Tree, author_id: &str, name: &str) -> Option { - tree.all(author_id) - .into_iter() - .find(|node| node.label() == Some(name)) - .and_then(Node::bounds) -} - -/// Points on the window, from the tree's `f64`. -fn point(x: f64, y: f64) -> Pos2 { - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - Pos2::new(x as f32, y as f32) -} - -fn centre(rect: Rect) -> Pos2 { - point(f64::midpoint(rect.x0, rect.x1), f64::midpoint(rect.y0, rect.y1)) -} - -/// The titles drawn inside `zone`. -fn titles_in(tree: &Tree, zone: &str) -> Vec { - let Some(frame) = bounds_of(tree, "board-zone", zone) else { - return Vec::new(); - }; - tree.all("board-zone-card") - .into_iter() - .filter(|node| { - node.bounds() - .is_some_and(|card| card.x0 >= frame.x0 && card.x1 <= frame.x1 && card.y0 >= frame.y0) - }) - .map(|node| node.label().unwrap_or_default().to_owned()) - .collect() -} - -/// A zone's control, the one in that zone's header. -fn control_of(tree: &Tree, author_id: &str, zone: &str) -> Option { - let frame = bounds_of(tree, "board-zone", zone)?; - tree.all(author_id).into_iter().filter_map(Node::bounds).find(|control| { - control.x0 >= frame.x0 - 1.0 - && control.x1 <= frame.x1 + 1.0 - && control.y0 >= frame.y0 - 1.0 - && control.y1 <= frame.y1 + 1.0 - }) -} - -fn write(app: &mut App, title: &str) { - app.click("new-note"); - app.fill("editor-title", title); - app.fill("editor-body", "SELECT 1;"); - app.click("editor-close"); - app.eventually("the note is a card", |tree| { - !tree.has("editor-title") && tree.texts("note-card").contains(&title.to_owned()) - }); -} - -/// The selection bar's « File into », on the entry named `name`. -/// The box of the card the steps file and take back. -fn filed(node: &Node) -> bool { - node.label().is_some_and(|label| label.contains(FILED)) -} - -fn file_into(app: &mut App, name: &str) { - app.click("selection-move"); - let end = format!(" › {name}"); - app.click_where("selection-move-place", |node| node.label().is_some_and(|label| label.ends_with(&end))); -} - -fn reopen(app: App) -> App { - let mut app = app.relaunch(); - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.eventually("the board is back", |tree| tree.has("board-zone")); - app -} - -fn seed(app: &mut App) { - step("a space of its own: two folders, a note filed, one loose", || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") - }); - for name in ["Perf", "Migrations"] { - app.click("folder-create-open"); - app.fill("folder-create-input", name); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| { - tree.texts("folder-option").contains(&name.to_owned()) - }); - } - app.click_where("folder-option", named("Perf")); - app.wait_for("folder-breadcrumb-name"); - write(app, FILED); - app.click_where("space-option", named(SPACE)); - app.eventually("the space is shown", |tree| !tree.has("folder-breadcrumb-name")); - write(app, LOOSE); - app.click("view-board"); - app.eventually("the board is drawn", |tree| tree.count("board-zone") == 2); - }); -} - -fn cards(app: &mut App) { - step("a card dragged into a zone is filed there, and its place forgotten", || { - let tree = app.tree(); - let card = bounds_of(&tree, "board-loose-card", LOOSE).unwrap(); - let zone = bounds_of(&tree, "board-zone", "Migrations").unwrap(); - // The card lands where its corner does: the grab, at its centre, keeps the offset. - let into = point(zone.x0 + 150.0, zone.y0 + 120.0); - app.drag(centre(card), into, PointerButton::Primary); - app.eventually("the card flows in the zone", |tree| { - titles_in(tree, "Migrations") == [LOOSE] - && !tree.texts("board-loose-card").contains(&LOOSE.to_owned()) - }); - app.capture("board-filed"); - }); - - step("dropped on the ground, it comes back out", || { - let card = bounds_of(&app.tree(), "board-zone-card", LOOSE).unwrap(); - let ground = Pos2::new(centre(card).x, centre(card).y + 360.0); - app.drag(centre(card), ground, PointerButton::Primary); - app.eventually("the card is loose again", |tree| { - tree.texts("board-loose-card").contains(&LOOSE.to_owned()) - && titles_in(tree, "Migrations").is_empty() - }); - }); - - step("dropped on the rail, it is filed in that folder", || { - let tree = app.tree(); - let card = bounds_of(&tree, "board-loose-card", LOOSE).unwrap(); - let row = bounds_of(&tree, "folder-option", "Migrations").unwrap(); - app.drag(centre(card), centre(row), PointerButton::Primary); - app.eventually("the card flows in the zone", |tree| titles_in(tree, "Migrations") == [LOOSE]); - let card = bounds_of(&app.tree(), "board-zone-card", LOOSE).unwrap(); - let ground = Pos2::new(centre(card).x, centre(card).y + 360.0); - app.drag(centre(card), ground, PointerButton::Primary); - app.eventually("the card is loose again", |tree| titles_in(tree, "Migrations").is_empty()); - }); - - step("the keyboard files with no pointer, from the selection bar", || { - app.click_where("note-card-check", filed); - app.wait_for("selection-count"); - file_into(app, "Migrations"); - app.eventually("the note is in the other zone", |tree| titles_in(tree, "Migrations") == [FILED]); - // While the bar offers the filing back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - app.click_where("note-card-check", filed); - file_into(app, "Perf"); - app.eventually("and back", |tree| titles_in(tree, "Perf") == [FILED]); - // While the bar offers the filing back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| !tree.has("selection-count")); - }); - - step("a zone's menu ticks every card it holds", || { - app.click_where("board-zone-menu", |node| node.label().is_some_and(|label| label.contains("Perf"))); - app.click("folder-select-notes"); - app.eventually("its card is ticked", |tree| { - tree.text("selection-count").is_some_and(|said| said.contains('1')) - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| !tree.has("selection-count")); - }); -} - -fn zones(app: &mut App) { - step("a zone's header holds in ZONE_HEADER", || { - let tree = app.tree(); - let frame = bounds_of(&tree, "board-zone", "Perf").unwrap(); - for control in ["board-zone-grip", "board-zone-open", "board-zone-menu"] { - let drawn = control_of(&tree, control, "Perf").unwrap(); - assert!(drawn.y1 <= frame.y0 + ZONE_HEADER, "{control} overflows the header"); - } - }); - - step("a zone moved by its grip lands on the grid and keeps its notes", || { - let tree = app.tree(); - let before = bounds_of(&tree, "board-zone", "Perf").unwrap(); - let grip = control_of(&tree, "board-zone-grip", "Perf").unwrap(); - let to = centre(grip) + egui::vec2(93.0, 141.0); - app.drag(centre(grip), to, PointerButton::Primary); - app.eventually("the zone moved, its size kept", |tree| { - bounds_of(tree, "board-zone", "Perf").is_some_and(|moved| { - (moved.x0 - before.x0).abs() > 0.5 && (moved.width() - before.width()).abs() < 0.5 - }) - }); - assert_eq!(titles_in(&app.tree(), "Perf"), [FILED]); - }); - - step("resized by its corner, it captures and releases nothing", || { - let tree = app.tree(); - let before = bounds_of(&tree, "board-zone", "Perf").unwrap(); - let corner = control_of(&tree, "board-zone-resize", "Perf").unwrap(); - let to = centre(corner) + egui::vec2(260.0, 120.0); - app.drag(centre(corner), to, PointerButton::Primary); - app.eventually("the zone is wider, where it was", |tree| { - bounds_of(tree, "board-zone", "Perf").is_some_and(|resized| { - resized.width() > before.width() + 100.0 && (resized.x0 - before.x0).abs() < 0.5 - }) - }); - let tree = app.tree(); - assert_eq!(titles_in(&tree, "Perf"), [FILED]); - assert!(tree.texts("board-loose-card").contains(&LOOSE.to_owned())); - }); - - step("a band drawn on the ground becomes the folder named there", || { - let ground = app.tree().find("board").and_then(Node::bounds).unwrap(); - let from = point(ground.x0 + 40.0, ground.y1 - 260.0); - app.drag(from, from + egui::vec2(300.0, 220.0), PointerButton::Primary); - app.fill("folder-name-input", "Reporting"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the zone is drawn where it was drawn", |tree| { - tree.texts("board-zone-open").contains(&"Reporting".to_owned()) - }); - app.capture("board-drawn-zone"); - }); -} - -fn selecting(app: &mut App) { - step("a right-button sweep ticks the cards it crosses, zones included", || { - let ground = app.tree().find("board").and_then(Node::bounds).unwrap(); - let from = point(ground.x0 + 4.0, ground.y0 + 4.0); - let to = point(ground.x1 - 40.0, ground.y1 - 60.0); - app.drag(from, to, PointerButton::Secondary); - app.eventually("both cards are ticked", |tree| { - tree.text("selection-count").is_some_and(|said| said.contains('2')) - }); - assert!(!app.has("folder-name-input"), "the right button draws no folder"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| !tree.has("selection-count")); - }); -} - -/// One step: the core writes in order, so the undo of the reorganisation puts back the layout -/// aligning left — the hand's, if aligning moved no zone. -fn tidying(app: &mut App) { - step("aligning leaves the zones; reorganising moves them, and its undo puts the hand's back", || { - let by_hand = bounds_of(&app.tree(), "board-zone", "Perf").unwrap(); - app.click("board-tidy"); - app.click("board-tidy-more"); - app.click("board-tidy-everything"); - app.eventually("the zone is back at its seat", |tree| { - bounds_of(tree, "board-zone", "Perf").is_some_and(|seat| (seat.x0 - by_hand.x0).abs() > 0.5) - && tree.has("undo-restore") - }); - app.capture("board-reorganised"); - app.click("undo-restore"); - app.eventually("the hand's layout is back", |tree| { - bounds_of(tree, "board-zone", "Perf") - .is_some_and(|back| (back.x0 - by_hand.x0).abs() < 0.5 && (back.y0 - by_hand.y0).abs() < 0.5) - }); - }); -} - -#[test] -fn board_gesture() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("19_board_gesture", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - seed(&mut app); - cards(&mut app); - zones(&mut app); - let before = ( - bounds_of(&app.tree(), "board-zone", "Perf"), - bounds_of(&app.tree(), "board-loose-card", LOOSE), - bounds_of(&app.tree(), "board-zone", "Reporting"), - ); - let mut app = reopen(app); - - step("a relaunch reads back every place the hand chose", || { - let tree = app.tree(); - let after = ( - bounds_of(&tree, "board-zone", "Perf"), - bounds_of(&tree, "board-loose-card", LOOSE), - bounds_of(&tree, "board-zone", "Reporting"), - ); - assert_eq!(after, before); - }); - - selecting(&mut app); - tidying(&mut app); - app.quit(); -} diff --git a/e2e/tests/20_folder_descent.rs b/e2e/tests/20_folder_descent.rs deleted file mode 100644 index 44ce87427..000000000 --- a/e2e/tests/20_folder_descent.rs +++ /dev/null @@ -1,184 +0,0 @@ -//! Opening a folder: empty, it offers the card a note is made from, not « nothing matches »; from -//! a zone's title on the board, a flat grid of its notes named after it, -//! the switchers put away for its breadcrumb, a note made inside it filed there, renamed from -//! beside the breadcrumb, and left again — Escape giving the search back first, then the folder -//! — down to the board it was opened from, or through the breadcrumb, or by deleting it. -//! -//! A space of its own, made here: the samples are in the system's language. - -use e2e::{App, Tree, step}; -use egui::accesskit::{Node, Toggled}; -use egui::{Key, Modifiers}; - -const SPACE: &str = "Descente"; -const INSIDE: &str = "EXPLAIN lent sur join"; -const LOOSE: &str = "Dump nocturne"; -const MADE: &str = "Cache hit ratio"; - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -fn crumb(tree: &Tree) -> Option { - tree.text("folder-breadcrumb-name") -} - -fn titles(tree: &Tree) -> Vec { - tree.all("note-card-title") - .into_iter() - .map(|node| node.label().or(node.value()).unwrap_or_default().to_owned()) - .collect() -} - -fn heading(tree: &Tree) -> String { - tree.texts("note-section").join(" ") -} - -/// A note made from `from`: « + New note », or the card that offers it. -fn write(app: &mut App, from: &str, title: &str) { - app.click(from); - app.fill("editor-title", title); - app.fill("editor-body", "SELECT 1;"); - app.click("editor-close"); - app.eventually("the note is a card", |tree| { - !tree.has("editor-title") && titles(tree).contains(&title.to_owned()) - }); -} - -fn search(app: &mut App, words: &str) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(words); -} - -fn clear(app: &mut App) { - app.click("search-clear"); - app.eventually("the search is empty", |tree| !tree.has("search-clear")); -} - -fn seed(app: &mut App) { - step("a space of its own, a folder holding one note, one loose", || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") - }); - app.click("folder-create-open"); - app.fill("folder-create-input", "Perf"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| tree.has("folder-option")); - app.click_where("folder-option", named("Perf")); - app.eventually("empty, it offers the card to create from, not a search", |tree| { - tree.has("create-ghost") - && !tree.has("canvas-no-results") - && heading(tree).to_uppercase().starts_with("PERF") - }); - write(app, "create-ghost", INSIDE); - app.click_where("space-option", named(SPACE)); - app.eventually("the space is shown", |tree| crumb(tree).is_none()); - write(app, "new-note", LOOSE); - app.click("view-board"); - app.wait_for("board-zone"); - }); -} - -fn inside(app: &mut App) { - step("a zone's title opens its folder, a flat grid of its notes", || { - app.click_where("board-zone-open", named("Perf")); - app.eventually("the breadcrumb names it, the grid shows its note", |tree| { - crumb(tree).as_deref() == Some("Perf") && !tree.has("board") && titles(tree) == [INSIDE] - }); - let tree = app.tree(); - assert!(heading(&tree).to_uppercase().starts_with("PERF"), "{}", heading(&tree)); - for gone in ["space-switcher", "view-board", "folder-switcher"] { - assert!(!tree.has(gone), "{gone} is put away"); - } - assert!(tree.has("create-ghost"), "a note is made from here"); - app.capture("folder-open"); - }); - - step("a search stays inside the folder, and drops the ghost", || { - search(app, "EXPLAIN"); - // The heading follows the field at once, the ghost the view once the search rests. - app.eventually("found inside, the list no longer named after it", |tree| { - titles(tree) == [INSIDE] - && !heading(tree).to_uppercase().starts_with("PERF") - && !tree.has("create-ghost") - }); - search(app, "Dump"); - app.eventually("a note of the space outside it stays out of reach", |tree| { - tree.has("canvas-no-results") && crumb(tree).is_some() - }); - clear(app); - }); - - step("a note made here arrives filed", || { - write(app, "new-note", MADE); - app.eventually("both notes are in it", |tree| titles(tree).len() == 2); - }); - - step("renamed from beside the breadcrumb", || { - app.click("folder-breadcrumb-menu"); - app.click("folder-rename-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("Performance"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the breadcrumb carries the new name", |tree| { - crumb(tree).as_deref() == Some("Performance") - }); - }); -} - -fn leaving(app: &mut App) { - step("Escape gives the search back before the folder", || { - search(app, "EXPLAIN"); - app.eventually("searched", |tree| tree.has("search-clear")); - // egui lets go of the field before the canvas reads the key: one press is one rung. - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the search is cleared, the folder kept", |tree| { - !tree.has("search-clear") && crumb(tree).is_some() - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("back on the board it was opened from", |tree| { - crumb(tree).is_none() && tree.has("board") - }); - }); - - step("the breadcrumb leads back too", || { - app.click_where("board-zone-open", named("Performance")); - app.wait_for("folder-breadcrumb-name"); - app.click("folder-breadcrumb-back"); - app.eventually("back on the board", |tree| crumb(tree).is_none() && tree.has("board")); - assert!( - app.tree() - .all("space-option") - .into_iter() - .any(|node| node.label() == Some(SPACE) && node.toggled() == Some(Toggled::True)) - ); - }); - - step("deleted from inside it, its notes stay on the board", || { - app.click_where("board-zone-open", named("Performance")); - app.wait_for("folder-breadcrumb-name"); - app.click("folder-breadcrumb-menu"); - app.click("folder-delete"); - app.click("folder-delete"); - app.eventually("the folder is gone, its notes loose", |tree| { - crumb(tree).is_none() && !tree.has("board-zone") && tree.count("board-loose-card") == 3 - }); - }); -} - -#[test] -fn folder_descent() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("20_folder_descent", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - seed(&mut app); - inside(&mut app); - leaving(&mut app); - app.quit(); -} diff --git a/e2e/tests/21_folders_travel.rs b/e2e/tests/21_folders_travel.rs deleted file mode 100644 index 778150af2..000000000 --- a/e2e/tests/21_folders_travel.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! A space exported from one machine and imported on another comes back arranged: the notes in -//! their folders, the folders cited by nobody left behind, and a second import adds nothing. -//! -//! « The other machine » is a second profile: a genuinely fresh library. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -const SPACE: &str = "Voyage"; -const CITED: &str = "Perf"; -const UNCITED: &str = "Jamais citée"; -const FILED: &str = "EXPLAIN lent"; -const LOOSE: &str = "Dump nocturne"; - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -fn folders_named(tree: &Tree, name: &str) -> usize { - tree.texts("folder-option").iter().filter(|row| *row == name).count() -} - -fn write(app: &mut App, title: &str) { - app.click("new-note"); - app.fill("editor-title", title); - app.fill("editor-body", "SELECT 1;"); - app.click("editor-close"); - app.eventually("the note is a card", |tree| !tree.has("editor-title")); -} - -fn make_folder(app: &mut App, name: &str) { - app.click("folder-create-open"); - app.fill("folder-create-input", name); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| folders_named(tree, name) == 1); -} - -fn menu(app: &mut App, entry: &str) { - app.click("file-menu"); - app.click(&format!("file-option-{entry}")); -} - -fn report(app: &mut App) { - app.wait_for("status-toast"); - app.click("status-dismiss"); - app.eventually("the report is dismissed", |tree| !tree.has("status-toast")); -} - -#[test] -fn folders_travel() { - let directory = tempfile::tempdir().unwrap(); - let file = directory.path().join("arranged.devnotes"); - let first = tempfile::tempdir().unwrap(); - let mut app = App::launch_answering("21_folders_travel", first.path(), &file); - app.create_library(); - - step("a space with a folder that holds a note", || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the space is shown", |tree| tree.count("note-card") == 0); - make_folder(&mut app, UNCITED); - make_folder(&mut app, CITED); - write(&mut app, LOOSE); - app.click_where("folder-option", named(CITED)); - write(&mut app, FILED); - }); - - step("it leaves as a file", || { - menu(&mut app, "exportSpace"); - app.click("passphrase-prompt-plain"); - report(&mut app); - assert!(file.exists()); - }); - app.quit(); - - let second = tempfile::tempdir().unwrap(); - let mut app = App::launch_answering("21_folders_travel", second.path(), &file); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - - step("on the other side it arrives in its folder", || { - menu(&mut app, "import"); - report(&mut app); - app.click_where("space-option", named(SPACE)); - app.eventually("the two notes are drawn", |tree| tree.count("note-card") == 2); - let tree = app.tree(); - assert_eq!(folders_named(&tree, CITED), 1); - assert_eq!(folders_named(&tree, UNCITED), 0, "cited by nobody"); - app.click_where("folder-option", named(CITED)); - app.eventually("the folder holds its note", |tree| { - tree.count("note-card") == 1 && tree.texts("note-card-title").contains(&FILED.to_owned()) - }); - }); - - step("the same file a second time adds nothing", || { - menu(&mut app, "import"); - report(&mut app); - app.click_where("space-option", named(SPACE)); - app.eventually("still two notes", |tree| tree.count("note-card") == 2); - assert_eq!(folders_named(&app.tree(), CITED), 1); - }); - - app.quit(); -} diff --git a/e2e/tests/22_note_history.rs b/e2e/tests/22_note_history.rs deleted file mode 100644 index 29d1e970c..000000000 --- a/e2e/tests/22_note_history.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! A note's history: nothing on a note nobody has edited, one body kept per edit, newest first, -//! a preview of what going back would change, and going back, which takes that version and every -//! newer one out of the list. Nothing on a todo list. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -const TITLE: &str = "History under test"; -const LIST: &str = "List without history"; - -fn code(tree: &Tree) -> String { - tree.find("editor-body") - .and_then(|body| body.value()) - .unwrap_or_default() - .to_owned() -} - -/// The note titled `title`, found and opened from the keyboard: a list's card is mostly its -/// ticks. -fn open(app: &mut App, title: &str) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(title); - // By its title: the search before this one left a card alone too, until the debounce ends. - app.eventually("the note alone", |tree| { - tree.count("note-card") == 1 && tree.texts("note-card").contains(&title.to_owned()) - }); - app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); - app.press(Key::Enter, Modifiers::NONE); - app.wait_for("editor-title"); -} - -fn close(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); -} - -/// The code replaced by `text`, written on close. -fn rewrite(app: &mut App, text: &str) { - open(app, TITLE); - app.click("editor-body"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(text); - close(app); -} - -/// A row added to the list open, and typed in. -fn add(app: &mut App, words: &str) { - let before = app.tree().count("checklist-text"); - app.click("checklist-add"); - app.eventually("a new row has the focus", |tree| { - tree.count("checklist-text") == before + 1 && tree.focused().starts_with("checklist-text") - }); - app.type_text(words); -} - -fn todo_list_keeps_none(app: &mut App) { - app.click("new-note-kind"); - app.click("new-note-checklist"); - app.fill("editor-title", LIST); - add(app, "one"); - close(app); - open(app, LIST); - add(app, "two"); - close(app); - open(app, LIST); - assert!(!app.has("revisions-toggle")); - close(app); -} - -#[test] -fn note_history() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("22_note_history", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - step("a note nobody has edited shows no history", || { - app.click("new-note"); - app.fill("editor-title", TITLE); - app.click("editor-body"); - app.type_text("select 1"); - close(&mut app); - open(&mut app, TITLE); - assert!(!app.has("revisions-toggle")); - close(&mut app); - }); - - step("each edit keeps the body before it, newest first", || { - rewrite(&mut app, "select 2"); - rewrite(&mut app, "select 3"); - open(&mut app, TITLE); - app.click("revisions-toggle"); - app.eventually("two versions kept", |tree| tree.count("revision-open") == 2); - }); - - step("a click previews what going back would change", || { - app.click_nth("revision-open", 1); - app.wait_for("revision-diff"); - app.eventually("« select 1 » comes back, « select 3 » goes", |tree| { - let restored = tree.texts("diff-restored"); - let dropped = tree.texts("diff-dropped"); - restored.iter().any(|line| line.contains("select 1")) - && dropped.iter().any(|line| line.contains("select 3")) - }); - app.capture("revision-preview"); - }); - - step("going back puts the body in the editor, nothing newer kept", || { - app.click("revision-restore"); - app.eventually("the oldest body back", |tree| code(tree) == "select 1"); - app.eventually("nothing newer kept", |tree| !tree.has("revisions-toggle")); - close(&mut app); - open(&mut app, TITLE); - app.eventually("still the oldest body", |tree| code(tree) == "select 1"); - close(&mut app); - }); - - step("a todo list keeps no history", || { - todo_list_keeps_none(&mut app); - }); - - app.quit(); -} diff --git a/e2e/tests/23_backups.rs b/e2e/tests/23_backups.rs deleted file mode 100644 index 66cd1a5c2..000000000 --- a/e2e/tests/23_backups.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! The copies, and the one gesture that puts one back. A copy is taken at unlock, so a real -//! relaunch comes first; the last step really replaces the library, and unlocks the copy. - -use e2e::{App, PASSPHRASE, step}; -use egui::accesskit::Node; - -const LATER: &str = "Written after the copy"; - -fn security(app: &mut App) { - app.click("file-menu"); - app.click("file-preferences"); - app.click("settings-page-backups"); - app.scroll_to("settings-content", "backup-row"); -} - -/// The strip opens further down a panel that scrolls: its buttons are clicked once they are in view. -fn strip_shown(app: &mut App) { - app.eventually("the strip is in view", |tree| { - let place = |id| tree.find(id).and_then(Node::bounds); - place("backup-confirm-restore") - .zip(place("settings-cancel")) - .is_some_and(|(button, footer)| button.y1 < footer.y0) - }); -} - -fn close(app: &mut App) { - app.click("settings-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); -} - -fn unlock(app: &mut App) { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); -} - -fn is_stamped(words: &str) -> bool { - words - .split_whitespace() - .next() - .is_some_and(|stamp| stamp.len() == 19 && stamp.as_bytes()[10] == b'_') -} - -#[test] -fn backups() { - let profile = tempfile::tempdir().unwrap(); - let app = { - let mut app = App::launch("23_backups", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - app - }; - let mut app = app.relaunch(); - unlock(&mut app); - - step("the launch's copy is listed, with when and how big", || { - security(&mut app); - let detail = app.tree().text("backup-detail").unwrap_or_default(); - assert!(is_stamped(&detail), "{detail}"); - app.capture("backups"); - close(&mut app); - }); - - step("the trigger names what a restore would do, and runs none", || { - security(&mut app); - app.click("backup-restore"); - app.wait_for("backup-confirm"); - strip_shown(&mut app); - assert!(!app.has("backup-restore"), "the trigger gave way"); - assert!(app.has("settings-dialog")); - app.click("backup-cancel"); - app.eventually("the strip is gone", |tree| !tree.has("backup-confirm")); - close(&mut app); - }); - - step("it replaces the library and goes back to the gate", || { - app.click("new-note"); - app.fill("editor-title", LATER); - app.fill("editor-body", "echo later"); - app.click("editor-close"); - app.eventually("the note is a card", |tree| !tree.has("editor-title")); - - security(&mut app); - app.click("backup-restore"); - strip_shown(&mut app); - app.click("backup-confirm-restore"); - app.wait_for("vault-passphrase"); - assert!(!app.has("file-menu")); - assert!(!app.has("settings-dialog")); - app.wait_for("status-toast"); - }); - - step("the copy opens, without what was written after it", || { - unlock(&mut app); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - let titles = app.tree().texts("note-card-title"); - assert!(!titles.contains(&LATER.to_owned()), "{titles:?}"); - }); - - app.quit(); -} diff --git a/e2e/tests/24_forgotten_passphrase.rs b/e2e/tests/24_forgotten_passphrase.rs deleted file mode 100644 index 983d69d6c..000000000 --- a/e2e/tests/24_forgotten_passphrase.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! The way out of a library whose phrase is forgotten: it archives the library and leaves the -//! profile with none, which is what turns the gate into the one that asks for a new phrase. - -use e2e::{App, PASSPHRASE, step}; - -#[test] -fn forgotten_passphrase() { - let profile = tempfile::tempdir().unwrap(); - let mut first = App::launch("24_forgotten_passphrase", profile.path()); - first.create_library(); - first.eventually("the samples are drawn", |tree| tree.has("note-card")); - let mut app = first.relaunch(); - app.wait_for("vault-passphrase"); - - step("a way out is offered from under the unlock button", || { - assert!(app.has("vault-forgotten")); - }); - - step("the field gives way to what would be lost", || { - app.click("vault-forgotten"); - app.wait_for("vault-archive"); - assert!(!app.has("vault-passphrase")); - }); - - step("it goes back to the field without touching anything", || { - app.click("vault-keep-trying"); - app.wait_for("vault-passphrase"); - assert!(!app.has("vault-archive")); - }); - - step("it archives and comes back asking for a new phrase", || { - app.click("vault-forgotten"); - app.click("vault-archive-confirm"); - app.wait_for("vault-confirmation"); - app.wait_for("status-toast"); - }); - - step("a new phrase opens a new library, seeded again", || { - app.fill("vault-passphrase", PASSPHRASE); - app.fill("vault-confirmation", PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - }); - - app.quit(); -} diff --git a/e2e/tests/25_libraries.rs b/e2e/tests/25_libraries.rs deleted file mode 100644 index 04b509b92..000000000 --- a/e2e/tests/25_libraries.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Several libraries: created from the File menu and opened through the gate, each with its own -//! phrase and its own samples, a switch that asks before it loses an unsaved request, the way -//! between them from the gate itself, a deletion named before it runs, and a registry cut short -//! that loses no library. - -use e2e::{App, PASSPHRASE, Tree, step}; -use egui::{Key, Modifiers}; - -const OTHER: &str = "Boulot"; -/// Only the first library holds it, which is what tells the two rails apart. -const HOME: &str = "Maison"; - -fn panel(app: &mut App) { - app.click("file-menu"); - app.click("file-libraries"); - app.wait_for("library-row"); -} - -fn close_panel(app: &mut App) { - app.click("libraries-close"); - app.eventually("the panel is closed", |tree| !tree.has("library-row")); -} - -/// The library the gate asks for, as its menu names it. -fn gate_library(tree: &Tree) -> String { - tree.find("vault-library-switch") - .and_then(egui::accesskit::Node::value) - .unwrap_or_default() - .to_owned() -} - -fn pass_the_gate(app: &mut App) { - app.fill("vault-passphrase", PASSPHRASE); - if app.has("vault-confirmation") { - app.fill("vault-confirmation", PASSPHRASE); - } - app.click("vault-submit"); - app.wait_for("area-notes"); -} - -fn has_space(tree: &Tree, name: &str) -> bool { - tree.texts("space-option").iter().any(|row| row == name) -} - -/// A request begun in the HTTP area and left there, then back to the notes. -fn leave_a_request_unsaved(app: &mut App) { - app.press(Key::Num3, Modifiers::COMMAND); - app.click("http-tab-new"); - app.wait_for("http-url"); - app.press(Key::Num1, Modifiers::COMMAND); - app.wait_for("area-notes"); -} - -#[test] -fn libraries() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("25_libraries", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - app.click("space-create-open"); - app.fill("space-create-input", HOME); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the space is listed", |tree| has_space(tree, HOME)); - - step("the panel lists the one open, and says so", || { - panel(&mut app); - app.capture("libraries"); - let tree = app.tree(); - assert_eq!(tree.count("library-row"), 1); - assert!(tree.has("library-open")); - assert!(!tree.has("library-delete"), "the last cannot go"); - }); - - step("creating one goes straight to it, through the gate", || { - app.fill("library-new-name", OTHER); - app.click("library-create"); - app.wait_for("vault-confirmation"); - assert!(!app.has("file-menu")); - assert!(!app.has("library-row"), "the panel went with the library"); - pass_the_gate(&mut app); - }); - - step("it is a library of its own, seeded as a first launch", || { - app.eventually("its samples are drawn", |tree| tree.has("note-card")); - assert!(!has_space(&app.tree(), HOME)); - panel(&mut app); - assert_eq!(app.tree().count("library-row"), 2); - close_panel(&mut app); - }); - - step("a switch asks before it loses an unsaved request", || { - leave_a_request_unsaved(&mut app); - panel(&mut app); - app.click("library-switch"); - app.wait_for("http-leave-dialog"); - assert_eq!(app.tree().count("http-leave-name"), 1); - app.click("http-leave-cancel"); - app.eventually("the question is gone", |tree| !tree.has("http-leave-dialog")); - assert!(!app.has("vault-passphrase"), "nothing changed"); - - app.click("library-switch"); - app.click("http-leave-discard"); - app.wait_for("vault-passphrase"); - assert!(!app.has("vault-confirmation"), "this one has its phrase"); - }); - - step("the gate goes from one library to the other, and back", || { - app.click("vault-library-switch"); - app.click("vault-library-switch-1"); - app.eventually("the gate asks for the other", |tree| gate_library(tree) == OTHER); - app.click("vault-library-switch"); - app.click("vault-library-switch-0"); - app.eventually("the gate asks for the first", |tree| { - tree.has("vault-library-switch") && gate_library(tree) != OTHER - }); - }); - - step("what was left there is found", || { - pass_the_gate(&mut app); - app.eventually("its own spaces are listed", |tree| has_space(tree, HOME)); - }); - - step("a deletion is named before it takes anything", || { - panel(&mut app); - app.click("library-delete"); - app.wait_for("library-confirm"); - let said = app.tree().text("library-confirm").unwrap_or_default(); - assert!(said.contains(OTHER), "{said}"); - assert_eq!(app.tree().count("library-row"), 2); - app.click("library-confirm-delete"); - app.eventually("the library is erased", |tree| tree.count("library-row") == 1); - }); - - step("the one that is left offers no deletion", || { - assert!(!app.has("library-delete")); - close_panel(&mut app); - }); - - app.quit(); - let registry = profile.path().join("libraries.json"); - let whole = std::fs::read(®istry).unwrap(); - std::fs::write(®istry, &whole[..whole.len() / 2]).unwrap(); - let mut app = App::launch("25_libraries", profile.path()); - - step("a registry cut short still opens on the library", || { - app.wait_for("vault-passphrase"); - assert!(!app.has("vault-confirmation"), "not taken for a first launch"); - pass_the_gate(&mut app); - app.eventually("its own spaces are listed", |tree| has_space(tree, HOME)); - }); - - app.quit(); -} diff --git a/e2e/tests/26_formatting.rs b/e2e/tests/26_formatting.rs deleted file mode 100644 index c7d7a62f4..000000000 --- a/e2e/tests/26_formatting.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! Formatting a snippet with Prettier: the button formats the sample written on one line and its -//! notice undoes it, Shift+Alt+F formats from the title and the result is kept, a syntax error -//! is said, the library's settings change the style, and a language Prettier does not read -//! leaves the button disabled. The samples are found by their code, which no translation touches. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -fn code(tree: &Tree) -> String { - tree.find("editor-body") - .and_then(|body| body.value()) - .unwrap_or_default() - .to_owned() -} - -fn notice(tree: &Tree) -> Option { - tree.find("editor-format-notice") - .and_then(|notice| notice.description()) - .map(str::to_owned) -} - -fn open(app: &mut App, found_by: &str) { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Backspace, Modifiers::NONE); - // Until the search's debounce, the previous search's one card passes for this one. - app.eventually("every note listed", |tree| tree.count("note-card") > 1); - app.type_text(found_by); - app.eventually("the sample alone", |tree| tree.count("note-card") == 1); - app.click("note-card-open"); - app.wait_for("editor-body"); -} - -fn close(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); -} - -#[test] -fn formatting() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("26_formatting", profile.path()); - app.create_library(); - app.wait_for("note-card"); - open(&mut app, "withRetry"); - - step("the button formats, marks the lines and says so", || { - app.click("editor-format"); - app.eventually("the code on several lines", |tree| { - code(tree).lines().count() > 5 && notice(tree).as_deref() == Some("formatted") - }); - }); - - step("its notice takes the format back", || { - app.click("editor-format-undo"); - app.eventually("the code on one line again", |tree| code(tree).lines().count() == 1); - }); - - step("Shift+Alt+F formats from the title, and it is kept", || { - app.click("editor-title"); - app.press(Key::F, Modifiers::SHIFT | Modifiers::ALT); - app.eventually("formatted", |tree| code(tree).lines().count() > 5); - // Here and not before the undo: a slow capture outlasts the notice it would click. - app.capture("formatted"); - close(&mut app); - open(&mut app, "withRetry"); - assert!( - app.tree() - .find("editor-body") - .is_some_and(|body| { body.value().unwrap_or_default().lines().count() > 5 }) - ); - }); - - step("the library's indentation is the next format's", || { - app.click("editor-format-settings"); - app.click("prettier-indentation-2"); - app.press(Key::Escape, Modifiers::NONE); - app.click("editor-format"); - app.eventually("four spaces a level", |tree| { - code(tree) - .lines() - .any(|line| line.starts_with(" ") && !line.starts_with(" ")) - }); - }); - - step("format on save is named beside its switch, and turns", || { - let on = |tree: &Tree| { - tree.find("prettier-formatOnSave").and_then(egui::accesskit::Node::toggled) - == Some(egui::accesskit::Toggled::True) - }; - app.click("editor-format-settings"); - app.wait_for("prettier-formatOnSave"); - let tree = app.tree(); - assert!(!on(&tree)); - let label = tree.text("prettier-formatOnSave").unwrap_or_default(); - assert!(!label.is_empty() && tree.mentions(&label)); - app.capture("format-settings"); - app.click("prettier-formatOnSave"); - app.eventually("on", on); - app.click("prettier-formatOnSave"); - app.eventually("off again", |tree| !on(tree)); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("closed", |tree| !tree.has("prettier-formatOnSave")); - }); - - step("a syntax error is said, and nothing changes", || { - app.click("editor-body"); - app.press(Key::End, Modifiers::COMMAND); - app.type_text(")"); - let typed = code(&app.tree()); - app.click("editor-format"); - app.eventually("the error said", |tree| notice(tree).as_deref() == Some("syntax")); - assert_eq!(code(&app.tree()), typed); - close(&mut app); - }); - - step("a language Prettier does not read leaves the button disabled", || { - open(&mut app, "5432"); - assert!(app.tree().find("editor-format").is_some_and(egui::accesskit::Node::is_disabled)); - close(&mut app); - }); - - app.quit(); -} diff --git a/e2e/tests/27_json_explorer.rs b/e2e/tests/27_json_explorer.rs deleted file mode 100644 index 0c1caacd2..000000000 --- a/e2e/tests/27_json_explorer.rs +++ /dev/null @@ -1,147 +0,0 @@ -//! A JSON snippet explored: the band says it parses, the graph draws its nodes and selects one -//! with its path, a row closes and opens its container, the arrows walk, everything folds and -//! opens again, a match is stepped to and shown in the code, the tree folds, the code and the -//! graph side by side select in each other. The sample used is found by its code, and every -//! entry by its path, which no translation touches. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -fn selected(tree: &Tree) -> String { - tree.text("json-selected-path").unwrap_or_default() -} - -fn nodes(tree: &Tree) -> usize { - tree.count("json-node-head") -} - -fn at(path: &'static str) -> impl Fn(&egui::accesskit::Node) -> bool { - move |node| node.description() == Some(path) -} - -fn invalid(tree: &Tree) -> bool { - tree.find("editor-json-validity").is_some_and(|node| node.invalid().is_some()) -} - -#[test] -fn json_explorer() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("27_json_explorer", profile.path()); - app.create_library(); - app.wait_for("note-card"); - // The notes header stays above an expanded note: the graph is given its height back. - app.resize(1_100, 900); - app.fill("search-input", "p95Ms"); - app.eventually("the JSON sample, alone", |tree| tree.count("note-card") == 1); - - step("the band says the draft parses, over its code", || { - app.click("note-card-open"); - app.wait_for("editor-json-validity"); - // The whole graph wants the whole area, not the panel beside the cards. - app.click("editor-fullscreen"); - app.eventually("the draft read as valid", |tree| !invalid(tree)); - }); - - step("the graph draws the document and selects a node", || { - app.click("editor-view-graph"); - app.wait_for("json-node-head"); - app.click("json-fit"); - app.eventually("every node", |tree| nodes(tree) == 6); - app.click_where("json-node-head", at("$.owner")); - app.eventually("its path said", |tree| selected(tree) == "$.owner"); - app.capture("graph"); - }); - - step("a row closes and opens its container", || { - app.click_where("json-row", at("$.endpoints")); - app.eventually("the endpoints closed", |tree| nodes(tree) == 2); - app.click_where("json-row", at("$.endpoints")); - app.eventually("one level open again", |tree| nodes(tree) == 3); - }); - - step("the arrows walk the rows", || { - app.click_where("json-node-head", at("$")); - app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the first row", |tree| selected(tree) == "$.service"); - }); - - step("everything folds and opens, the selection falling back and coming back", || { - app.click("json-open-all"); - app.eventually("every node", |tree| nodes(tree) == 6); - app.click_where("json-row", at("$.owner.team")); - app.click("json-collapse-all"); - app.eventually("the root alone", |tree| nodes(tree) == 1); - app.eventually("the row still drawn", |tree| selected(tree) == "$.owner"); - app.click("json-open-all"); - app.eventually("back where it was", |tree| selected(tree) == "$.owner.team"); - }); - - step("a match is stepped to and shown in the code", || { - app.fill("json-search", "ONCALL"); - app.eventually("one match", |tree| tree.text("json-match-count").as_deref() == Some("1")); - app.click("json-match-next"); - app.eventually("the match selected", |tree| selected(tree) == "$.owner.onCall"); - app.click("json-show-in-code"); - app.eventually("back to the code", |tree| tree.has("editor-body") && !tree.has("json-node-head")); - }); - - step("the tree folds a container", || { - app.click("editor-view-tree"); - app.click_where("json-line", at("$.owner")); - app.eventually("the owner folded", |tree| { - tree.all("json-line") - .into_iter() - .any(|line| at("$.owner")(line) && line.is_expanded() == Some(false)) - }); - app.capture("tree"); - }); - - side_by_side(&mut app); - broken_draft(&mut app); - app.quit(); -} - -/// The code and the graph side by side, selecting in each other; the code hidden; too narrow. -fn side_by_side(app: &mut App) { - step("side by side the code and the graph select in each other", || { - app.click("editor-view-graph"); - app.click("editor-side-by-side"); - app.eventually("the graph beside the code", |tree| { - tree.has("side-by-side") && tree.has("side-by-side-code") - }); - app.click("editor-body"); - app.press(Key::Home, Modifiers::COMMAND); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::End, Modifiers::NONE); - app.press(Key::ArrowLeft, Modifiers::NONE); - app.press(Key::ArrowLeft, Modifiers::NONE); - app.eventually("the value under the caret", |tree| selected(tree) == "$.service"); - app.capture("side-by-side"); - - app.click("editor-hide-code"); - app.eventually("the graph alone", |tree| !tree.has("side-by-side")); - app.click("editor-hide-code"); - app.wait_for("side-by-side"); - app.resize(720, 700); - app.wait_for("editor-side-by-side-narrow"); - assert!(!app.has("side-by-side"), "too narrow, it is not squeezed"); - app.resize(1_100, 900); - app.wait_for("side-by-side"); - app.click("editor-side-by-side"); - app.eventually("one at a time again", |tree| !tree.has("side-by-side")); - }); -} - -fn broken_draft(app: &mut App) { - step("a broken draft says where it breaks", || { - app.click("editor-view-code"); - app.click("editor-body"); - app.press(Key::End, Modifiers::COMMAND); - app.type_text(",,"); - app.eventually("the draft refused", invalid); - app.click("editor-view-graph"); - app.wait_for("json-invalid"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - }); -} diff --git a/e2e/tests/28_areas.rs b/e2e/tests/28_areas.rs deleted file mode 100644 index c7940ca81..000000000 --- a/e2e/tests/28_areas.rs +++ /dev/null @@ -1,181 +0,0 @@ -//! The three areas: reached from the bar and by `Ctrl+1/2/3` read by position, each keeping its -//! state, the window reopening on the last one, and a key moved in the preferences. - -use e2e::{App, PASSPHRASE, step}; -use egui::{Key, Modifiers}; - -fn tools(app: &mut App) { - app.press(Key::Num2, Modifiers::COMMAND); - app.wait_for("area-tools"); -} - -fn notes(app: &mut App) { - app.press(Key::Num1, Modifiers::COMMAND); - app.wait_for("area-notes"); -} - -fn shortcuts(app: &mut App) { - app.click("file-menu"); - app.click("file-preferences"); - app.click("settings-page-shortcuts"); - app.wait_for("shortcut-field-palette"); -} - -fn close_preferences(app: &mut App) { - app.click("settings-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); -} - -fn reach(app: &mut App, author_id: &str) { - app.scroll_above("settings-content", author_id, "settings-cancel"); -} - -fn value_of(app: &mut App, author_id: &str) -> String { - let tree = app.tree(); - let node = tree.find(author_id); - node.and_then(egui::accesskit::Node::value).unwrap_or_default().to_owned() -} - -fn palette_key_shows(app: &mut App, said: &str) { - app.eventually(&format!("the palette's field shows {said}"), |tree| { - tree.find("shortcut-field-palette").and_then(egui::accesskit::Node::value) == Some(said) - }); -} - -/// AZERTY's Q, where QWERTY's A stands: macOS hears the place, the others the letter. -fn another_layout(app: &mut App) { - step("a key of another layout is kept as the system will hear it", || { - app.click("shortcut-field-palette"); - app.press_laid_out(Key::Q, Key::A, Modifiers::COMMAND | Modifiers::ALT); - let heard = if cfg!(target_os = "macos") { "Ctrl+Alt+A" } else { "Ctrl+Alt+Q" }; - palette_key_shows(app, heard); - app.click("shortcut-reset-palette"); - palette_key_shows(app, "Ctrl+Alt+P"); - }); -} - -/// The sidebar toggle's box in the area shown, once it holds still. -fn toggle_box(app: &mut App, author_id: &str) -> (f64, f64, f64, f64) { - app.at_rest(author_id); - let tree = app.tree(); - let bounds = tree - .find(author_id) - .and_then(egui::accesskit::Node::bounds) - .expect("the toggle is drawn"); - (bounds.x0, bounds.y0, bounds.x1, bounds.y1) -} - -/// The toggle stands at one place in the three areas. -fn one_toggle_place(app: &mut App) { - let same = |a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)| { - [a.0 - b.0, a.1 - b.1, a.2 - b.2, a.3 - b.3].iter().all(|gap| gap.abs() < 0.5) - }; - step("the sidebar toggle stands at one place in every area", || { - let notes = toggle_box(app, "library-rail-toggle"); - app.click("area-option-tools"); - let tools = toggle_box(app, "tools-rail-toggle"); - assert!(same(tools, notes), "{tools:?} in the tools, {notes:?} in the notes"); - app.click("area-option-http"); - let http = toggle_box(app, "http-rail-toggle"); - assert!(same(http, notes), "{http:?} in HTTP, {notes:?} in the notes"); - app.click("area-option-notes"); - app.wait_for("area-notes"); - }); -} - -#[test] -fn areas() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("28_areas", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - - step("the bar goes to the tools, and back", || { - app.click("area-option-tools"); - app.wait_for("area-tools"); - assert!(!app.has("canvas")); - app.click("area-option-notes"); - app.wait_for("area-notes"); - }); - - one_toggle_place(&mut app); - - step("the keys go there too, and the notes keep their search", || { - app.click("search-input"); - app.type_text("zzz-nothing-matches"); - app.eventually("nothing matches", |tree| !tree.has("note-card")); - tools(&mut app); - notes(&mut app); - app.eventually("the search is as it was", |tree| !tree.has("note-card")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the search is off", |tree| tree.has("note-card")); - }); - - step("what the native side asks comes back to the notes", || { - tools(&mut app); - app.act("new-note"); - app.wait_for("editor-title"); - app.click("editor-close"); - app.eventually("the editor closed", |tree| !tree.has("editor-title")); - assert!(app.has("area-notes")); - }); - - step("a global key is refused without a modifier", || { - shortcuts(&mut app); - let before = value_of(&mut app, "shortcut-field-palette"); - app.click("shortcut-field-palette"); - app.press(Key::P, Modifiers::NONE); - app.wait_for("shortcut-error-palette"); - assert_eq!(value_of(&mut app, "shortcut-field-palette"), before); - }); - - step("a key another action holds is refused by its name", || { - app.press(Key::N, Modifiers::COMMAND | Modifiers::ALT); - app.eventually("the refusal names the key", |tree| { - tree.text("shortcut-error-palette") - .is_some_and(|said| said.contains("Ctrl+Alt+N")) - }); - }); - - step("a free one is taken, and put back", || { - app.press(Key::J, Modifiers::COMMAND | Modifiers::ALT); - palette_key_shows(&mut app, "Ctrl+Alt+J"); - app.click("shortcut-reset-palette"); - palette_key_shows(&mut app, "Ctrl+Alt+P"); - }); - - another_layout(&mut app); - - step("Escape ends the listening, not the panel", || { - reach(&mut app, "shortcut-field-canvas.pin"); - app.click("shortcut-field-canvas.pin"); - // The field keeps Escape from the frame after it took the focus: `has` settles. - assert!(app.has("settings-dialog")); - app.press(Key::Escape, Modifiers::NONE); - assert!(app.has("settings-dialog")); - }); - - step("a canvas key takes a bare letter, and the canvas answers", || { - reach(&mut app, "shortcut-field-canvas.check"); - app.click("shortcut-field-canvas.check"); - app.press(Key::J, Modifiers::NONE); - app.eventually("the field shows it", |tree| { - tree.find("shortcut-field-canvas.check").and_then(egui::accesskit::Node::value) == Some("J") - }); - close_preferences(&mut app); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::J, Modifiers::NONE); - app.wait_for("selection-count"); - }); - - tools(&mut app); - let mut app = app.relaunch(); - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - - step("the window reopens on the area it was left in", || { - app.wait_for("area-tools"); - }); - - app.quit(); -} diff --git a/e2e/tests/29_tools.rs b/e2e/tests/29_tools.rs deleted file mode 100644 index b7e27d96c..000000000 --- a/e2e/tests/29_tools.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! The tools' home: reached from the notes on its shortcut, its search finding a tool by a keyword, -//! the tool opened from the keyboard, its star and its place among the recent ones over a relaunch. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -fn search_is_focused(tree: &Tree) -> bool { - tree.focused().contains("tools-search") -} - -fn home(app: &mut App) { - step("the home opens on its search from the notes", || { - app.press(Key::T, Modifiers::COMMAND | Modifiers::SHIFT); - app.wait_for("area-tools"); - app.eventually("the search takes the focus", search_is_focused); - }); - step("a keyword narrows the catalogue", || { - app.fill("tools-search", "crlf"); - app.wait_for("tools-entry-line-breaks"); - app.eventually("the others are gone", |tree| tree.find("tools-entry-hash").is_none()); - app.press(Key::Escape, Modifiers::NONE); - app.wait_for("tools-entry-hash"); - }); -} - -fn a_tool(app: &mut App) { - step("Enter opens the first result, in its frame", || { - app.fill("tools-search", "cron"); - app.wait_for("tools-first-result"); - app.press(Key::Enter, Modifiers::NONE); - app.wait_for("tool-title"); - app.wait_for("tools-rail-tool-zones"); - }); - step("its star files it under the favourites", || { - app.click("tool-favourite"); - app.wait_for("tools-rail-favourites"); - }); - step("Ctrl+K goes back to the search", || { - app.press(Key::K, Modifiers::COMMAND); - app.eventually("the search takes the focus", search_is_focused); - app.press(Key::Escape, Modifiers::NONE); - app.wait_for("tools-favourite-cron"); - }); -} - -fn text_tools(app: &mut App) { - step("the case converter answers what is typed", || { - app.click("tools-entry-case"); - app.wait_for("tool-title"); - app.fill("case-input", "parse URL"); - app.eventually("the cases are shown", |tree| { - tree.texts("output-value").iter().any(|it| it == "parse_url") - }); - }); - step("the diff compares two texts", || { - app.click("tools-rail-tool-diff"); - app.fill("text-diff-a", "one"); - app.fill("text-diff-b", "two"); - app.wait_for("text-diff-rows"); - app.click("tool-clear"); - app.click("tool-back"); - }); -} - -/// By the search: the catalogue is longer than the window. -fn open_tool(app: &mut App, tool: &str) { - app.fill("tools-search", tool); - app.eventually("the catalogue is narrowed", |tree| !tree.has("tools-entry-hash")); - app.click(&format!("tools-entry-{tool}")); - app.wait_for("tool-title"); -} - -/// With the search let go: what it holds stays on the home. -fn back_to_the_home(app: &mut App) { - app.click("tool-back"); - app.click("tools-search"); - app.press(Key::Escape, Modifiers::NONE); - app.wait_for("tools-entry-hash"); -} - -fn data_tools(app: &mut App) { - step("a document is converted, and the swap brings it back", || { - open_tool(app, "convert"); - app.fill("convert-input", r#"{"service":"billing"}"#); - app.eventually("the YAML is shown", |tree| { - tree.text("convert-output").is_some_and(|it| it.contains("service: billing")) - }); - app.click("convert-swap"); - app.eventually("the JSON is back", |tree| { - tree.text("convert-output").is_some_and(|it| it.contains('{')) - }); - back_to_the_home(app); - }); - step("a seed brings the same person back", || { - open_tool(app, "identity"); - app.wait_for("identity-card"); - let drawn = app.tree().text("identity-surname"); - app.fill("identity-seed", "devnotes"); - app.wait_for("identity-seed-pinned"); - app.eventually("the seed's person is on the card", |tree| tree.text("identity-surname") != drawn); - let surname = app.tree().text("identity-surname"); - retype(app, "identity-seed", "another"); - app.eventually("another person is drawn", |tree| tree.text("identity-surname") != surname); - retype(app, "identity-seed", "devnotes"); - app.eventually("the first person is back", |tree| tree.text("identity-surname") == surname); - back_to_the_home(app); - }); - step("a code is drawn from a URL", || { - open_tool(app, "qr"); - app.fill("qr-url", "https://exemple.fr/doc"); - app.wait_for("qr-code"); - back_to_the_home(app); - }); -} - -fn references(app: &mut App) { - step("a code no tool answers is found in the references", || { - app.fill("tools-search", "418"); - app.wait_for("tools-references"); - app.wait_for("tools-first-result"); - assert!(!app.has("tools-no-match")); - app.press(Key::Enter, Modifiers::NONE); - app.wait_for("reference-search"); - app.eventually("the table is whole, its own search empty", |tree| { - tree.count("reference-row") > 3 - && tree.find("reference-search").and_then(Node::value) != Some("418") - }); - back_to_the_home(app); - }); - step("the rest of a reference opens it searched", || { - app.fill("tools-search", "cors"); - app.click("tools-reference-more"); - app.eventually("the reference is searched for it", |tree| { - tree.find("reference-search").and_then(Node::value) == Some("cors") - }); - back_to_the_home(app); - }); -} - -fn remembered(mut app: App) -> App { - step("the star and the recent tools come back", || { - app.click("tools-entry-case"); - app.wait_for("tool-title"); - }); - let mut app = app.relaunch(); - step("over a relaunch", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("tools-favourite-cron"); - app.wait_for("tools-recent-case"); - let tree = app.tree(); - assert!(tree.text("tools-count").is_some_and(|words| words.contains("32"))); - }); - app -} - -/// Over what the field holds: `fill` types at the caret, and a second click only selects the -/// word when it comes within the double click's delay, which is the machine's speed. -fn retype(app: &mut App, author_id: &str, text: &str) { - app.click(author_id); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(text); -} - -#[test] -fn tools_home() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("29_tools", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - home(&mut app); - a_tool(&mut app); - text_tools(&mut app); - data_tools(&mut app); - references(&mut app); - remembered(app).quit(); -} diff --git a/e2e/tests/30_http.rs b/e2e/tests/30_http.rs deleted file mode 100644 index 57ec05072..000000000 --- a/e2e/tests/30_http.rs +++ /dev/null @@ -1,350 +0,0 @@ -//! The HTTP area: a collection begun from the empty rail, a folder and requests made from a row's -//! menu, a request moved with the keys, renamed in place, a fold kept across a relaunch, and the -//! collection deleted once the rail has said what goes with it. A request opens in its tab, -//! reopened at the next launch in the order the tabs were dragged to; a draft asks before it is -//! closed, by its × or the middle button. A body is read as it is typed, -//! and a GraphQL draft names the variables it lacks. -//! -//! Rows are read by their names, which the scenario types: the window speaks the system's -//! language. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers, PointerButton, Pos2}; - -const API: &str = "API Paiements"; - -/// The rail's rows, top to bottom: a request after its method. -fn rows(tree: &Tree) -> Vec { - tree.texts("http-node-name") -} - -fn ends(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label().is_some_and(|label| label.ends_with(name)) -} - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -fn create(app: &mut App, name: &str) { - app.fill("http-create-input", name); - app.press(Key::Enter, Modifiers::NONE); -} - -/// A row's `⋯`, then an entry of its menu, a sub-menu's through its parent. -fn choose(app: &mut App, row: &str, entries: &[&str]) { - app.click_where("http-node-menu", ends(row)); - for entry in entries { - app.click(entry); - } -} - -fn organise(app: &mut App) { - step("a collection begun from the empty rail", || { - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-rail-empty"); - app.click("http-rail-empty-create"); - create(app, API); - app.eventually("the collection is listed", |tree| rows(tree) == [API]); - }); - step("a folder and two requests made from the rows' menus", || { - choose(app, API, &["http-node-new-folder"]); - create(app, "Auth"); - app.eventually("the folder is listed", |tree| rows(tree) == [API, "Auth"]); - choose(app, "Auth", &["http-node-new", "http-node-new-http"]); - create(app, "Login"); - app.eventually("the request is listed", |tree| rows(tree) == [API, "Auth", "GET Login"]); - choose(app, "Auth", &["http-node-new", "http-node-new-websocket"]); - create(app, "Flux"); - app.eventually("the socket is listed", |tree| rows(tree) == [API, "Auth", "GET Login", "WS Flux"]); - }); - step("a request moved with the keys, then out of its folder", || { - app.click_where("http-node-name", named("WS Flux")); - app.press(Key::ArrowUp, Modifiers::ALT); - app.eventually("the socket is first", |tree| rows(tree) == [API, "Auth", "WS Flux", "GET Login"]); - app.eventually("the move is said", |tree| { - tree.text("http-rail-moved").is_some_and(|said| said.contains("Login")) - }); - app.press(Key::ArrowLeft, Modifiers::ALT); - app.eventually("the socket is at the collection's root", |tree| { - rows(tree) == [API, "Auth", "GET Login", "WS Flux"] - }); - // Nothing is above a folder's first request but its folder: refused, and said. - app.click_where("http-node-name", named("GET Login")); - app.press(Key::ArrowRight, Modifiers::ALT); - app.eventually("the refusal is said", |tree| { - tree.text("http-rail-moved").is_some_and(|said| said.contains("Login")) - }); - }); - step("a request renamed in place, the field left", || { - app.click_where("http-node-name", named("WS Flux")); - app.press(Key::F2, Modifiers::NONE); - app.wait_for("http-rename-input"); - app.press(Key::End, Modifiers::NONE); - app.type_text(" live"); - app.click("http-rail-title"); - app.eventually("the new name is read back", |tree| { - rows(tree).contains(&"WS Flux live".to_owned()) && !tree.has("http-rename-input") - }); - }); -} - -fn tabs(tree: &Tree) -> Vec { - tree.texts("http-tab-open") -} - -/// The open tabs, in no order: a request clicked in the rail opens, the rows moved above too. -fn open(tree: &Tree) -> Vec { - let mut open = tabs(tree); - open.sort(); - open -} - -fn in_tabs(app: &mut App) { - step("a request opens in its tab, and a draft asks before it closes", || { - app.click_where("http-node-name", named("GET Login")); - app.eventually("the requests clicked have their tabs", |tree| { - open(tree) == ["GET Login", "WS Flux live"] - }); - app.click("http-tab-new"); - app.eventually("a draft opens beside them", |tree| tabs(tree).len() == 3); - app.click_nth("http-tab-close", 2); - app.wait_for("http-close-dialog"); - app.click("http-close-discard"); - app.eventually("the draft is gone", |tree| { - open(tree) == ["GET Login", "WS Flux live"] && !tree.has("http-close-dialog") - }); - }); -} - -/// The first tab dragged past the second, kept so after the relaunch; the middle button closes a -/// tab, asking first when it holds a draft. The order is answered by name: what was typed in a -/// tab is not reopened. -fn tabs_moved(app: &mut App) -> Vec { - let mut order = Vec::new(); - step("a tab dragged past the other takes its place", || { - let tree = app.tree(); - let before = tabs(&tree); - let bounds: Vec<_> = tree.all("http-tab-open").into_iter().filter_map(Node::bounds).collect(); - let [first, second, ..] = bounds[..] else { - panic!("two tabs at least: {before:?}"); - }; - #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let at = |x: f64, rect: &egui::accesskit::Rect| { - Pos2::new(x as f32, f64::midpoint(rect.y0, rect.y1) as f32) - }; - let (from, to) = (at(first.x0 + 20.0, &first), at(second.x1, &second)); - app.drag(from, to, PointerButton::Primary); - order = before; - order.swap(0, 1); - app.eventually("the first two swapped", |tree| tabs(tree) == order); - }); - step("the middle button on a draft asks, then closes it", || { - app.click("http-tab-new"); - app.eventually("a draft opens beside them", |tree| tabs(tree).len() == order.len() + 1); - let draft = app.tree().texts("http-tab-open")[order.len()].clone(); - app.click_with("http-tab-open", PointerButton::Middle, named(&draft)); - app.wait_for("http-close-dialog"); - app.click("http-close-discard"); - app.eventually("the draft is gone", |tree| tabs(tree) == order && !tree.has("http-close-dialog")); - }); - order - .iter() - .map(|tab| tab.split(',').next().unwrap_or_default().to_owned()) - .collect() -} - -/// What the fields wearing `author_id` hold, top to bottom. -fn values(tree: &Tree, author_id: &str) -> Vec { - tree.all(author_id) - .into_iter() - .map(|node| node.value().unwrap_or_default().to_owned()) - .collect() -} - -/// Typed at the end of what a field holds. -fn append(app: &mut App, author_id: &str, words: &str) { - app.click(author_id); - app.press(Key::End, Modifiers::NONE); - app.type_text(words); -} - -fn compose(app: &mut App) { - step("the query and its table kept in step, a header split, Ctrl+S", || { - app.click_where("http-tab-open", named("GET Login")); - app.wait_for("http-url"); - append(app, "http-url", "?page=2&q=x"); - app.eventually("the table follows the URL", |tree| values(tree, "http-kv-key") == ["page", "q", ""]); - app.click_nth("http-kv-enabled", 0); - app.eventually("the URL follows the table", |tree| { - tree.find("http-url").and_then(Node::value).is_some_and(|url| url == "?q=x") - }); - app.click("http-section-headers"); - app.wait_for("http-implied-headers"); - app.click_nth("http-kv-key", 0); - app.type_text("Accept: application/json"); - app.eventually("the header is split into its two cells", |tree| { - values(tree, "http-kv-key").first().map(String::as_str) == Some("Accept") - && values(tree, "http-kv-value").first().map(String::as_str) == Some("application/json") - }); - app.press(Key::S, Modifiers::COMMAND); - app.eventually("the tab is saved", |tree| tabs(tree).contains(&"GET Login".to_owned())); - }); -} - -fn send(app: &mut App) { - step("sent from Rust on Ctrl+Enter: its status, time, size and body, then cleared", || { - let port = e2e::serve(); - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(&format!("http://127.0.0.1:{port}/json")); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the answer is shown", |tree| { - tree.text("http-response-status").as_deref() == Some("200 OK") - && tree.has("http-response-time") - && tree.has("http-response-size") - && tree.text("http-response-pretty").is_some_and(|body| body.contains("Ada")) - }); - app.click("http-response-section-timeline"); - app.eventually("the exchange is shown", |tree| { - tree.text("http-response-sent") - .is_some_and(|sent| sent.starts_with("GET http://127.0.0.1")) - }); - app.click("http-response-clear"); - app.wait_for("http-response-idle"); - }); - step("the send in the history, read again, then reopened", || { - app.click("http-history-open"); - app.wait_for("http-history-item"); - app.click("http-history-item"); - app.wait_for("http-history-url"); - app.eventually("it reads like an answer", |tree| { - tree.text("http-response-status").as_deref() == Some("200 OK") - }); - app.click("http-history-reopen"); - app.wait_for("http-history-replace"); - app.click("http-history-replace-confirm"); - app.wait_for("http-url"); - app.eventually("the page has gone", |tree| !tree.has("http-history")); - }); - step("the cookie the answer set, in the jar, then thrown away", || { - app.click("http-cookies-open"); - app.eventually("the cookie is listed", |tree| tree.text("http-cookie").as_deref() == Some("session")); - app.click("http-cookie-remove"); - app.wait_for("http-cookies-empty"); - app.click("http-cookies-close"); - app.eventually("the jar is closed", |tree| !tree.has("http-cookies-dialog")); - }); -} - -fn bodies(app: &mut App) { - step("a JSON body read as it is typed, said on a GET, taken back to none", || { - app.click("http-section-body"); - app.click("http-body-kind-1"); - app.fill("http-body-text", "{\"amount\":4900}"); - app.eventually("the body reads and its type is said", |tree| { - tree.has("http-body-valid") - && tree - .text("http-body-type") - .is_some_and(|said| said.contains("application/json")) - }); - app.wait_for("http-body-unusual"); - app.wait_for("http-body-unusual-mark"); - app.click("http-body-to-none"); - app.eventually("no body, no warning", |tree| { - !tree.has("http-body-unusual") && !tree.has("http-body-text") - }); - }); - step("a GraphQL draft: its variable named, then added", || { - app.click("http-tab-new-kind"); - app.click("http-new-kind-graphql"); - app.fill("http-graphql-query", "query One($code: ID!) { product(code: $code) { id } }"); - app.wait_for("http-graphql-missing"); - app.click("http-graphql-add"); - app.eventually("the variable has its null", |tree| { - !tree.has("http-graphql-missing") - && values(tree, "http-graphql-variables") - .first() - .is_some_and(|text| text.contains("\"code\": null")) - }); - app.click_nth("http-tab-close", 2); - app.wait_for("http-close-dialog"); - app.click("http-close-discard"); - app.eventually("the draft is gone", |tree| tabs(tree).len() == 2); - }); -} - -fn socket(app: &mut App) { - step("a socket connected, a message echoed, then disconnected", || { - let port = e2e::serve_socket(); - app.click_where("http-tab-open", named("WS Flux live")); - app.wait_for("http-socket-message"); - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(&format!("ws://127.0.0.1:{port}/")); - app.click("http-socket-connect"); - app.eventually("the socket is open", |tree| tree.count("http-socket-entry") == 1); - app.fill("http-socket-message", "ping"); - // A key overtakes what is still being typed: it would reach the area, not the message. - app.eventually("the message is typed", |tree| { - values(tree, "http-socket-message").first().map(String::as_str) == Some("ping") - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the message came back", |tree| tree.count("http-socket-entry") == 3); - app.click("http-socket-connect"); - app.eventually("the socket is closed", |tree| tree.count("http-socket-entry") == 4); - app.press(Key::S, Modifiers::COMMAND); - }); -} - -fn fold_kept(app: App, order: &[String]) -> App { - let mut app = app; - step("a folder folded, still folded after a relaunch", || { - app.click_where("http-node-twisty", ends("Auth")); - app.eventually("the folder is folded", |tree| rows(tree) == [API, "Auth", "WS Flux live"]); - }); - let mut app = app.relaunch_discarding(); - step("unlocked again, the HTTP area shows the fold", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-http"); - app.eventually("the fold and the tab are kept", |tree| { - rows(tree) == [API, "Auth", "WS Flux live"] && tabs(tree) == order - }); - }); - app -} - -fn delete(app: &mut App) { - step("the collection deleted after saying what goes with it", || { - choose(app, API, &["http-node-delete"]); - app.wait_for("http-delete-count"); - app.click("http-delete-cancel"); - app.eventually("cancel keeps it", |tree| !tree.has("http-delete-confirm") && rows(tree).len() == 3); - choose(app, API, &["http-node-delete"]); - app.click("http-delete-submit"); - app.eventually("the rail is empty again", |tree| { - rows(tree).is_empty() && tree.has("http-rail-empty") && tabs(tree).is_empty() - }); - }); -} - -#[test] -fn http() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("30_http", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - organise(&mut app); - in_tabs(&mut app); - compose(&mut app); - send(&mut app); - bodies(&mut app); - socket(&mut app); - let order = tabs_moved(&mut app); - let mut app = fold_kept(app, &order); - delete(&mut app); - app.quit(); -} diff --git a/e2e/tests/31_http_environments.rs b/e2e/tests/31_http_environments.rs deleted file mode 100644 index d79541b3b..000000000 --- a/e2e/tests/31_http_environments.rs +++ /dev/null @@ -1,168 +0,0 @@ -//! The environment a request is sent with, and what a request sets for itself: the picker with no -//! environment yet, an auth and a setting saved and read back after a relaunch, then an -//! environment made, its secret kept, and the question it asks once protected. - -use e2e::{App, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -const API: &str = "API Paiements"; - -fn ends(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label().is_some_and(|label| label.ends_with(name)) -} - -fn create(app: &mut App, name: &str) { - app.fill("http-create-input", name); - app.press(Key::Enter, Modifiers::NONE); -} - -fn a_request(app: &mut App) { - step("a collection and a request to work on", || { - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-rail-empty"); - app.click("http-rail-empty-create"); - create(app, API); - app.wait_for("http-node-menu"); - app.click_where("http-node-menu", ends(API)); - app.click("http-node-new"); - app.click("http-node-new-http"); - create(app, "Login"); - app.eventually("the request is listed", |tree| tree.texts("http-node-name").len() == 2); - app.click_where("http-node-name", ends("Login")); - app.wait_for("http-url"); - }); -} - -fn picker(app: &mut App) { - step("the picker offers the globals alone", || { - app.click("http-environment-picker"); - app.eventually("one entry, none", |tree| tree.count("http-environment-option") == 1); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("it closes", |tree| !tree.has("http-environment-option")); - }); -} - -fn own_parts(app: &mut App) { - step("an inherited auth said, a token and a timeout set, Ctrl+S", || { - app.click("http-section-auth"); - app.wait_for("http-auth-inherited"); - app.click("http-auth-kind"); - app.click("http-auth-kind-3"); - app.fill("http-auth-secret", "s3cret"); - app.click("http-section-settings"); - app.fill("http-transport-timeoutMs", "5000"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the field is settled", |tree| { - tree.find("http-transport-timeoutMs") - .and_then(Node::value) - .is_some_and(|value| value == "5000") - }); - app.press(Key::S, Modifiers::COMMAND); - }); -} - -fn an_environment(app: &mut App) { - step("an environment made, a secret typed, used from the picker", || { - app.click("http-environment-picker"); - app.click("http-environment-manage"); - app.wait_for("http-environments"); - app.click("http-environment-create-open"); - app.fill("http-environment-create-input", "Production"); - app.click("http-environment-create-submit"); - app.wait_for("http-environment-name"); - app.click_nth("http-variable-name", 0); - app.type_text("apiKey"); - app.click_nth("http-variable-value", 0); - app.type_text("s3cret"); - app.click_nth("http-variable-kind", 0); - app.click("http-variable-kind-2"); - app.eventually("the value is masked", |tree| { - tree.has("http-variable-reveal") - && tree - .find("http-variable-value") - .and_then(Node::value) - .is_some_and(|value| value != "s3cret") - }); - app.click("http-environment-use"); - app.eventually("it is the active one", |tree| !tree.has("http-environment-use")); - }); -} - -fn protected(app: &mut App) { - step("once protected, a POST asks before it leaves", || { - app.click("http-environment-protected"); - app.wait_for("http-environment-protected-note"); - app.click("http-environments-open"); - app.wait_for("http-url"); - app.click("http-method"); - app.click("http-method-1"); - let port = e2e::serve(); - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(&format!("http://127.0.0.1:{port}/json")); - app.click("http-send"); - app.wait_for("http-protected-confirm"); - assert!(!app.has("http-response-status"), "nothing left yet"); - app.click("http-protected-cancel"); - app.eventually("the question goes", |tree| !tree.has("http-protected-confirm")); - app.click("http-send"); - app.click("http-protected-send"); - app.wait_for("http-response-status"); - }); -} - -/// The active environment's secret, named in the URL: its chip's card says where it comes from, -/// masks it, and shows it when asked. -fn pointed_at(app: &mut App) { - step("a variable pointed at says where it is from, and its value", || { - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("https://example.test/{{apiKey}}"); - app.wait_for("http-used-variable"); - app.hover("http-used-variable"); - app.eventually("the card masks the secret", |tree| { - tree.text("http-used-variable-value").as_deref() == Some("••••••••") - }); - app.click("http-used-variable-reveal"); - app.eventually("and shows it", |tree| { - tree.text("http-used-variable-value").as_deref() == Some("s3cret") - }); - }); -} - -fn read_back(app: App) -> App { - let mut app = app.relaunch(); - step("unlocked again, the secret is masked, then shown", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-http"); - app.wait_for("http-url"); - app.click("http-section-auth"); - app.wait_for("http-auth-secret"); - app.click("http-auth-reveal"); - app.eventually("the token came back", |tree| { - tree.find("http-auth-secret") - .and_then(Node::value) - .is_some_and(|value| value == "s3cret") - }); - }); - app -} - -#[test] -fn http_environments() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("31_http_environments", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - a_request(&mut app); - picker(&mut app); - own_parts(&mut app); - let mut app = read_back(app); - an_environment(&mut app); - protected(&mut app); - pointed_at(&mut app); - app.quit_discarding(); -} diff --git a/e2e/tests/32_http_code.rs b/e2e/tests/32_http_code.rs deleted file mode 100644 index 17f847880..000000000 --- a/e2e/tests/32_http_code.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! A request written for another tool: a draft saved into the collection its first save makes, -//! an environment's secret left as a variable until a yes, and the targets of the list. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -fn code(tree: &Tree) -> String { - tree.find("http-code-output") - .and_then(Node::label) - .unwrap_or_default() - .to_owned() -} - -fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label() == Some(name) -} - -fn saved_draft(app: &mut App) { - step("a draft saved into the collection it lacks", || { - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-rail-empty"); - app.click("http-tab-new"); - app.fill("http-url", "https://api.exemple.fr/{{path}}"); - app.press(Key::S, Modifiers::COMMAND); - app.wait_for("http-save-dialog"); - app.fill("http-save-collection", "Facturation"); - app.click("http-save-submit"); - app.eventually("the request is in the rail", |tree| { - tree.texts("http-node-name").len() == 2 && !tree.has("http-save-dialog") - }); - }); -} - -fn secret(app: &mut App) { - step("an environment that sets a secret and a path", || { - app.click("http-environment-picker"); - app.click("http-environment-manage"); - app.click("http-environment-create-open"); - app.fill("http-environment-create-input", "Staging"); - app.click("http-environment-create-submit"); - app.wait_for("http-environment-name"); - app.click_nth("http-variable-name", 0); - app.type_text("path"); - app.click_nth("http-variable-value", 0); - app.type_text("invoices"); - app.click("http-environment-use"); - app.eventually("it is the active one", |tree| !tree.has("http-environment-use")); - app.click("http-environments-open"); - app.wait_for("http-url"); - }); -} - -fn generated(app: &mut App) { - step("cURL from the active environment, then as written", || { - app.click("http-code-open"); - app.wait_for("http-code-dialog"); - app.eventually("the URL is resolved", |tree| code(tree).contains("https://api.exemple.fr/invoices")); - app.click("http-code-resolve"); - app.eventually("the URL is as written", |tree| { - code(tree).contains("https://api.exemple.fr/{{path}}") - }); - app.click("http-code-resolve"); - app.eventually("resolved again", |tree| code(tree).contains("/invoices")); - }); - step("other targets, one of them found by the filter", || { - app.click_where("http-code-target", named("JavaScript · fetch")); - app.eventually("the fetch call", |tree| code(tree).contains("await fetch(")); - app.fill("http-code-filter", "elixir"); - app.click_where("http-code-target", named("Elixir · Req")); - app.eventually("the Req call", |tree| code(tree).contains("Req.request!(")); - app.click("http-code-copy"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the dialog closes", |tree| !tree.has("http-code-dialog")); - }); -} - -#[test] -fn http_code() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("32_http_code", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - saved_draft(&mut app); - secret(&mut app); - generated(&mut app); - app.quit(); -} diff --git a/e2e/tests/33_calc.rs b/e2e/tests/33_calc.rs deleted file mode 100644 index b5707c9f6..000000000 --- a/e2e/tests/33_calc.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! A Calcul note: made from the new-note menu, each line computed as it is typed, an error kept on -//! its line, a result picked and summed in the footer, and the last lines on its card. Results -//! are read by their figures: the language on screen writes the decimal mark and the units. - -use e2e::{App, Tree, step}; - -const TITLE: &str = "Budget sheet"; -const SHEET: &str = "# Budget -hébergement = 100,521 € -domaines = 4,99 € -mensuel = total -mensuel × 12 -3 h 20 min en min -20 % of 340 -100 € en $ -en = 5"; - -fn digits(text: &str) -> String { - text.chars().filter(char::is_ascii_digit).collect() -} - -fn results(tree: &Tree) -> Vec { - tree.all("calc-result") - .into_iter() - .map(|node| digits(node.value().unwrap_or_default())) - .collect() -} - -#[test] -fn calc() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("33_calc", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - step("a sheet is made from the new-note menu", || { - app.click("new-note-kind"); - app.click("new-note-calc"); - app.fill("editor-title", TITLE); - app.wait_for("calc-counts"); - }); - - step("each line is computed, and an error stays on its line", || { - app.click("editor-body"); - app.paste(SHEET); - app.eventually("the results computed", |tree| { - let results = results(tree); - results.contains(&"10551".to_owned()) && results.contains(&"200".to_owned()) - }); - app.eventually("two lines refused, on their lines", |tree| tree.count("calc-failure") == 2); - app.capture("sheet"); - }); - - step("a result picked is summed in the footer", || { - app.click_nth("calc-result", 0); - app.eventually("the sum said", |tree| { - tree.text("calc-summary").is_some_and(|said| digits(&said).contains("10052")) - }); - app.capture("picked"); - }); - - step("the card shows the last lines that gave something", || { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - app.capture("card"); - }); - - step("a short date before an accent leaves the sheet listed", || { - app.click("new-note-kind"); - app.click("new-note-calc"); - app.fill("editor-title", "Agenda"); - app.click("editor-body"); - app.paste("RDV le 5/11/24 à 10h\n2 + 2"); - app.eventually("the line computed", |tree| results(tree).contains(&"4".to_owned())); - app.click("editor-close"); - app.eventually("the card listed", |tree| { - tree.texts("note-card-title").iter().any(|title| title == "Agenda") - }); - app.capture("short-date"); - }); - - app.quit(); -} diff --git a/e2e/tests/34_http_scripts.rs b/e2e/tests/34_http_scripts.rs deleted file mode 100644 index 98c8d9213..000000000 --- a/e2e/tests/34_http_scripts.rs +++ /dev/null @@ -1,161 +0,0 @@ -//! Scripts run for real: the application relaunches itself as their host. One keeps a value of the -//! answer in a variable, a test reads the answer, the console hears them, the answer is kept as a -//! note, a file a script asks to send waits for a yes, and a throw before the send stops it and -//! leads back to its line. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -fn ends(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label().is_some_and(|label| label.ends_with(name)) -} - -fn create(app: &mut App, name: &str) { - app.fill("http-create-input", name); - app.press(Key::Enter, Modifiers::NONE); -} - -fn request(app: &mut App) { - step("a request to the local server", || { - let port = e2e::serve(); - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-rail-empty"); - app.click("http-rail-empty-create"); - create(app, "Boutique"); - app.wait_for("http-node-menu"); - app.click_where("http-node-menu", ends("Boutique")); - app.click("http-node-new"); - app.click("http-node-new-http"); - create(app, "Commander"); - app.eventually("the request is listed", |tree| tree.texts("http-node-name").len() == 2); - app.click_where("http-node-name", ends("Commander")); - app.fill("http-url", &format!("http://127.0.0.1:{port}/json")); - }); -} - -fn counted(tree: &Tree) -> Vec { - tree.texts("http-section-count") -} - -fn kept_value(app: &mut App) { - step("a script after the answer keeps a value in the globals", || { - app.click("http-section-scripts"); - app.wait_for("http-script-code"); - app.click("http-script-phase-1"); - app.fill("http-script-code", "env.set('who', res.json().name);"); - app.eventually("the tab counts it", |tree| counted(tree).contains(&"1".to_owned())); - app.press(Key::Enter, Modifiers::COMMAND); - app.wait_for("http-response-status"); - app.click("http-environments-open"); - app.eventually("the value is in the globals", |tree| { - tree.all("http-variable-value").iter().any(|node| node.value() == Some("Ada")) - }); - app.click("http-environments-open"); - app.wait_for("http-url"); - }); -} - -fn tests_and_console(app: &mut App) { - step("the tests of an answer, and what the console heard", || { - app.click("http-section-tests"); - app.fill("http-script-code", "test('the status is 200', () => { expect(res.status).toBe(200); });"); - app.eventually("the test is typed", |tree| { - tree.find("http-script-code") - .and_then(Node::value) - .is_some_and(|text| text.contains("toBe(200)")) - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.wait_for("http-response-section-tests"); - app.click("http-response-section-tests"); - app.wait_for("http-tests-passed"); - app.click("http-console-unfold"); - app.wait_for("http-console-line"); - app.click("http-console-fold"); - app.wait_for("http-console-unfold"); - app.click("http-response-section-body"); - }); - step("the answer kept as a note", || { - app.click("http-response-save-note"); - app.wait_for("save-as-note-submit"); - app.eventually("the dialog is filled", |tree| { - tree.find("save-as-note-title") - .and_then(Node::value) - .is_some_and(|title| title.contains("Commander")) - }); - app.click("save-as-note-submit"); - app.eventually("the dialog closes", |tree| !tree.has("save-as-note")); - }); -} - -fn file_asked(app: &mut App, path: &str) { - step("a file a script asks to send waits for a yes", || { - app.click("http-section-scripts"); - app.click("http-script-phase-0"); - app.fill( - "http-script-code", - &format!("pm.request.body.update({{ mode: 'file', file: {{ src: '{path}' }} }});"), - ); - app.eventually("the script is typed", |tree| { - tree.find("http-script-code") - .and_then(Node::value) - .is_some_and(|text| text.contains("id_ed25519")) - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the file is named", |tree| { - tree.text("http-script-file-confirm") - .is_some_and(|said| said.contains("id_ed25519")) - }); - app.capture("file-asked"); - app.click("http-script-file-cancel"); - app.eventually("nothing left", |tree| { - !tree.has("http-script-file-confirm") && !tree.has("http-response-status") - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.wait_for("http-script-file-confirm"); - app.click("http-script-file-send"); - app.wait_for("http-response-status"); - }); -} - -fn stopped(app: &mut App) { - step("a throw before the send stops it, and leads to its line", || { - app.click("http-section-scripts"); - app.click("http-script-phase-0"); - app.fill("http-script-code", "\nthrow new Error('refused');"); - // A key overtakes what is still being typed. - app.eventually("the script is typed", |tree| { - tree.find("http-script-code") - .and_then(Node::value) - .is_some_and(|text| text.contains("refused")) - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the stop is said", |tree| { - tree.text("http-script-stop-message") - .is_some_and(|said| said.contains("refused")) - }); - app.wait_for("http-script-stop-where"); - app.click("http-script-open"); - app.wait_for("http-script-code"); - }); -} - -#[test] -fn http_scripts() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("34_http_scripts", profile.path()); - app.create_library(); - app.wait_for("note-card"); - - let outside = tempfile::tempdir().unwrap(); - let key = outside.path().join("id_ed25519"); - std::fs::write(&key, "not a key").unwrap(); - let path = key.display().to_string().replace('\\', "/"); - - request(&mut app); - kept_value(&mut app); - tests_and_console(&mut app); - file_asked(&mut app, &path); - stopped(&mut app); - app.quit_discarding(); -} diff --git a/e2e/tests/35_http_runner.rs b/e2e/tests/35_http_runner.rs deleted file mode 100644 index 08eb2a797..000000000 --- a/e2e/tests/35_http_runner.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! A collection run: two requests over two iterations, each with its test, summed up, what failed -//! open on its assertion, nothing in the history; the rows of a data file; the order arranged kept -//! over a relaunch; and the quit that asks about a request left with changes. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -const API: &str = "Execution"; - -fn ends(name: &str) -> impl Fn(&Node) -> bool + '_ { - move |node| node.label().is_some_and(|label| label.ends_with(name)) -} - -fn create(app: &mut App, name: &str) { - app.fill("http-create-input", name); - app.press(Key::Enter, Modifiers::NONE); -} - -fn a_request(app: &mut App, name: &str, url: &str) { - app.click_where("http-node-menu", ends(API)); - app.click("http-node-new"); - app.click("http-node-new-http"); - create(app, name); - app.eventually("the request is listed", |tree| { - tree.all("http-node-name") - .iter() - .any(|node| node.label().is_some_and(|label| label.ends_with(name))) - }); - app.click_where("http-node-name", ends(name)); - app.fill("http-url", url); - app.click("http-section-tests"); - app.wait_for("http-script-code"); - app.fill("http-script-code", "test('found', () => { expect(res.status).toBe(200); });"); - app.eventually("the test is typed", |tree| { - tree.find("http-script-code") - .and_then(Node::value) - .is_some_and(|text| text.contains("toBe(200)")) - }); - app.click("http-save"); - app.eventually("the request is saved", |tree| tree.find("http-save").is_some_and(Node::is_disabled)); -} - -fn collection(app: &mut App) { - step("a collection of two requests with their tests", || { - let port = e2e::serve(); - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-rail-empty"); - app.click("http-rail-empty-create"); - create(app, API); - app.wait_for("http-node-menu"); - a_request(app, "Login", &format!("http://127.0.0.1:{port}/json")); - a_request(app, "Client", &format!("http://127.0.0.1:{port}/missing")); - }); -} - -fn open_runner(app: &mut App) { - app.click_where("http-node-menu", ends(API)); - app.click("http-node-run"); - app.eventually("the order is read", |tree| tree.count("http-runner-row") == 2); -} - -fn figures(tree: &Tree) -> String { - tree.text("http-runner-figures").unwrap_or_default() -} - -fn over_iterations(app: &mut App) { - step("a run over two iterations, summed up", || { - open_runner(app); - app.click("http-runner-iterations"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("2"); - app.eventually("the field says two iterations", |tree| { - tree.find("http-runner-iterations").and_then(Node::value) == Some("2") - }); - app.click("http-runner-start"); - app.eventually("the run is summed up", |tree| { - figures(tree).contains(" 2/4") && figures(tree).ends_with(" s") - }); - }); - step("each iteration apart, the failed requests open", || { - let tree = app.tree(); - assert_eq!(tree.count("http-runner-iteration"), 2); - assert_eq!(tree.count("http-runner-result-passed"), 2); - assert_eq!(tree.count("http-runner-result-failed"), 2); - assert_eq!(tree.count("http-runner-test"), 2); - app.click("http-runner-filter-failed"); - app.eventually("only the failed are shown", |tree| tree.count("http-runner-result-passed") == 0); - app.click("http-runner-filter-all"); - }); - step("a run writes no history", || { - app.click("http-history-open"); - app.wait_for("http-history"); - app.eventually("nothing is listed", |tree| tree.count("http-history-item") == 0); - }); -} - -fn over_a_file(app: &mut App) { - step("a data file gives an iteration a row", || { - open_runner(app); - app.click("http-runner-data-choose"); - app.wait_for("http-runner-data"); - app.click("http-runner-start"); - app.eventually("each row ran, and the run is over", |tree| { - tree.count("http-runner-iteration") == 3 && !tree.has("http-runner-cancel") - }); - }); -} - -fn order_kept(app: &mut App) { - step("the order moved by the keys", || { - app.click_nth("http-runner-row", 0); - app.eventually("the row has the focus", |tree| { - tree.focused().contains("http-runner-row") && tree.focused().contains("Login") - }); - app.press(Key::ArrowDown, Modifiers::ALT); - app.eventually("the rows are swapped", |tree| { - tree.all("http-runner-row") - .first() - .is_some_and(|row| row.label() == Some("Client")) - }); - }); -} - -#[test] -fn http_runner() { - let profile = tempfile::tempdir().unwrap(); - let files = tempfile::tempdir().unwrap(); - let csv = files.path().join("clients.csv"); - std::fs::write(&csv, "customer\ncus_1\ncus_2\ncus_3\n").unwrap(); - let mut app = App::launch_answering("35_http_runner", profile.path(), &csv); - app.create_library(); - app.wait_for("note-card"); - - collection(&mut app); - over_iterations(&mut app); - over_a_file(&mut app); - order_kept(&mut app); - - let mut app = app.relaunch(); - step("the order is still the one arranged", || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-http"); - app.wait_for("http-node-menu"); - open_runner(&mut app); - app.eventually("the order is the one kept", |tree| { - tree.all("http-runner-row") - .first() - .is_some_and(|row| row.label() == Some("Client")) - }); - }); - step("a quit asks about a request with changes", || { - app.click_where("http-node-name", ends("Login")); - app.wait_for("http-url"); - app.fill("http-url", "/changed"); - app.eventually("the request has changes", |tree| { - tree.find("http-save").is_some_and(|save| !save.is_disabled()) - }); - app.act("quit"); - app.wait_for("http-leave-dialog"); - app.click("http-leave-cancel"); - app.eventually("the question is gone", |tree| !tree.has("http-leave-dialog")); - app.act("quit"); - app.wait_for("http-leave-dialog"); - app.click("http-leave-save"); - }); - app.ended(); -} diff --git a/e2e/tests/36_recette_libraries.rs b/e2e/tests/36_recette_libraries.rs deleted file mode 100644 index 7b4cac137..000000000 --- a/e2e/tests/36_recette_libraries.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! The acceptance sheet's cases on libraries that no other scenario holds. A step opens on the -//! case it runs, so that a run can be read back into the sheet. - -use std::path::PathBuf; - -use e2e::{App, PASSPHRASE, step}; -use egui::{Key, Modifiers}; - -const OTHER: &str = "Recette 2"; -const RENAMED: &str = "Recette Deux"; -const ONLY_HERE: &str = "zq-isolation"; -const TOO_SHORT: &str = "abc"; - -fn panel(app: &mut App) { - app.click("file-menu"); - app.click("file-libraries"); - app.wait_for("library-row"); -} - -fn pass_the_gate(app: &mut App) { - app.fill("vault-passphrase", PASSPHRASE); - if app.has("vault-confirmation") { - app.fill("vault-confirmation", PASSPHRASE); - } - app.click("vault-submit"); - app.wait_for("area-notes"); -} - -/// The key file of the only library of `profile`. -fn key_file(profile: &std::path::Path) -> PathBuf { - let libraries = profile.join("libraries"); - let library = std::fs::read_dir(libraries).unwrap().next().unwrap().unwrap(); - library.path().join("vault.json") -} - -#[test] -fn recette_libraries() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("36_recette_libraries", profile.path()); - - step("LIB-01 the gate says the floor before anything is typed", || { - app.wait_for("vault-minimum"); - assert!(app.has("vault-confirmation")); - }); - - step("LIB-03 two different phrases are said to differ", || { - app.fill("vault-passphrase", PASSPHRASE); - app.fill("vault-confirmation", "correct horse battery stapler"); - app.wait_for("vault-problem"); - assert!(app.tree().find("vault-submit").is_some_and(egui::accesskit::Node::is_disabled)); - }); - - // A field that reveals keeps its role and no value: the picture is what says it. - step("LIB-04 show and hide take both fields together", || { - let hidden = std::fs::read(app.capture("phrase-hidden")).unwrap(); - app.click("vault-reveal"); - let shown = std::fs::read(app.capture("phrase-shown")).unwrap(); - assert_ne!(hidden, shown); - app.click("vault-reveal"); - }); - - step("LIB-05 the right phrase twice opens the canvas", || { - app.click("vault-confirmation"); - app.press(Key::Backspace, Modifiers::NONE); - app.click("vault-submit"); - app.wait_for("area-notes"); - }); - - step("LIB-14 a note of one library is not in the other", || { - app.click("new-note"); - app.fill("editor-title", ONLY_HERE); - app.click("editor-close"); - app.eventually("the note is a card", |tree| { - tree.texts("note-card").iter().any(|card| card == ONLY_HERE) - }); - panel(&mut app); - app.fill("library-new-name", OTHER); - app.click("library-create"); - app.wait_for("vault-confirmation"); - pass_the_gate(&mut app); - app.eventually("its samples are drawn", |tree| tree.has("note-card")); - app.fill("search-input", ONLY_HERE); - app.wait_for("search-matched"); - app.eventually("nothing is found", |tree| !tree.has("note-card")); - }); - - step("LIB-15 a library is renamed from the panel", || { - app.click("search-clear"); - panel(&mut app); - app.click("library-start-rename"); - app.click("library-rename"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(RENAMED); - app.press(Key::Enter, Modifiers::NONE); - let registry = profile.path().join("libraries.json"); - app.eventually("the registry names it", |_| { - std::fs::read_to_string(®istry).is_ok_and(|text| text.contains(RENAMED)) - }); - app.click("libraries-close"); - }); - - let mut app = app.relaunch(); - - step("LIB-08 no length rule at the unlock, only a refusal", || { - app.fill("vault-passphrase", TOO_SHORT); - app.click("vault-submit"); - app.wait_for("vault-problem"); - assert!(!app.has("vault-minimum")); - }); - app.quit(); -} - -#[test] -fn recette_a_lost_key_file() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("36_recette_key_file", profile.path()); - app.create_library(); - app.quit(); - let key = key_file(profile.path()); - let kept = key.with_extension("json.bak"); - std::fs::rename(&key, &kept).unwrap(); - - let mut app = App::launch("36_recette_key_file", profile.path()); - step("LIB-20 a library without its key file says so", || { - app.wait_for("vault-key-missing"); - assert!(!app.has("vault-passphrase")); - }); - app.quit(); - - std::fs::rename(&kept, &key).unwrap(); - let mut app = App::launch("36_recette_key_file", profile.path()); - step("LIB-20 the file put back, the phrase opens it again", || { - pass_the_gate(&mut app); - }); - app.quit(); -} diff --git a/e2e/tests/37_recette_socle.rs b/e2e/tests/37_recette_socle.rs deleted file mode 100644 index 271b54c3c..000000000 --- a/e2e/tests/37_recette_socle.rs +++ /dev/null @@ -1,368 +0,0 @@ -//! The acceptance sheet's cases on security, the window and the preferences that no other scenario -//! holds. A step opens on the case it runs, so that a run can be read back into the sheet. - -use std::path::{Path, PathBuf}; - -use e2e::{App, PASSPHRASE, Tree, step}; -use egui::accesskit::{Node, Toggled}; -use egui::{Key, Modifiers}; - -const NEXT: &str = "a second end-to-end passphrase"; -const SECRET: &str = "zq-secret-recette"; -const LATER: &str = "zq-apres-copie"; -const THEME_LIGHT: &str = "setting-theme-2"; -const THEME_DARK: &str = "setting-theme-1"; -const COMPACT: &str = "setting-density-1"; -const COMFORTABLE: &str = "setting-density-0"; -const ENGLISH: &str = "setting-locale-2"; - -fn preferences(app: &mut App) { - app.click("file-menu"); - app.click("file-preferences"); - app.wait_for("settings-dialog"); -} - -fn security(app: &mut App) { - preferences(app); - app.click("settings-page-backups"); - app.wait_for("setting-automatic-backups"); -} - -fn close(app: &mut App) { - app.click("settings-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); -} - -fn unlock(app: &mut App, phrase: &str) { - app.fill("vault-passphrase", phrase); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("the cards are drawn", |tree| tree.has("note-card")); -} - -fn a_note(app: &mut App, title: &str, body: &str) { - app.click("new-note"); - app.fill("editor-title", title); - app.fill("editor-body", body); - app.click("editor-close"); - app.eventually("the editor closed", |tree| !tree.has("editor-title")); -} - -fn is_on(node: Option<&Node>) -> bool { - node.and_then(Node::toggled) == Some(Toggled::True) -} - -fn top_of(tree: &Tree) -> f64 { - tree.find("area-option-notes") - .and_then(Node::bounds) - .map_or(f64::INFINITY, |bounds| bounds.y0) -} - -fn switch_top(app: &mut App) -> f64 { - top_of(&app.tree()) -} - -fn files_under(directory: &Path, found: &mut Vec) { - for entry in std::fs::read_dir(directory).unwrap().flatten() { - let path = entry.path(); - if path.is_dir() { - files_under(&path, found); - } else { - found.push(path); - } - } -} - -fn the_library(profile: &Path) -> PathBuf { - let mut libraries = std::fs::read_dir(profile.join("libraries")).unwrap(); - libraries.next().unwrap().unwrap().path() -} - -#[test] -fn recette_security() { - let directory = tempfile::tempdir().unwrap(); - let profile = directory.path(); - let mut app = App::launch("37_recette_security", profile); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - let mut app = app.relaunch(); - unlock(&mut app, PASSPHRASE); - - step("SEC-01 the page holds the phrase and the copies", || { - security(&mut app); - assert!(is_on(app.tree().find("setting-automatic-backups"))); - app.capture("security"); - }); - - step("SEC-02 a copy of the launch, offered back", || { - app.scroll_to("settings-content", "backup-row"); - assert!(app.has("backup-restore")); - close(&mut app); - }); - - let mut app = app.relaunch(); - unlock(&mut app, PASSPHRASE); - - step("SEC-03 a second launch of the day takes no copy", || { - security(&mut app); - app.scroll_to("settings-content", "backup-row"); - assert_eq!(app.tree().count("backup-row"), 1); - }); - - step("SEC-05 a new phrase too short changes nothing", || { - app.click("settings-page-security"); - app.click("setting-change-passphrase"); - app.fill("change-passphrase-current", PASSPHRASE); - app.fill("change-passphrase-next", "court-08"); - app.fill("change-passphrase-confirmation", "court-08"); - app.wait_for("change-passphrase-problem"); - assert!(app.tree().find("change-passphrase-submit").is_some_and(Node::is_disabled)); - app.click("change-passphrase-cancel"); - app.eventually("the dialog closed", |tree| !tree.has("change-passphrase")); - }); - - step("SEC-06 the session carries on over a new phrase", || { - app.click("setting-change-passphrase"); - app.wait_for("change-passphrase-copies"); - app.capture("change-passphrase"); - app.fill("change-passphrase-current", PASSPHRASE); - app.fill("change-passphrase-next", NEXT); - app.fill("change-passphrase-confirmation", NEXT); - app.click("change-passphrase-submit"); - app.eventually("the dialog closed", |tree| !tree.has("change-passphrase")); - app.wait_for("status-toast"); - close(&mut app); - assert!(app.has("note-card"), "no phrase is asked again"); - }); - - restoring(&mut app, profile); - app.quit(); -} - -fn restoring(app: &mut App, profile: &Path) { - step("SEC-08 the restore says what leaves, and Cancel keeps it", || { - a_note(app, LATER, "echo after"); - security(app); - app.scroll_to("settings-content", "backup-row"); - app.click("backup-restore"); - app.wait_for("backup-confirm"); - app.capture("restore-confirm"); - app.click("backup-cancel"); - app.eventually("the strip is gone", |tree| !tree.has("backup-confirm")); - close(app); - app.eventually("the note stays", |tree| tree.texts("note-card-title").iter().any(|it| it == LATER)); - }); - - step("SEC-09 a restore sets the library aside in replaced", || { - security(app); - app.scroll_to("settings-content", "backup-row"); - app.click("backup-restore"); - app.scroll_above("settings-content", "backup-confirm-restore", "settings-cancel"); - app.click("backup-confirm-restore"); - app.wait_for("vault-passphrase"); - app.wait_for("status-toast"); - app.capture("restored"); - let replaced = the_library(profile).join("replaced"); - assert!(std::fs::read_dir(replaced).unwrap().next().is_some()); - }); - - step("SEC-10 a copy older than the change opens with the new phrase", || { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.eventually("the old phrase is refused", |tree| { - tree.text("vault-problem").is_some_and(|said| !said.is_empty()) - }); - unlock(app, NEXT); - }); - - step("SEC-09 what was written after the copy is gone", || { - let titles = app.tree().texts("note-card-title"); - assert!(!titles.contains(&LATER.to_owned()), "{titles:?}"); - }); -} - -#[test] -fn recette_nothing_readable_on_the_disk() { - let directory = tempfile::tempdir().unwrap(); - let profile = directory.path(); - let mut app = App::launch("37_recette_disk", profile); - app.create_library(); - a_note(&mut app, SECRET, SECRET); - app.quit(); - - step("SEC-12 neither title nor body can be read on the disk", || { - let mut files = Vec::new(); - files_under(&profile.join("libraries"), &mut files); - assert!(!files.is_empty()); - for file in files { - let bytes = std::fs::read(&file).unwrap(); - let found = bytes.windows(SECRET.len()).any(|window| window == SECRET.as_bytes()); - assert!(!found, "{} reads in the clear", file.display()); - } - }); -} - -#[test] -fn recette_window() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("37_recette_window", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - - step("APP-01 each area is found as it was left", || { - app.click("note-card"); - app.wait_for("editor-title"); - app.press(Key::Num2, Modifiers::COMMAND); - app.wait_for("area-tools"); - app.click("tools-entry-case"); - app.wait_for("tool-title"); - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-rail-title"); - app.click("http-tab-new"); - app.wait_for("http-tab-open"); - app.press(Key::Num1, Modifiers::COMMAND); - app.wait_for("area-notes"); - app.wait_for("editor-title"); - app.press(Key::Num2, Modifiers::COMMAND); - app.wait_for("tool-title"); - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-tab-open"); - app.press(Key::Num1, Modifiers::COMMAND); - app.wait_for("editor-title"); - app.click("editor-close"); - app.eventually("the editor closed", |tree| !tree.has("editor-title")); - }); - - step("APP-02 one state of the rail for the three areas", || { - let in_the_rail = switch_top(&mut app); - app.press(Key::B, Modifiers::COMMAND); - app.eventually("the bar took the switch", |tree| top_of(tree) < in_the_rail); - app.press(Key::Num2, Modifiers::COMMAND); - app.wait_for("area-tools"); - assert!(switch_top(&mut app) < in_the_rail); - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-tab-open"); - assert!(switch_top(&mut app) < in_the_rail); - app.press(Key::B, Modifiers::COMMAND); - app.eventually("the rail took it back", |tree| top_of(tree) >= in_the_rail); - app.press(Key::Num1, Modifiers::COMMAND); - app.wait_for("area-notes"); - assert!(switch_top(&mut app) >= in_the_rail); - }); - - step("APP-07 the bar's theme switches in one click", || { - let word = app.tree().text("theme-toggle").unwrap_or_default(); - app.click("theme-toggle"); - app.eventually("the word changed", |tree| tree.text("theme-toggle").is_some_and(|now| now != word)); - }); - - let word = app.tree().text("theme-toggle").unwrap_or_default(); - let mut app = app.relaunch_discarding(); - unlock(&mut app, PASSPHRASE); - - step("APP-07 the theme survives a relaunch", || { - assert_eq!(app.tree().text("theme-toggle").unwrap_or_default(), word); - }); - - step("APP-13 quitting takes two clicks, a click elsewhere calls it off", || { - app.click("file-menu"); - let word = app.tree().text("file-quit").unwrap_or_default(); - app.click("file-quit"); - app.eventually("the entry asks", |tree| tree.text("file-quit").is_some_and(|now| now != word)); - app.press(Key::ArrowUp, Modifiers::NONE); - app.eventually("the arrows call it off", |tree| { - tree.text("file-quit").is_some_and(|now| now == word) - }); - app.click("file-quit"); - app.eventually("the entry asks again", |tree| tree.text("file-quit").is_some_and(|now| now != word)); - app.click("file-menu"); - app.eventually("the menu closed", |tree| !tree.has("file-quit")); - app.click("file-menu"); - assert_eq!(app.tree().text("file-quit").unwrap_or_default(), word); - app.click("file-quit"); - app.click("file-quit"); - }); - - app.ended(); -} - -#[test] -fn recette_preferences() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("37_recette_preferences", profile.path()); - app.create_library(); - - step("PRF-01 the panel: its pages and its footer", || { - preferences(&mut app); - for id in [ - "settings-page-general", - "settings-page-variables", - "settings-page-shortcuts", - "settings-page-security", - "settings-cancel", - "settings-apply", - "settings-close", - ] { - assert!(app.has(id), "{id}"); - } - app.capture("preferences"); - }); - - step("PRF-02 theme and density preview, Cancel takes both back", || { - app.click(THEME_DARK); - app.click(COMFORTABLE); - app.click("settings-apply"); - let word = app.tree().text("theme-toggle").unwrap_or_default(); - let before = std::fs::read(app.capture("density-before")).unwrap(); - app.click(THEME_LIGHT); - app.click(COMPACT); - app.eventually("the theme previews", |tree| tree.text("theme-toggle").is_some_and(|now| now != word)); - assert_ne!(before, std::fs::read(app.capture("density-after")).unwrap()); - app.click("settings-cancel"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - assert_eq!(app.tree().text("theme-toggle").unwrap_or_default(), word); - preferences(&mut app); - assert!(is_on(app.tree().find(THEME_DARK))); - assert!(is_on(app.tree().find(COMFORTABLE))); - }); - - step("PRF-05 three changes waiting are counted, each way out does as it says", || { - app.click(THEME_LIGHT); - app.click(COMPACT); - app.click("setting-locale"); - app.click(ENGLISH); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the footer counts them", |tree| { - tree.text("settings-unapplied").is_some_and(|said| said.contains('3')) - }); - app.capture("unapplied"); - app.click("settings-discard"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - preferences(&mut app); - assert!(is_on(app.tree().find(THEME_DARK))); - - app.click(THEME_LIGHT); - app.press(Key::Escape, Modifiers::NONE); - app.click("settings-apply-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - preferences(&mut app); - assert!(is_on(app.tree().find(THEME_LIGHT))); - app.click(THEME_DARK); - close(&mut app); - }); - - step("PRF-15 a canvas key refuses the navigation's keys", || { - preferences(&mut app); - app.click("settings-page-shortcuts"); - app.scroll_above("settings-content", "shortcut-field-canvas.pin", "settings-cancel"); - app.click("shortcut-field-canvas.pin"); - assert!(app.has("settings-dialog")); - app.press(Key::ArrowUp, Modifiers::NONE); - app.wait_for("shortcut-error-canvas.pin"); - app.capture("reserved"); - app.press(Key::Escape, Modifiers::NONE); - assert!(app.has("settings-dialog")); - }); - - app.quit(); -} diff --git a/e2e/tests/38_recette_notes.rs b/e2e/tests/38_recette_notes.rs deleted file mode 100644 index 17baa803b..000000000 --- a/e2e/tests/38_recette_notes.rs +++ /dev/null @@ -1,558 +0,0 @@ -//! The acceptance sheet's main paths through the notes that no other scenario walks whole. A step -//! opens on the case it runs, so that a run can be read back into the sheet. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -const SHIFT_COMMAND: Modifiers = Modifiers::COMMAND.plus(Modifiers::SHIFT); - -const SHEET: &str = "# Hébergement -prix = 0,045 €/h -serveurs = 3 -coût = prix × 730 h × serveurs -20 % de 340 -30 sur 120 en % -de 80 à 100 -250 + 20 % -300 hors 20 % -2,5 kg en g -3 h 20 min en min -1 Go en Mo - -# Courses -10 € -20 € -30 € -total -moyenne - -# Erreurs -distance = 5 km -distance + 3 Go -distance en m"; - -const RUST: &str = "editor-language-6"; -const TYPESCRIPT: &str = "editor-language-3"; - -const LITERAL: &str = "{{db_host}}\na -> b\n2 * 3 * 4\nsnake_case_name"; -const SLIDES: &str = "# Un\n\ntexte\n\n## Deux\n\n### Reste ici\n\n---\n\nTrois"; - -fn close_editor(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor closed", |tree| !tree.has("editor-title")); -} - -fn open_card(app: &mut App, title: &str) { - app.click_where("note-card-open", |node| node.label().is_some_and(|label| label.contains(title))); - app.wait_for("editor-title"); -} - -fn card_titles(tree: &Tree) -> Vec { - tree.texts("note-card-title") -} - -fn has_card(tree: &Tree, title: &str) -> bool { - card_titles(tree).iter().any(|it| it == title) -} - -fn a_snippet(app: &mut App, title: &str, body: &str) { - app.click("new-note"); - app.fill("editor-title", title); - app.click("editor-body"); - app.paste(body); - close_editor(app); -} - -fn code(tree: &Tree) -> String { - tree.find("editor-body").and_then(Node::value).unwrap_or_default().to_owned() -} - -/// A snippet holding Markdown, made a Note: what a file of Markdown comes in as. -fn a_note_of(app: &mut App, title: &str, markdown: &str) { - a_snippet(app, title, markdown); - open_card(app, title); - app.click("editor-kind"); - app.click_nth("editor-kind-0", 0); - app.wait_for("editor-rich"); -} - -/// The language menu's filter takes the focus a frame after it opens; a click in it keeps the -/// menu open. -fn choose_language(app: &mut App, typed: &str, option: &str) { - app.click("editor-language"); - app.wait_for("editor-language-filter"); - app.click("editor-language-filter"); - app.eventually("the filter has the focus", |tree| tree.focused().starts_with("editor-language-filter")); - app.type_text(typed); - app.click(option); -} - -fn digits(text: &str) -> String { - text.chars().filter(char::is_ascii_digit).collect() -} - -fn calc_results(tree: &Tree) -> Vec { - tree.all("calc-result") - .into_iter() - .map(|node| digits(node.value().unwrap_or_default())) - .collect() -} - -fn a_new_library(scenario: &'static str, profile: &std::path::Path) -> App { - let mut app = App::launch(scenario, profile); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.has("note-card")); - app -} - -#[test] -fn recette_creating() { - let profile = tempfile::tempdir().unwrap(); - let mut app = a_new_library("38_recette_creating", profile.path()); - - step("NOT-02 a title alone, left by Escape, is a note", || { - app.click("new-note"); - app.fill("editor-title", "Recette première note"); - app.press(Key::Escape, Modifiers::NONE); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the card is there", |tree| { - !tree.has("editor-title") && has_card(tree, "Recette première note") - }); - }); - - step("NOT-06 a fast close writes one note, with its body", || { - app.click("new-note"); - app.fill("editor-title", "Course"); - app.fill("editor-body", "corps"); - app.press(Key::Escape, Modifiers::NONE); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the card is there", |tree| has_card(tree, "Course")); - let titles = app.tree().texts("note-card-title"); - assert_eq!(titles.iter().filter(|it| *it == "Course").count(), 1); - }); - - a_snippet(&mut app, "Psql", "psql -h localhost"); - - step("NOT-07 a title changed, another card clicked", || { - open_card(&mut app, "Course"); - app.click("editor-title"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("Titre modifié au clic"); - app.capture("not-07-before"); - let psql = |node: &egui::accesskit::Node| node.label().is_some_and(|it| it.contains("Psql")); - // In a window too narrow to keep the cards beside the editor, none is there to click. - let beside = app.tree().all("note-card-open").into_iter().any(psql); - if beside { - app.click_where("note-card-open", psql); - } else { - close_editor(&mut app); - } - app.eventually("the editor closed or moved", |tree| { - !tree.has("editor-title") || has_card(tree, "Titre modifié au clic") - }); - app.capture("not-07-after"); - if app.has("editor-title") { - close_editor(&mut app); - } - app.eventually("the first note wears its new title", |tree| has_card(tree, "Titre modifié au clic")); - }); - - step("NOT-10 a snippet made a Note, and taken back", || { - open_card(&mut app, "Psql"); - app.click("editor-kind"); - app.click_nth("editor-kind-0", 0); - app.wait_for("editor-rich"); - app.capture("not-10-converted"); - app.click("undo-restore"); - app.wait_for("editor-body"); - close_editor(&mut app); - }); - - app.quit(); -} - -#[test] -fn recette_a_snippet_and_a_list() { - let profile = tempfile::tempdir().unwrap(); - let mut app = a_new_library("38_recette_snippet", profile.path()); - - step("COD-01 the language menu filters, and the card says it", || { - app.click("new-note"); - app.fill("editor-title", "Rouille"); - app.fill("editor-body", "fn main() { println!(\"bonjour\"); }"); - choose_language(&mut app, "rus", RUST); - app.eventually("the language is chosen", |tree| { - tree.text("editor-stats").is_some_and(|said| said.starts_with("RS")) - }); - app.capture("cod-01-coloured"); - close_editor(&mut app); - }); - - step("COD-09 a formatted snippet keeps its fields", || { - app.click("new-note"); - app.fill("editor-title", "Champs formatés"); - app.click("editor-body"); - app.paste("const url=\"{{host}}/api/{{version=v2}}\";fetch(url)"); - choose_language(&mut app, "typescript", TYPESCRIPT); - app.click("editor-format"); - app.wait_for("editor-format-notice"); - let body = code(&app.tree()); - assert!(body.contains("{{host}}/api/{{version=v2}}"), "{body}"); - assert!(body.contains(";\n"), "{body}"); - close_editor(&mut app); - }); - - step("COD-12 a word found three times, stepped through", || { - app.click("new-note"); - app.fill("editor-title", "Trois foo"); - app.fill("editor-body", "foo(); foo(); foo();"); - app.press(Key::F, Modifiers::COMMAND); - app.wait_for("search-field"); - app.type_text("foo"); - app.eventually("three are counted", |tree| { - tree.text("search-count").is_some_and(|said| said.ends_with("/ 3")) - }); - let count = app.tree().text("search-count").unwrap_or_default(); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the next one", |tree| tree.text("search-count").is_some_and(|said| said != count)); - app.click("search-previous"); - app.eventually("back to the first", |tree| { - tree.text("search-count").is_some_and(|said| said == count) - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the bar closed", |tree| !tree.has("search-field")); - assert!(app.has("editor-title"), "the editor stays"); - close_editor(&mut app); - }); - - step("TCH-01 Enter adds a row, the caret in it", || { - app.press(Key::L, SHIFT_COMMAND); - app.fill("editor-title", "Tâches"); - app.click("checklist-add"); - app.eventually("the row takes the caret", |tree| tree.focused().starts_with("checklist-text")); - app.type_text("Préparer"); - app.press(Key::Enter, Modifiers::NONE); - app.type_text("Déployer"); - app.eventually("two rows", |tree| { - tree.all("checklist-text") - .iter() - .filter_map(|row| row.value()) - .eq(["Préparer", "Déployer"]) - }); - close_editor(&mut app); - }); - - step("TCH-06 ticked from its card, the progress follows", || { - app.click_nth("note-card-item", 0); - app.eventually("the progress moved", |tree| { - tree.texts("note-card-progress").iter().any(|it| it.contains("1/2")) - }); - }); - - app.quit(); -} - -#[test] -fn recette_a_formatted_note() { - let profile = tempfile::tempdir().unwrap(); - let mut app = a_new_library("38_recette_rich", profile.path()); - - step("RIC-01 every button of the bar formats", || { - app.press(Key::N, SHIFT_COMMAND); - app.fill("editor-title", "Barre"); - for button in [ - "rich-h1", - "rich-h2", - "rich-h3", - "rich-bold", - "rich-italic", - "rich-strike", - "rich-code", - "rich-bullet", - "rich-ordered", - "rich-tasks", - "rich-quote", - ] { - assert!(app.has(button), "{button}"); - } - app.click("editor-rich"); - app.type_text("gras"); - app.press(Key::A, Modifiers::COMMAND); - app.click("rich-bold"); - app.capture("ric-01"); - close_editor(&mut app); - }); - - step("RIC-08 a final code block is left by the down arrow", || { - app.press(Key::N, SHIFT_COMMAND); - app.fill("editor-title", "Bloc final"); - app.click("editor-rich"); - app.click("rich-codeBlock"); - app.type_text("let x = 1;"); - app.press(Key::ArrowDown, Modifiers::NONE); - app.type_text("Suite"); - app.eventually("the text is under the block", |tree| { - tree.find("editor-rich") - .and_then(Node::value) - .is_some_and(|text| text.contains("let x = 1;") && text.contains("\nSuite")) - }); - close_editor(&mut app); - }); - - step("RIC-09 what looks like Markdown comes back as typed", || { - app.press(Key::N, SHIFT_COMMAND); - app.fill("editor-title", "Littéral"); - app.click("editor-rich"); - for line in LITERAL.lines() { - app.type_text(line); - app.press(Key::Enter, Modifiers::NONE); - } - close_editor(&mut app); - open_card(&mut app, "Littéral"); - app.capture("ric-09"); - close_editor(&mut app); - }); - - step("RIC-19 a Note presented: cover, then a slide per heading", || { - a_note_of(&mut app, "Lancement", SLIDES); - app.click("editor-present"); - app.wait_for("presentation"); - app.wait_for("presentation-cover"); - app.capture("ric-19-cover"); - let count = app.tree().text("presentation-count").unwrap_or_default(); - assert!(count.contains('1') && count.contains('4'), "{count}"); - app.press(Key::ArrowRight, Modifiers::NONE); - app.eventually("the next slide", |tree| { - tree.text("presentation-count").is_some_and(|now| now != count) - }); - app.capture("ric-19-slide"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("it left", |tree| !tree.has("presentation")); - close_editor(&mut app); - }); - - app.quit(); -} - -#[test] -fn recette_a_sheet_and_a_drawing() { - let profile = tempfile::tempdir().unwrap(); - let mut app = a_new_library("38_recette_calc", profile.path()); - // Every result in view under the notes header, which stays above an expanded note. - app.resize(1_100, 900); - - step("CAL-45 a sheet pasted answers line by line", || { - app.press(Key::M, SHIFT_COMMAND); - // Every result in view: the sheet expanded over the cards. - app.click("editor-fullscreen"); - app.fill("editor-title", "Feuille"); - app.click("editor-body"); - app.paste(SHEET); - app.eventually("the figures are there", |tree| { - let results = calc_results(tree); - ["9855", "68", "25", "300", "250", "2500", "200", "1000", "6000", "2000", "5000"] - .iter() - .all(|it| results.contains(&(*it).to_owned())) - }); - app.eventually("one line refused, the next carries on", |tree| tree.count("calc-failure") == 1); - app.capture("cal-45"); - }); - - step("CAL-37 results picked: a range, then a stranger", || { - app.click_where("calc-result", |node| node.value().is_some_and(|it| digits(it) == "1000")); - app.eventually("the footer sums it", |tree| { - tree.text("calc-summary").is_some_and(|said| digits(&said).contains("1000")) - }); - close_editor(&mut app); - }); - - step("DES-01 an empty drawing says what to do", || { - app.press(Key::D, SHIFT_COMMAND); - app.fill("editor-title", "Plan"); - app.wait_for("drawing-stage"); - app.capture("des-01"); - }); - - step("DES-02 three shapes from their letters", || { - app.click("drawing-stage"); - for (key, from, to) in [ - (Key::R, (40.0, 40.0), (140.0, 100.0)), - (Key::O, (180.0, 40.0), (280.0, 100.0)), - (Key::D, (320.0, 40.0), (420.0, 100.0)), - ] { - app.press(key, Modifiers::NONE); - app.drag_in("drawing-stage", from, to); - } - app.eventually("the footer counts three", |tree| { - tree.text("editor-stats").is_some_and(|said| said.contains('3')) - }); - app.capture("des-02"); - }); - - step("DES-09 the drawing is kept, its card shows it", || { - close_editor(&mut app); - app.wait_for("note-card-drawing"); - app.click("note-card-drawing"); - app.wait_for("drawing-stage"); - app.eventually("the footer still counts three", |tree| { - tree.text("editor-stats").is_some_and(|said| said.contains('3')) - }); - close_editor(&mut app); - }); - - step("DES-13 a drawing inserted into a Note shows its picture", || { - app.press(Key::N, SHIFT_COMMAND); - app.fill("editor-title", "Avec dessin"); - app.click("rich-embed-drawing"); - app.click("rich-embed-drawing-0"); - app.wait_for("rich-embed"); - app.capture("des-13"); - }); - - step("a drawing in a Note is resized, and stays so", || { - let width = |tree: &Tree| { - let drawn = tree.find("rich-embed").and_then(Node::bounds); - drawn.map_or(0.0, |bounds| bounds.width()) - }; - app.click("rich-embed"); - app.click("rich-embed-size-4"); - app.wait_for("rich-embed-resize"); - let whole = width(&app.tree()); - app.click("rich-embed-size-1"); - app.eventually("a quarter of the width", |tree| (width(tree) - whole / 4.0).abs() < 2.0); - app.drag_in("rich-embed-resize", (12.0, 12.0), (1_200.0, 12.0)); - app.eventually("the whole width again", |tree| (width(tree) - whole).abs() < 2.0); - app.capture("des-13-sized"); - close_editor(&mut app); - open_card(&mut app, "Avec dessin"); - app.eventually("kept", |tree| (width(tree) - whole).abs() < 2.0); - close_editor(&mut app); - }); - - app.quit(); -} - -#[test] -fn recette_on_the_canvas() { - let profile = tempfile::tempdir().unwrap(); - let mut app = a_new_library("38_recette_canvas", profile.path()); - - step("MET-01 three spellings are one tag", || { - a_snippet(&mut app, "Avec tags", "echo tags"); - open_card(&mut app, "Avec tags"); - for tag in ["devops", "#DevOps", " DEVOPS "] { - app.fill("editor-tag-add", tag); - app.press(Key::Enter, Modifiers::NONE); - } - app.eventually("one tag", |tree| tree.count("editor-tag") == 1); - close_editor(&mut app); - }); - - step("CLV-01 the arrows walk the cards, Enter opens", || { - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::ArrowRight, Modifiers::NONE); - app.press(Key::Enter, Modifiers::NONE); - app.wait_for("editor-title"); - close_editor(&mut app); - }); - - step("MET-04 P pins and unpins, no date moves", || { - let sorted = |mut dates: Vec| { - dates.sort(); - dates - }; - let when = sorted(app.tree().texts("note-card-when")); - let pinned = app.tree().count("note-card-pin"); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::P, Modifiers::NONE); - app.eventually("the pin moved", |tree| tree.count("note-card-pin") != pinned); - assert_eq!(sorted(app.tree().texts("note-card-when")), when); - app.click("undo-restore"); - app.eventually("the pin is back", |tree| tree.count("note-card-pin") == pinned); - }); - - step("CLV-02 C copies a plain card and says so", || { - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::C, Modifiers::NONE); - app.wait_for("status-toast"); - app.capture("clv-02"); - }); - - step("SEL-02 a selection moved to a space, and taken back", || { - app.click("space-create-open"); - app.fill("space-create-input", "Perso"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown, empty", |tree| !tree.has("note-card")); - app.click("space-option-all"); - app.eventually("the cards are back", |tree| tree.has("note-card")); - app.press(Key::ArrowDown, Modifiers::NONE); - for key in [Key::X, Key::ArrowRight, Key::X] { - app.press(key, Modifiers::NONE); - } - app.click("selection-move"); - app.click_where("selection-move-place", |node| node.label() == Some("Perso")); - app.wait_for("undo-text"); - app.capture("sel-02"); - app.click("undo-restore"); - app.eventually("the bar went", |tree| !tree.has("undo-text")); - }); - - step("SEL-09 a selection trashed, then given back whole", || { - let cards = app.tree().count("note-card"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection let go", |tree| !tree.has("selection-count")); - app.press(Key::ArrowDown, Modifiers::NONE); - for key in [Key::X, Key::ArrowRight, Key::X] { - app.press(key, Modifiers::NONE); - } - app.click("selection-delete"); - app.click("selection-delete"); - app.eventually("two left", |tree| tree.count("note-card") == cards - 2); - app.click("undo-restore"); - app.eventually("both back", |tree| tree.count("note-card") == cards); - }); - - app.quit(); -} - -#[test] -fn recette_a_line_gone_to() { - let profile = tempfile::tempdir().unwrap(); - let mut app = a_new_library("38_recette_go_to_line", profile.path()); - - step("COD-15 Ctrl+Alt+G goes to a line, the keys back in the code", || { - app.click("new-note"); - app.fill("editor-title", "Lignes"); - app.click("editor-body"); - app.paste("un\ndeux\ntrois"); - app.press(Key::G, Modifiers::COMMAND | Modifiers::ALT); - app.eventually("the field has the focus", |tree| tree.focused().starts_with("go-to-line-input")); - app.type_text("2"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the code has the focus", |tree| { - !tree.has("go-to-line-input") && tree.focused().starts_with("editor-body") - }); - app.type_text("X"); - app.eventually("typed on line 2", |tree| code(tree) == "un\nXdeux\ntrois"); - close_editor(&mut app); - }); - - app.quit(); -} - -/// The focus follows the card: the second P reaches the note the first one moved. -#[test] -fn recette_a_second_p_gives_the_card_back() { - let profile = tempfile::tempdir().unwrap(); - let mut app = a_new_library("38_ko_met_04", profile.path()); - app.eventually("the six samples", |tree| tree.count("note-card") == 6); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::ArrowRight, Modifiers::NONE); - app.press(Key::P, Modifiers::NONE); - app.eventually("a second pin", |tree| tree.count("note-card-pin") == 2); - app.press(Key::P, Modifiers::NONE); - app.eventually("back to one pin", |tree| tree.count("note-card-pin") == 1); - app.quit(); -} diff --git a/e2e/tests/39_recette_tools.rs b/e2e/tests/39_recette_tools.rs deleted file mode 100644 index 23f3c76e9..000000000 --- a/e2e/tests/39_recette_tools.rs +++ /dev/null @@ -1,480 +0,0 @@ -//! The acceptance sheet's main paths through the tools: each case typed as the sheet writes it and -//! its answer read from the window, in French, the sheet's language. A step opens on the case it -//! runs, so that a run can be read back into the sheet. - -use e2e::{App, PASSPHRASE, step}; -use egui::{Key, Modifiers}; - -const FRENCH: &str = "setting-locale-1"; -const JWT: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJyZWNldHRlIiwibmFtZSI6IlJlY2V0dGUgRGV2Tm90ZXMiLCJpYXQiOjE3NjcyMjU2MDAsImV4cCI6MTkyNDk5MjAwMH0.89V7D9SwqkMbyIoAbtwhgH3y8UgxyoI4vKAN_pgawSY"; -const PIXEL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; -const SCHEMA: &str = r#"{"type":"object","required":["id","email","age","role"],"properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string","format":"email"},"age":{"type":"integer","minimum":18,"maximum":99},"role":{"enum":["admin","lecteur","redacteur"]}}}"#; - -/// One line of the sheet: the tool, its field, what is typed, and what must be read. -type Case = (&'static str, &'static str, &'static str, &'static str, &'static [&'static str]); - -const CASES: &[Case] = &[ - ( - "TXT-01", - "case", - "case-input", - "parse HTTP response", - &[ - "parseHttpResponse", - "ParseHttpResponse", - "parse_http_response", - "PARSE_HTTP_RESPONSE", - "parse-http-response", - "Parse-Http-Response", - "parse.http.response", - "parse/http/response", - "parsehttpresponse", - "Parse Http Response", - "Parse http response", - "PARSE HTTP RESPONSE", - ], - ), - ( - "CRY-01", - "hash", - "hash-input", - "DevNotes", - &[ - "7fd0b69809fbca9dc53d03ab5450e18d", - "f8148cf8eb16a1419d5ffa6819b8338ed76a13b2", - "7a215fd1357dc4712283d610bd18335a1e28066bc839535bca7c10c5069ea3bb", - "a1c24cfd5aac355e70003a964af2264228f8214317d3f9f004a89133b340a2ed", - "345e99d395", - "8 octets", - ], - ), - ( - "ENC-01", - "url-codec", - "url-codec-decoded", - "café crème & croissants", - &["caf%C3%A9%20cr%C3%A8me%20%26%20croissants"], - ), - ( - "ENC-06", - "base64", - "base64-input", - "Café ☕", - &[ - "6 caractères", - "9 octets", - "Q2Fmw6kg4piV", - "INQWNQ5JEDRJRFI=", - "43 61 66 c3 a9 20 e2 98 95", - "67 97 102 195 169 32 226 152 149", - ], - ), - ( - "ENC-13", - "convert", - "convert-input", - r#"{"service":"billing","replicas":2,"tags":["api","web"],"debug":null}"#, - &["service: billing", "replicas: 2", "debug: null"], - ), - ("ENC-19", "colour", "colour-input", "#1e90ff", &["#1e90ff", "30 144 255", "209.6", "oklch("]), - ("GEN-18", "qr", "qr-url", "https://devnotes.fr", &["Récupérable"]), - ("TPS-01", "dates", "dates-input", "1790000000", &["2026-09-21T14:13:20Z", "secondes", "lundi"]), - ("TPS-18", "cron", "cron-input", "*/15 9-18 * * MON-FRI", &["15 minutes", "lundi", "vendredi"]), - ("CMP-01", "sizes", "sizes-input", "1,5 Go", &["1 500 000 000", "1,397", "1 430,51", "12"]), - ("CMP-07", "permissions", "permissions-octal", "755", &["rwxr-xr-x", "chmod"]), - ("CMP-13", "checks", "checks-input", "4111 1111 1111 1111", &["Valide", "Visa"]), - ( - "CMP-13", - "checks", - "checks-input", - "4111 1111 1111 1112", - &["Invalide", "Le dernier chiffre devrait être 1."], - ), - ("CMP-13", "checks", "checks-input", "378282246310005", &["Valide", "American Express"]), - ("CMP-13", "checks", "checks-input", "5555 5555 5555 4444", &["Valide", "Mastercard"]), - ( - "CMP-14", - "checks", - "checks-input", - "FR14 2004 1010 0505 0001 3M02 606", - &["20041", "01005", "0500013M026", "06", "Valide"], - ), - ( - "CMP-19", - "cidr", - "cidr-network", - "10.24.8.0/21", - &[ - "10.24.8.0", - "255.255.248.0", - "0.0.7.255", - "10.24.8.1", - "10.24.15.254", - "10.24.15.255", - "2 046", - "2 048", - ], - ), -]; - -/// From the home, its search emptied: the window is wide enough for every tool to be in view. -fn open_tool(app: &mut App, tool: &str) { - if app.has("tool-back") { - app.click("tool-back"); - } - app.wait_for("tools-search"); - app.click("tools-search"); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Backspace, Modifiers::NONE); - app.click(&format!("tools-entry-{tool}")); - app.wait_for("tool-title"); -} - -fn reads(app: &mut App, words: &[&str]) { - for word in words { - app.eventually(&format!("« {word} » is read"), |tree| tree.mentions(word)); - } -} - -fn retype(app: &mut App, field: &str, input: &str) { - app.click(field); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Backspace, Modifiers::NONE); - app.paste(input); -} - -fn in_french(app: &mut App) { - app.click("file-menu"); - app.click("file-preferences"); - app.click("setting-locale"); - app.click(FRENCH); - app.click("settings-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); -} - -fn the_tools(scenario: &'static str, profile: &std::path::Path) -> App { - let mut app = App::launch(scenario, profile); - app.create_library(); - in_french(&mut app); - app.resize(1800, 1000); - app.press(Key::Num2, Modifiers::COMMAND); - app.wait_for("area-tools"); - app -} - -#[test] -fn recette_the_table_of_the_sheet() { - let profile = tempfile::tempdir().unwrap(); - let mut app = the_tools("39_recette_tools", profile.path()); - for (case, tool, field, input, words) in CASES { - step(&format!("{case} {tool}: {input}"), || { - open_tool(&mut app, tool); - retype(&mut app, field, input); - reads(&mut app, words); - app.capture(&format!("{case}-{tool}")); - }); - } - app.quit(); -} - -#[test] -fn recette_tools_of_several_gestures() { - let profile = tempfile::tempdir().unwrap(); - let mut app = the_tools("39_recette_gestures", profile.path()); - - step("TXT-07 mixed endings are read and put right", || { - open_tool(&mut app, "line-breaks"); - retype(&mut app, "line-breaks-input", "un\r\ndeux \ntrois\rquatre "); - app.wait_for("line-breaks-found"); - app.capture("TXT-06"); - app.click("line-breaks-trim"); - app.capture("TXT-07"); - }); - - step("TXT-08 what is counted of a flag", || { - open_tool(&mut app, "text-stats"); - retype(&mut app, "text-stats-input", "Hé 🇫🇷\nok"); - reads(&mut app, &["7", "8", "10", "15"]); - app.capture("TXT-08"); - }); - - step("TXT-11 two texts compared", || { - open_tool(&mut app, "diff"); - retype(&mut app, "text-diff-a", "un\ndeux\ntrois\n"); - retype(&mut app, "text-diff-b", "un\n2\n3\n"); - app.wait_for("text-diff-rows"); - app.capture("TXT-11"); - app.click("tool-clear"); - }); - - step("TXT-14 two documents compared as data", || { - app.click("diff-mode-1"); - retype(&mut app, "structured-diff-a", r#"{"total":126,"client":{"ville":"Lyon"},"remise":null}"#); - retype( - &mut app, - "structured-diff-b", - r#"{"total":138,"client":{"ville":"Villeurbanne"},"payeeLe":"2026-10-02"}"#, - ); - reads(&mut app, &["total", "client.ville", "remise", "payeeLe"]); - app.capture("TXT-14"); - app.click("tool-clear"); - }); - - app.quit(); -} - -#[test] -fn recette_crypto() { - let profile = tempfile::tempdir().unwrap(); - let mut app = the_tools("39_recette_crypto", profile.path()); - - step("CRY-03 HMAC in hex, then in base64", || { - open_tool(&mut app, "hash"); - retype(&mut app, "hash-input", "DevNotes"); - app.click("hash-hmac"); - retype(&mut app, "hash-key", "secret"); - reads(&mut app, &["4b86bba0e71ff3bea4180fc0ee8abc4d7f5939927d5f1a1acee89b837e47ec7a"]); - app.click("hash-encoding-1"); - reads(&mut app, &["S4a7oOcf876kGA/A7oq8TX9ZOZJ9Xxoazuibg35H7Ho="]); - app.capture("CRY-03"); - }); - - step("CRY-08 passwords drawn, and drawn again", || { - open_tool(&mut app, "password"); - app.wait_for("password-strength"); - app.capture("CRY-08"); - let first = app.tree().texts("output-value"); - app.click("password-generate"); - app.eventually("others are drawn", |tree| tree.texts("output-value") != first); - }); - - step("CRY-11 identifiers of each kind", || { - open_tool(&mut app, "identifiers"); - app.wait_for("identifiers-row"); - app.capture("CRY-11"); - }); - - step("CRY-12 identifiers read back", || { - for (id, words) in [ - ("01ARZ3NDEKTSV4RRFFQ69G5FAV", &["ULID", "2016"][..]), - ("550e8400-e29b-41d4-a716-446655440000", &["UUID", "RFC 9562"]), - ("507f1f77bcf86cd799439011", &["ObjectId", "2012"]), - ("00000000-0000-0000-0000-000000000000", &["UUID nul"]), - ("bonjour", &["Aucun identifiant connu"]), - ] { - retype(&mut app, "identifiers-checked", id); - reads(&mut app, words); - } - app.capture("CRY-12"); - }); - - step("CRY-13 a token read and checked", || { - open_tool(&mut app, "jwt"); - retype(&mut app, "jwt-token", JWT); - reads(&mut app, &["HS256", "recette", "Recette DevNotes"]); - app.click("jwt-secret"); - app.type_text("secret"); - reads(&mut app, &["Signature valide."]); - app.capture("CRY-13"); - }); - - app.quit(); -} - -#[test] -fn recette_encoders() { - let profile = tempfile::tempdir().unwrap(); - let mut app = the_tools("39_recette_encoders", profile.path()); - - step("ENC-04 a URL taken apart", || { - open_tool(&mut app, "url-codec"); - app.click("url-tab-1"); - retype( - &mut app, - "url-parser-input", - "https://ada:pwd@api.exemple.fr:8443/v1/factures?statut=payée&page=2#total", - ); - reads(&mut app, &["https", "ada", "pwd", "api.exemple.fr", "8443", "/v1/factures", "payée", "total"]); - app.capture("ENC-04"); - }); - - step("ENC-08 a format recognised, ENC-11 a picture shown", || { - open_tool(&mut app, "base64"); - app.click("base64-direction-1"); - for (written, read) in [ - ("Q2Fmw6k=", "Café"), - ("43 61 66 c3 a9", "Café"), - ("01000011 01100001", "Ca"), - ("67 97 102", "Caf"), - ] { - retype(&mut app, "base64-input", written); - reads(&mut app, &[read]); - } - app.capture("ENC-08"); - retype(&mut app, "base64-input", PIXEL); - app.wait_for("base64-image-facts"); - app.capture("ENC-11"); - }); - - step("ENC-19 what is no colour, ENC-20 a contrast put right", || { - open_tool(&mut app, "colour"); - retype(&mut app, "colour-input", "pas-une-couleur"); - app.wait_for("colour-invalid"); - retype(&mut app, "colour-input", "#777777"); - retype(&mut app, "colour-against", "#ffffff"); - reads(&mut app, &["4,48"]); - app.click("colour-fix"); - reads(&mut app, &["4,5"]); - app.capture("ENC-20"); - }); - - app.quit(); -} - -#[test] -fn recette_the_rest() { - let profile = tempfile::tempdir().unwrap(); - let mut app = the_tools("39_recette_rest", profile.path()); - - step("GEN-01 documents drawn from a schema", || { - open_tool(&mut app, "json-generator"); - retype(&mut app, "json-generator-input", SCHEMA); - retype(&mut app, "json-generator-count", "3"); - app.wait_for("json-generator-seed-used"); - app.capture("GEN-01"); - }); - - step("GEN-16 lorem ipsum, opening on its words", || { - open_tool(&mut app, "lorem"); - reads(&mut app, &["Lorem ipsum dolor sit amet, consectetur adipiscing elit"]); - let first = app.tree().text("lorem-output"); - app.click("lorem-again"); - app.eventually("another text", |tree| tree.text("lorem-output") != first); - }); - - step("TPS-07 a gap, TPS-10 a duration", || { - open_tool(&mut app, "dates"); - app.wait_for("dates-input"); - retype(&mut app, "dates-from", "2026-01-01 00:00"); - retype(&mut app, "dates-to", "2026-03-01 12:00"); - reads(&mut app, &["59 j 12 h 00", "8 sem 3 j", "1 428 h 00"]); - app.capture("TPS-07"); - retype(&mut app, "dates-duration", "PT1H30M"); - reads(&mut app, &["5 400"]); - retype(&mut app, "dates-duration", "1h30"); - reads(&mut app, &["PT1H30M"]); - retype(&mut app, "dates-duration", "P1M"); - reads(&mut app, &["Un mois ou une année n’a pas de durée fixe"]); - app.capture("TPS-10"); - }); - - step("CMP-13 numbers drawn that pass", || { - open_tool(&mut app, "checks"); - app.wait_for("checks-numbers"); - retype(&mut app, "checks-prefix", "4242"); - app.eventually("five that begin so", |tree| { - let drawn = tree.texts("output-value"); - drawn.len() == 5 && drawn.iter().all(|it| it.starts_with("4242")) - }); - app.capture("CMP-13-generate"); - }); - - step("CMP-05 a transfer timed", || { - open_tool(&mut app, "sizes"); - app.wait_for("sizes-input"); - retype(&mut app, "transfer-size", "4,7"); - retype(&mut app, "transfer-rate", "100"); - reads(&mut app, &["6 min 16 s"]); - app.capture("CMP-05"); - }); - - step("REF-01 a status found by code, name and words", || { - open_tool(&mut app, "http-status"); - for searched in ["418", "teapot", "trop de requêtes"] { - retype(&mut app, "reference-search", searched); - app.eventually("one row answers", |tree| tree.count("reference-row") == 1); - } - app.capture("REF-01"); - }); - - app.quit(); -} - -#[test] -fn recette_the_home() { - let profile = tempfile::tempdir().unwrap(); - let mut app = the_tools("39_recette_home", profile.path()); - - step("OUT-01 the home says what it holds", || { - reads(&mut app, &["32 utilitaires, tous hors ligne"]); - app.capture("OUT-01"); - }); - - step("OUT-02 a category found by its name, without its accents", || { - app.fill("tools-search", "generateur"); - for tool in ["json-generator", "identity", "lorem", "qr"] { - app.wait_for(&format!("tools-entry-{tool}")); - } - }); - - step("OUT-03 a reference found, opened by Enter", || { - app.press(Key::A, Modifiers::COMMAND); - app.type_text("418"); - app.wait_for("tools-reference-hit"); - reads(&mut app, &["teapot"]); - app.capture("OUT-03"); - app.press(Key::Enter, Modifiers::NONE); - app.wait_for("reference-search"); - app.click("tool-back"); - }); - - step("OUT-09 an example, then cleared", || { - open_tool(&mut app, "case"); - app.click("tool-sample"); - app.eventually("the field is filled", |tree| { - tree.find("case-input") - .and_then(egui::accesskit::Node::value) - .is_some_and(|it| !it.is_empty()) - }); - app.click("tool-clear"); - app.eventually("the field is empty", |tree| { - tree.find("case-input") - .and_then(egui::accesskit::Node::value) - .is_none_or(str::is_empty) - }); - }); - - step("OUT-10 what a tool worked out is kept as a note", || { - open_tool(&mut app, "hash"); - retype(&mut app, "hash-input", "DevNotes"); - app.click("tool-save-as-note"); - app.wait_for("save-as-note-what"); - app.capture("OUT-10-dialog"); - app.click("save-as-note-submit"); - app.wait_for("status-toast"); - app.capture("OUT-10-saved"); - }); - - step("OUT-07 three favourites over a relaunch", || { - for tool in ["case", "hash", "cron"] { - open_tool(&mut app, tool); - app.click("tool-favourite"); - } - app.click("tool-back"); - app.wait_for("tools-favourite-cron"); - }); - - let mut app = app.relaunch(); - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-tools"); - - step("OUT-07 they are still there, and go one by one", || { - for tool in ["case", "hash", "cron"] { - app.wait_for(&format!("tools-favourite-{tool}")); - } - app.capture("OUT-07"); - }); - - app.quit(); -} diff --git a/e2e/tests/40_recette_http.rs b/e2e/tests/40_recette_http.rs deleted file mode 100644 index dee05238d..000000000 --- a/e2e/tests/40_recette_http.rs +++ /dev/null @@ -1,273 +0,0 @@ -//! The acceptance sheet's main paths through the HTTP area that no other scenario walks whole, on -//! the local server. A step opens on the case it runs, so that a run can be read back into the -//! sheet. - -use e2e::{App, Tree, step}; -use egui::accesskit::Node; -use egui::{Key, Modifiers}; - -const COLLECTION: &str = "Recette API"; -const BASIC: &str = "http-auth-kind-2"; -const BEARER: &str = "http-auth-kind-3"; -const POST: &str = "http-method-1"; -const JSON_BODY: &str = "http-body-kind-1"; -const BIG: &str = r#"{"nom":"Recette","grand":12345678901234567890,"prix":1.10}"#; - -fn values(tree: &Tree, author_id: &str) -> Vec { - tree.all(author_id) - .into_iter() - .map(|node| node.value().unwrap_or_default().to_owned()) - .collect() -} - -fn url_of(tree: &Tree) -> String { - tree.find("http-url").and_then(Node::value).unwrap_or_default().to_owned() -} - -fn set_url(app: &mut App, url: &str) { - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(url); -} - -fn send(app: &mut App, url: &str) { - set_url(app, url); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the answer is shown", |tree| { - tree.has("http-response-status") && !tree.has("http-response-sending") - }); -} - -fn answers(app: &mut App, words: &str) { - app.eventually(&format!("the answer says {words}"), |tree| { - tree.text("http-response-pretty") - .or_else(|| tree.text("http-response-body")) - .is_some_and(|body| body.contains(words)) - }); -} - -fn a_draft(app: &mut App) { - app.click("http-tab-new"); - app.wait_for("http-url"); -} - -fn http(scenario: &'static str, profile: &std::path::Path) -> App { - let mut app = App::launch(scenario, profile); - app.create_library(); - app.press(Key::Num3, Modifiers::COMMAND); - app.wait_for("http-rail-title"); - app -} - -#[test] -fn recette_composing() { - let profile = tempfile::tempdir().unwrap(); - let mut app = http("40_recette_composing", profile.path()); - app.resize(1100, 1100); - - step("HRQ-01 a new request writes nothing", || { - a_draft(&mut app); - set_url(&mut app, "https://exemple.fr/get"); - app.click_nth("http-tab-close", 0); - app.wait_for("http-close-dialog"); - app.capture("hrq-01"); - app.click("http-close-discard"); - app.wait_for("http-rail-empty"); - }); - - step("HRL-01 a first collection", || { - app.click("http-rail-empty-create"); - app.fill("http-create-input", COLLECTION); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("it is listed", |tree| tree.texts("http-node-name") == [COLLECTION]); - }); - - step("HRQ-02 saved: a name is asked, and a place", || { - a_draft(&mut app); - set_url(&mut app, "https://exemple.fr/facture"); - app.press(Key::S, Modifiers::COMMAND); - app.wait_for("http-save-dialog"); - app.click("http-save-name"); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Backspace, Modifiers::NONE); - app.click("http-save-submit"); - app.wait_for("http-save-missing"); - app.capture("hrq-02"); - app.fill("http-save-name", "Lire une facture"); - app.click("http-save-submit"); - app.eventually("it is in the rail", |tree| { - tree.texts("http-node-name").iter().any(|it| it.ends_with("Lire une facture")) - }); - }); - - step("HRQ-04 a saved request changed asks before it closes", || { - set_url(&mut app, "https://exemple.fr/autre"); - app.capture("hrq-04-dot"); - app.click_nth("http-tab-close", 0); - app.wait_for("http-close-modified"); - app.click("http-close-cancel"); - app.eventually("the dialog closed", |tree| !tree.has("http-close-dialog")); - }); - - step("HRQ-05 the URL and its table agree", || { - set_url(&mut app, "https://exemple.fr/get?page=2&q=café"); - app.eventually("the table reads the URL", |tree| { - values(tree, "http-kv-key").starts_with(&["page".to_owned(), "q".to_owned()]) - }); - app.click_nth("http-kv-enabled", 1); - app.eventually("q leaves the URL and stays in the table", |tree| { - !url_of(tree).contains("q=") && values(tree, "http-kv-key")[1] == "q" - }); - app.click_nth("http-kv-key", 2); - app.type_text("limit"); - app.click_nth("http-kv-value", 2); - app.type_text("10"); - app.eventually("limit joins the URL", |tree| url_of(tree).contains("limit=10")); - append_to_url(&mut app, "&x={{page}}"); - app.eventually("a variable stays as written", |tree| url_of(tree).contains("{{page}}")); - }); - - step("HRQ-06 headers pasted are as many rows, typed ones split", || { - app.click("http-section-headers"); - app.wait_for("http-implied-headers"); - app.click_nth("http-kv-key", 0); - app.paste("Accept: application/json\nX-Trace: abc\nX-Tenant: recette"); - app.eventually("three rows", |tree| { - values(tree, "http-kv-key").starts_with(&[ - "Accept".to_owned(), - "X-Trace".to_owned(), - "X-Tenant".to_owned(), - ]) - }); - let last = app.tree().count("http-kv-key") - 1; - app.click_nth("http-kv-key", last); - app.type_text("X-Recette: 1"); - app.eventually("key and value apart", |tree| { - values(tree, "http-kv-key").contains(&"X-Recette".to_owned()) - && values(tree, "http-kv-value").contains(&"1".to_owned()) - }); - }); - - what_goes_with_it(&mut app); - app.quit_discarding(); -} - -fn what_goes_with_it(app: &mut App) { - step("HRQ-09 what leaves unasked is said", || { - a_draft(app); - set_url(app, "https://exemple.fr/post"); - app.click("http-section-body"); - app.click(JSON_BODY); - app.fill("http-body-text", "{}"); - app.click("http-section-headers"); - app.eventually("the implied headers are said", |tree| { - let said = tree.texts("http-implied-value").join(" "); - said.contains("DevNotes/") && said.contains("*/*") && said.contains("application/json") - }); - app.capture("hrq-09"); - }); - - step("HRL-06 a folder deleted says which change goes with it", || { - app.click_where("http-node-menu", |node| node.label().is_some_and(|it| it.ends_with(COLLECTION))); - app.click("http-node-delete"); - app.wait_for("http-delete-unsaved"); - app.capture("hrl-06"); - app.click("http-delete-cancel"); - app.eventually("nothing went", |tree| !tree.has("http-delete-unsaved")); - assert_eq!(app.tree().count("http-node-name"), 2); - }); -} - -fn append_to_url(app: &mut App, words: &str) { - app.click("http-url"); - app.press(Key::End, Modifiers::NONE); - app.type_text(words); -} - -#[test] -fn recette_sending() { - let profile = tempfile::tempdir().unwrap(); - let mut app = http("40_recette_sending", profile.path()); - let port = e2e::serve(); - let at = |path: &str| format!("http://127.0.0.1:{port}{path}"); - a_draft(&mut app); - - step("HRQ-10 Basic, its password hidden until asked", || { - app.click("http-section-auth"); - app.click("http-auth-kind"); - app.click(BASIC); - app.fill("http-auth-username", "ada"); - app.fill("http-auth-secret", "secret"); - app.capture("hrq-10-hidden"); - send(&mut app, &at("/echo")); - answers(&mut app, "Basic YWRhOnNlY3JldA=="); - }); - - step("HRQ-11 Bearer", || { - app.click("http-auth-kind"); - app.click(BEARER); - app.click("http-auth-secret"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("jeton-recette"); - send(&mut app, &at("/echo")); - answers(&mut app, "Bearer jeton-recette"); - }); - - step("HHI-02 the history masks both", || { - app.click("http-history-open"); - app.wait_for("http-history-item"); - app.click("http-history-item"); - app.wait_for("http-history-url"); - app.capture("hhi-02"); - app.eventually("no secret is read", |tree| { - !tree.mentions("jeton-recette") && !tree.mentions("YWRhOnNlY3JldA==") - }); - app.click("http-history-reopen"); - app.eventually("back to the request", |tree| !tree.has("http-history")); - }); - - step("HRQ-14 a JSON body leaves as it was written", || { - app.click("http-method"); - app.click(POST); - app.click("http-section-body"); - app.click(JSON_BODY); - app.click("http-body-text"); - app.paste(BIG); - send(&mut app, &at("/echo")); - answers(&mut app, BIG); - }); - - step("HRS-02 a send under way is said, and cancelled", || { - set_url(&mut app, &at("/slow")); - app.press(Key::Enter, Modifiers::COMMAND); - app.wait_for("http-response-sending"); - app.capture("hrs-02"); - app.click("http-send"); - app.wait_for("http-response-cancelled"); - }); - - step("HRS-04 the views of a body", || { - app.click("http-method"); - app.click("http-method-0"); - send(&mut app, &at("/json")); - for view in ["http-response-view-0", "http-response-view-1", "http-response-view-3"] { - app.click(view); - app.capture(view); - } - app.click("http-response-view-0"); - send(&mut app, &at("/png")); - app.wait_for("http-response-image"); - send(&mut app, &at("/bytes")); - app.wait_for("http-response-binary"); - app.capture("hrs-04-binary"); - }); - - step("HRS-06 redirects are followed and counted", || { - send(&mut app, &at("/redirect/3")); - app.click("http-response-section-timeline"); - app.wait_for("http-response-redirect"); - app.capture("hrs-06"); - }); - - app.quit_discarding(); -} diff --git a/e2e/tests/41_note_fullscreen.rs b/e2e/tests/41_note_fullscreen.rs deleted file mode 100644 index 5eccac03c..000000000 --- a/e2e/tests/41_note_fullscreen.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! A note expanded over the cards, with the layout of its kind: a snippet's fields over its code -//! and its text filled under it, the details in a column beside the body and put away, a task -//! list narrowed to the tasks done, and a title typed before J: the draft is written when the -//! next note opens. The scenario writes its own notes: the samples' names are translated. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -const SHIFT_COMMAND: Modifiers = Modifiers::COMMAND.plus(Modifiers::SHIFT); -const RENAMED: &str = "Renamed while expanded"; - -fn open_title(tree: &Tree) -> String { - tree.find("editor-title") - .and_then(|title| title.value()) - .unwrap_or_default() - .to_owned() -} - -fn close(app: &mut App) { - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); -} - -/// The left edge of the expanded note's title. -fn note_left(tree: &Tree) -> f64 { - tree.find("editor-title") - .and_then(egui::accesskit::Node::bounds) - .map_or(f64::NAN, |bounds| bounds.x0) -} - -/// The header stays over the expanded note: its toggle folds the sidebar and the note widens. -fn sidebar_folded_under_an_expanded_note(app: &mut App) { - let left = note_left(&app.tree()); - app.click("library-rail-toggle"); - app.eventually("the note took the sidebar's room", |tree| note_left(tree) < left - 100.0); - app.click("library-rail-toggle"); - app.eventually("and gave it back", |tree| (note_left(tree) - left).abs() < 1.0); -} - -#[test] -fn note_fullscreen() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("41_note_fullscreen", profile.path()); - app.create_library(); - app.wait_for("note-card"); - // Room for the details beside the body. - app.resize(1_440, 900); - - step("a snippet expanded: its fields over the code, filled under it, details beside", || { - app.click("new-note-kind"); - app.click("new-note-snippet"); - app.fill("editor-title", "Connexion"); - app.click("editor-body"); - app.paste("psql -h {{host}} -p {{port=5432}}"); - app.click("editor-title"); - app.wait_for("placeholder-input"); - app.click("editor-fullscreen"); - app.eventually("the column and the filled text", |tree| { - !tree.has("note-card") && tree.has("editor-space") && tree.has("editor-filled") - }); - app.click_nth("placeholder-input", 0); - app.type_text("db.internal"); - app.click("editor-title"); - app.eventually("one field of two filled", |tree| { - tree.find("placeholder-panel-toggle").and_then(|toggle| toggle.value()) == Some("1/2") - }); - app.capture("snippet"); - }); - - step("the details are put away, then shown again", || { - app.click("editor-details"); - app.eventually("the column gone", |tree| !tree.has("editor-space")); - app.click("editor-details"); - app.wait_for("editor-space"); - }); - - step("expanded, the sidebar is folded by its toggle", || { - sidebar_folded_under_an_expanded_note(&mut app); - close(&mut app); - }); - - step("a task list expanded narrows to the tasks done", || { - app.press(Key::L, SHIFT_COMMAND); - app.fill("editor-title", "Tâches"); - app.click("checklist-add"); - app.type_text("Préparer"); - app.press(Key::Enter, Modifiers::NONE); - app.type_text("Déployer"); - app.wait_for("checklist-shown-0"); - let all = app.tree().count("checklist-text"); - app.click_nth("checklist-check", 0); - app.click("checklist-shown-2"); - app.eventually("the task done, alone", |tree| tree.count("checklist-text") == 1); - app.capture("tasks"); - app.click("checklist-shown-0"); - app.eventually("every task again", |tree| tree.count("checklist-text") == all); - close(&mut app); - }); - - step("a title typed is written when J opens the next note", || { - app.click_nth("note-card-open", 0); - app.wait_for("editor-position"); - app.click("editor-title"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(RENAMED); - // The title takes the keys: Escape gives it up first. - app.press(Key::Escape, Modifiers::NONE); - app.press(Key::J, Modifiers::NONE); - app.eventually("the next note open", |tree| tree.has("editor-title") && open_title(tree) != RENAMED); - // Stepped to, the note leaves the keys to J and K. - app.press(Key::K, Modifiers::NONE); - app.eventually("the draft written", |tree| open_title(tree) == RENAMED); - }); - - app.quit(); -} diff --git a/e2e/tests/42_documentation.rs b/e2e/tests/42_documentation.rs deleted file mode 100644 index 65dad1880..000000000 --- a/e2e/tests/42_documentation.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! About › Documentation: its pages, read without the network, a search that leads to a section, -//! a link from one page to another, and the way out. Addressed by the pages' names, the same in -//! both languages; what is searched is a word of both. - -use e2e::{App, Tree, step}; -use egui::{Key, Modifiers}; - -fn title(tree: &Tree) -> String { - tree.text("docs-title").unwrap_or_default() -} - -#[test] -fn documentation() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("42_documentation", profile.path()); - app.create_library(); - - step("the About menu opens it on the overview", || { - app.click("about-open"); - app.click("about-documentation"); - app.wait_for("docs-dialog"); - app.wait_for("docs-card-start"); - }); - - step("a card leads to its page, and the page to the next", || { - let overview = title(&app.tree()); - app.click("docs-card-start"); - app.eventually("another page is read", |tree| title(tree) != overview); - let start = title(&app.tree()); - app.click("docs-page-writing"); - app.eventually("a page is chosen in the list", |tree| title(tree) != start); - }); - - step("a search answers sections, and one of them is read", || { - app.fill("docs-search", "Argon2id"); - app.eventually("the list gave way to the answers", |tree| { - tree.has("docs-result") && !tree.has("docs-page-start") - }); - app.click("docs-result"); - app.eventually("the list is back", |tree| tree.has("docs-page-start")); - }); - - step("Escape closes it", || { - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the window is closed", |tree| !tree.has("docs-dialog")); - }); -} diff --git a/e2e/tests/43_close_to_tray.rs b/e2e/tests/43_close_to_tray.rs deleted file mode 100644 index 52c372996..000000000 --- a/e2e/tests/43_close_to_tray.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Closing with « Close to tray » on hides the window and keeps the application, tray icon or not, -//! the same on every system; a second launch, the palette's global action or the tray's menu brings -//! it back, the palette open when asked. Off, the close button ends the application. Under Linux -//! the tray itself is driven too: a watcher served on a bus of the scenario's own, started after -//! the application as a session's panel may be, gets the item, and its menu answers. - -use e2e::{App, step}; -use egui::{Key, Modifiers}; - -const CARDS: usize = 6; - -/// Closed as its close button does; how many times the window had gone out of sight before. -/// Nothing is read while it is away: macOS minimises it, and a minimised window paints nothing. -fn close(app: &mut App) -> u32 { - let before = put_away(app); - app.act_hiding("close"); - before -} - -fn put_away(app: &mut App) -> u32 { - let tree = app.tree(); - tree.text("window-put-away") - .and_then(|count| count.parse().ok()) - .expect("the e2e flavour counts the window put away") -} - -/// Back in sight, having gone once more: the close hid it, and what brought it back found the -/// same process, its library still open. -fn back(app: &mut App, before: u32, also: impl Fn(&e2e::Tree) -> bool) { - let once_more = (before + 1).to_string(); - app.eventually("the window went out of sight once, and is back", |tree| { - tree.has("window-shown") - && tree.text("window-put-away").as_deref() == Some(once_more.as_str()) - && also(tree) - }); -} - -fn with_the_palette(tree: &e2e::Tree) -> bool { - tree.focused().starts_with("palette-input") -} - -fn close_the_palette(app: &mut App) { - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the palette is closed", |tree| !tree.has("palette-input")); -} - -#[test] -fn close_to_tray() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("43_close_to_tray", profile.path()); - app.create_library(); - app.eventually("the samples are drawn", |tree| { - tree.count("note-card") == CARDS && tree.has("window-shown") - }); - - step("closed, it hides, and a second launch, as the menu's entry, brings it back", || { - let before = close(&mut app); - app.launch_again(); - back(&mut app, before, |tree| tree.count("note-card") == CARDS && !tree.has("palette-input")); - }); - - step("hidden, the palette's global action brings it back with the palette", || { - let before = close(&mut app); - app.act("palette"); - back(&mut app, before, with_the_palette); - close_the_palette(&mut app); - }); - - step("the tray's Palette does the same", || { - let before = close(&mut app); - app.act("tray:palette"); - back(&mut app, before, with_the_palette); - close_the_palette(&mut app); - }); - - step("the tray's Open brings the window back as it was", || { - let before = close(&mut app); - app.act("tray:open"); - back(&mut app, before, |tree| tree.count("note-card") == CARDS); - }); - - // The tray's Quit, out of sight: nothing is left to ask, and the process ends. - close(&mut app); - app.ends_on("tray:quit"); -} - -#[test] -fn with_the_preference_off_the_close_button_ends_the_application() { - let profile = tempfile::tempdir().unwrap(); - std::fs::write(profile.path().join("preferences.json"), r#"{ "devnotes.closeToTray": "false" }"#) - .unwrap(); - let mut app = App::launch("43_close_to_tray", profile.path()); - app.wait_for("vault-confirmation"); - - app.ends_on("close"); -} - -#[cfg(target_os = "linux")] -#[test] -fn the_linux_tray_answers_a_watcher_started_after_it() { - let bus = linux::Bus::start(); - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch_on_bus("43_close_to_tray", profile.path(), &bus.address); - app.create_library(); - app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); - - let watcher = linux::Watcher::serve(&bus.address); - let menu = linux::Menu::of(&watcher); - step("a watcher started after the application gets its item and menu", || { - assert_eq!(menu.entries.len(), 6, "{:?}", menu.entries); - assert_eq!(menu.entries[4].1, "separator"); - }); - - step("hidden, the menu's Palette brings the window back with the palette", || { - let before = close(&mut app); - menu.click(menu.entries[3].0); - back(&mut app, before, with_the_palette); - close_the_palette(&mut app); - }); - - menu.click(menu.entries[5].0); - app.ended(); -} - -/// A session bus, a `StatusNotifierWatcher` and a host's calls, as a panel makes them. -#[cfg(target_os = "linux")] -mod linux { - use std::collections::HashMap; - use std::io::{BufRead, BufReader}; - use std::process::{Child, Command, Stdio}; - use std::sync::mpsc::{self, Receiver, Sender}; - use std::time::Duration; - - use zbus::blocking::{Connection, Proxy}; - use zbus::zvariant::{OwnedObjectPath, OwnedValue, Structure, Value}; - - /// An entry of a menu as dbusmenu sends it: id, properties, children. - type Entry = (i32, HashMap, Vec); - - /// The scenario's own: the machine's may have a panel on it, or no bus at all. - pub(super) struct Bus { - daemon: Child, - pub(super) address: String, - } - - impl Bus { - pub(super) fn start() -> Self { - let mut daemon = Command::new("dbus-daemon") - .args(["--session", "--nofork", "--print-address"]) - .stdout(Stdio::piped()) - .spawn() - .expect("dbus-daemon runs"); - let mut address = String::new(); - BufReader::new(daemon.stdout.take().expect("its address")) - .read_line(&mut address) - .expect("dbus-daemon says its address"); - Bus { daemon, address: address.trim().to_owned() } - } - } - - impl Drop for Bus { - fn drop(&mut self) { - let _ = self.daemon.kill(); - let _ = self.daemon.wait(); - } - } - - /// The one call an item makes of a watcher; a host's calls are made from here. - struct Registry { - told: Sender, - } - - #[zbus::interface(name = "org.kde.StatusNotifierWatcher")] - impl Registry { - /// By its bus name, or by its path from its own connection. - #[expect(clippy::needless_pass_by_value, reason = "zbus hands the header over by value")] - fn register_status_notifier_item( - &self, - service: &str, - #[zbus(header)] header: zbus::message::Header<'_>, - ) { - let name = if service.starts_with('/') { - header.sender().map(ToString::to_string).unwrap_or_default() - } else { - service.to_owned() - }; - let _ = self.told.send(name); - } - } - - pub(super) struct Watcher { - connection: Connection, - registered: Receiver, - } - - impl Watcher { - pub(super) fn serve(address: &str) -> Self { - let (told, registered) = mpsc::channel(); - let connection = zbus::blocking::connection::Builder::address(address) - .unwrap() - .name("org.kde.StatusNotifierWatcher") - .unwrap() - .serve_at("/StatusNotifierWatcher", Registry { told }) - .unwrap() - .build() - .unwrap(); - Watcher { connection, registered } - } - } - - /// The item's menu as a host reads it: each entry's id and type (`standard`, `separator`). - pub(super) struct Menu { - proxy: Proxy<'static>, - pub(super) entries: Vec<(i32, String)>, - } - - impl Menu { - /// Of the first item to register: a condition, waited for. - pub(super) fn of(watcher: &Watcher) -> Self { - let item = watcher - .registered - .recv_timeout(Duration::from_secs(30)) - .expect("an item registers with the watcher"); - let sni = Proxy::new( - &watcher.connection, - item.clone(), - "/StatusNotifierItem", - "org.kde.StatusNotifierItem", - ) - .unwrap(); - let path: OwnedObjectPath = sni.get_property("Menu").unwrap(); - let proxy = - Proxy::new(&watcher.connection, item, path.as_str().to_owned(), "com.canonical.dbusmenu") - .unwrap(); - let (_, (_, _, children)): (u32, Entry) = - proxy.call("GetLayout", &(0_i32, 1_i32, Vec::::new())).unwrap(); - let entries = children.iter().map(entry).collect(); - Menu { proxy, entries } - } - - pub(super) fn click(&self, id: i32) { - self.proxy - .call::<_, _, ()>("Event", &(id, "clicked", Value::from(0_i32), 0_u32)) - .unwrap(); - } - } - - fn entry(child: &OwnedValue) -> (i32, String) { - let child = Structure::try_from(child.try_clone().unwrap()).expect("an entry"); - let fields = child.fields(); - let id = i32::try_from(&fields[0]).expect("an entry's id"); - let properties = HashMap::::try_from(fields[1].try_clone().unwrap()).unwrap(); - let kind = properties - .get("type") - .and_then(|kind| kind.downcast_ref::().ok()) - .unwrap_or_else(|| "standard".to_owned()); - (id, kind) - } -} diff --git a/e2e/tests/44_window_controls.rs b/e2e/tests/44_window_controls.rs deleted file mode 100644 index 799160b6c..000000000 --- a/e2e/tests/44_window_controls.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! The window's own controls at the end of the title bar, the system's frame gone: maximise then -//! restore, remembered by the next launch; minimise; close, which ends the application with -//! « Close to tray » off (`43_close_to_tray` holds the close with it on). Maximised is the -//! system's answer — under Linux the window manager's — read from the control's name. macOS -//! keeps its own three buttons: nothing here runs there. -#![cfg(not(target_os = "macos"))] - -use std::path::Path; - -use e2e::{App, step}; - -fn maximized_on_disk(profile: &Path) -> bool { - platform::window::read(&profile.join("window.json")) - .expect("the geometry is kept") - .maximized -} - -fn name_of(app: &mut App, author_id: &str) -> String { - app.tree().text(author_id).unwrap_or_else(|| panic!("{author_id} is named")) -} - -#[test] -fn maximised_then_restored_and_the_next_launch_remembers() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("44_window_controls", profile.path()); - app.wait_for("window-maximize"); - let maximize = name_of(&mut app, "window-maximize"); - - step("maximised, the control names the restore", || { - app.click("window-maximize"); - app.eventually("the window is maximised", |tree| { - tree.text("window-maximize").is_some_and(|name| name != maximize) - }); - app.capture("maximised"); - }); - - let mut app = app.relaunch(); - step("the next launch opens maximised", || { - assert!(maximized_on_disk(profile.path())); - app.eventually("the window comes back maximised", |tree| { - tree.text("window-maximize").is_some_and(|name| name != maximize) - }); - }); - - step("restored, the control names the maximise again", || { - app.click("window-maximize"); - app.eventually("the window is restored", |tree| { - tree.text("window-maximize").as_deref() == Some(maximize.as_str()) - }); - }); - - app.quit(); - assert!(!maximized_on_disk(profile.path())); -} - -#[test] -fn minimised_it_goes_out_of_sight_and_a_launch_brings_it_back() { - let profile = tempfile::tempdir().unwrap(); - let mut app = App::launch("44_window_controls", profile.path()); - app.wait_for("window-minimize"); - let before: u32 = app - .tree() - .text("window-put-away") - .and_then(|count| count.parse().ok()) - .expect("the e2e flavour counts the window put away"); - - app.click("window-minimize"); - app.launch_again(); - - let once_more = (before + 1).to_string(); - app.eventually("the window went out of sight once, and is back", |tree| { - tree.has("window-shown") && tree.text("window-put-away").as_deref() == Some(&once_more) - }); - app.quit(); -} - -#[test] -fn with_the_preference_off_close_ends_the_application() { - let profile = tempfile::tempdir().unwrap(); - std::fs::write(profile.path().join("preferences.json"), r#"{ "devnotes.closeToTray": "false" }"#) - .unwrap(); - let mut app = App::launch("44_window_controls", profile.path()); - app.wait_for("window-close"); - - app.click("window-close"); - app.ended(); -}