From 13226cad70881e70f63189b87c664d46f13bd281 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 22:35:32 +0100 Subject: [PATCH] refactor(piquelctl): keep the tests out of the files they test --- apps/piquelctl/src/lib.rs | 189 +--------- .../src/{profiles.rs => profiles/mod.rs} | 161 +-------- apps/piquelctl/src/profiles/tests.rs | 156 ++++++++ .../src/{snapshot.rs => snapshot/mod.rs} | 337 +----------------- apps/piquelctl/src/snapshot/tests.rs | 334 +++++++++++++++++ apps/piquelctl/src/tests.rs | 183 ++++++++++ 6 files changed, 676 insertions(+), 684 deletions(-) rename apps/piquelctl/src/{profiles.rs => profiles/mod.rs} (71%) create mode 100644 apps/piquelctl/src/profiles/tests.rs rename apps/piquelctl/src/{snapshot.rs => snapshot/mod.rs} (66%) create mode 100644 apps/piquelctl/src/snapshot/tests.rs create mode 100644 apps/piquelctl/src/tests.rs diff --git a/apps/piquelctl/src/lib.rs b/apps/piquelctl/src/lib.rs index 15d2f3380..7fb94c17d 100644 --- a/apps/piquelctl/src/lib.rs +++ b/apps/piquelctl/src/lib.rs @@ -294,191 +294,4 @@ fn timeout_error(timeout: Duration) -> CliError { } #[cfg(test)] -mod tests { - use clap::Parser; - use std::time::Duration; - - use super::{ - cli::{Cli, parse_duration}, - support::looks_like_application_id, - }; - - /// The argument forms no command test in `tests/cli/` runs. - #[test] - fn parser_accepts_combined_exec_flags_and_build_filters() { - for arguments in [ - &["piquelctl", "builds", "list", "--environment", "app-01"][..], - &[ - "piquelctl", - "app", - "exec", - "piquel-fr", - "auth", - "-it", - "--", - "sh", - "-c", - "id", - ], - ] { - Cli::try_parse_from(arguments).expect("command parses"); - } - } - - #[test] - fn parser_takes_env_secret_targets_positionally_and_short_yes() { - for arguments in [ - &["piquelctl", "env", "secret", "list", "notes"][..], - &["piquelctl", "env", "secret", "list", "notes", "staging"], - &[ - "piquelctl", - "env", - "secret", - "regenerate", - "notes", - "staging", - "db", - "-y", - ], - &[ - "piquelctl", - "env", - "secret", - "delete", - "notes", - "staging", - "db", - "-y", - ], - &[ - "piquelctl", - "env", - "promote", - "notes", - "production", - "--force", - "-y", - ], - &["piquelctl", "app", "delete", "notes", "-y"], - ] { - Cli::try_parse_from(arguments).expect("command parses"); - } - for arguments in [ - // A generated secret is always named in one environment. - &["piquelctl", "env", "secret", "regenerate", "notes", "db"][..], - &[ - "piquelctl", - "env", - "promote", - "notes", - "production", - "--force", - "--expected-generation", - "3", - ], - ] { - assert!(Cli::try_parse_from(arguments).is_err(), "{arguments:?}"); - } - } - - #[test] - fn parser_rejects_conflicting_transports_and_invalid_timeout() { - assert!( - Cli::try_parse_from([ - "piquelctl", - "--socket", - "/tmp/piqueld.sock", - "--url", - "http://127.0.0.1:8080/", - "status", - ]) - .is_err() - ); - assert!(Cli::try_parse_from(["piquelctl", "--timeout", "zero", "status"]).is_err()); - assert!(Cli::try_parse_from(["piquelctl", "--timeout", "0s", "status"]).is_err()); - assert!(Cli::try_parse_from(["piquelctl", "app", "plan", "status"]).is_err()); - // Commands follow `--`, and services are validated logical names. - assert!(Cli::try_parse_from(["piquelctl", "app", "exec", "notes", "web"]).is_err()); - assert!( - Cli::try_parse_from(["piquelctl", "app", "exec", "notes", "Web", "--", "id"]).is_err() - ); - } - - #[test] - fn account_targets_do_not_select_the_credential() { - use super::{accounts::AccountCommand, cli::Command}; - for (command, extra) in [ - ("access", &["--permission", "apps:read"][..]), - ("enroll", &[]), - ] { - let mut arguments = vec!["piquelctl", "--account", "alice", "account", command, "bob"]; - arguments.extend(extra); - let cli = Cli::try_parse_from(arguments).expect("command parses"); - assert_eq!(cli.auth.account.as_deref(), Some("alice")); - let Command::Account { - command: AccountCommand::Access { target, .. } | AccountCommand::Enroll { target }, - } = cli.command - else { - panic!("account command"); - }; - assert_eq!(target, "bob"); - } - } - - // Clap stores arguments by id, so a subcommand argument sharing a global's - // id silently overwrites it (`app repository connect ` once replaced `--url`). - #[test] - fn subcommand_arguments_never_reuse_global_ids() { - fn check(command: &clap::Command, globals: &[String], path: &str) { - for subcommand in command.get_subcommands() { - let path = format!("{path} {}", subcommand.get_name()); - for argument in subcommand.get_arguments() { - let id = argument.get_id().as_str(); - assert!( - !globals.iter().any(|global| global == id), - "`{path}` argument `{id}` shadows a global argument", - ); - } - check(subcommand, globals, &path); - } - } - let command = ::command(); - let globals: Vec = command - .get_arguments() - .filter(|argument| argument.is_global_set()) - .map(|argument| argument.get_id().to_string()) - .collect(); - assert!(globals.iter().any(|global| global == "url")); - check(&command, &globals, "piquelctl"); - } - - #[test] - fn timeout_parser_accepts_bounded_units() { - assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500)); - assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30)); - assert_eq!(parse_duration("2m").unwrap(), Duration::from_mins(2)); - assert_eq!(parse_duration("1").unwrap(), Duration::from_secs(1)); - assert_eq!(parse_duration("7d").unwrap(), Duration::from_hours(7 * 24)); - } - - #[test] - fn application_ids_are_distinguished_from_names() { - assert!(looks_like_application_id("app-notes-01")); - assert!(!looks_like_application_id("notes")); - assert!(!looks_like_application_id("APP-NOTES")); - assert!(!looks_like_application_id("--------")); - } - - #[tokio::test] - async fn oversized_timeout_is_an_input_error_instead_of_a_panic() { - let cli = - Cli::try_parse_from(["piquelctl", "--timeout", "18446744073709551615s", "status"]) - .expect("the duration parser accepts a syntactically valid value"); - - let error = super::run_with_timeout(&cli, std::future::pending::>()) - .await - .expect_err("the platform cannot represent the deadline"); - - assert_eq!(error.to_string(), "timeout is too large"); - } -} +mod tests; diff --git a/apps/piquelctl/src/profiles.rs b/apps/piquelctl/src/profiles/mod.rs similarity index 71% rename from apps/piquelctl/src/profiles.rs rename to apps/piquelctl/src/profiles/mod.rs index ab3b7b27b..53f18fd60 100644 --- a/apps/piquelctl/src/profiles.rs +++ b/apps/piquelctl/src/profiles/mod.rs @@ -322,163 +322,4 @@ impl Profile { } #[cfg(test)] -mod tests { - use super::Profiles; - use std::path::PathBuf; - - struct Files { - directory: tempfile::TempDir, - } - - impl Files { - fn new() -> Self { - Self { - directory: tempfile::tempdir().unwrap(), - } - } - - fn write(&self, name: &str, text: &str) -> PathBuf { - let path = self.directory.path().join(name); - std::fs::write(&path, text).unwrap(); - path - } - } - - #[test] - fn user_profiles_replace_whole_system_entries_before_validation() { - let files = Files::new(); - let system = files.write( - "system.toml", - r#" -[profiles.prod] -url = "http://127.0.0.1:7845" -timeout = "2m" -[profiles.dev] -socket = "/tmp/system.sock" -url = "invalid" -timeout = "invalid" -[profiles.system] -socket = "/tmp/system-only.sock" -"#, - ); - let user = files.write( - "user.toml", - r#" -[profiles.prod] -socket = "/tmp/user.sock" -[profiles.dev] -url = "http://localhost:7846" -[profiles.user] -socket = "/tmp/user-only.sock" -"#, - ); - let profiles = - Profiles::load_files([(system.clone(), false), (user.clone(), false)]).unwrap(); - assert_eq!( - profiles - .profiles - .keys() - .map(String::as_str) - .collect::>(), - ["dev", "prod", "system", "user"] - ); - let prod = &profiles.profiles["prod"]; - assert_eq!(prod.endpoint(), "/tmp/user.sock"); - assert!(prod.url.is_none()); - assert!(prod.timeout.is_none()); - assert_eq!(prod.source, user); - assert_eq!(profiles.profiles["system"].source, system); - } - - #[test] - fn later_files_replace_the_default_which_must_name_a_merged_profile() { - let files = Files::new(); - // The system default names a profile defined only in the user file. - let system = files.write( - "system.toml", - "default = 'dev'\n[profiles.prod]\nurl = 'http://127.0.0.1:7845'", - ); - let user = files.write("user.toml", "[profiles.dev]\nsocket = '/tmp/dev.sock'"); - let profiles = - Profiles::load_files([(system.clone(), false), (user.clone(), false)]).unwrap(); - assert_eq!(profiles.default_name(), "dev"); - let later = files.write("later.toml", "default = 'prod'"); - let profiles = - Profiles::load_files([(system.clone(), false), (user, false), (later, false)]).unwrap(); - assert_eq!(profiles.default_name(), "prod"); - let error = Profiles::load_files([(system.clone(), false)]) - .err() - .unwrap() - .to_string(); - assert!( - error.contains(&format!( - "Unknown default connection profile dev in {}", - system.display() - )), - "{error}" - ); - } - - #[test] - fn missing_optional_files_are_ignored_but_required_files_fail_with_path() { - let files = Files::new(); - let missing = files.directory.path().join("missing.toml"); - let valid = files.write("valid.toml", "[profiles.dev]\nsocket = '/tmp/dev.sock'"); - let profiles = Profiles::load_files([(missing.clone(), false), (valid, false)]).unwrap(); - assert!(profiles.profiles.contains_key("dev")); - assert!( - Profiles::load_files([(missing.clone(), false)]) - .unwrap() - .profiles - .is_empty() - ); - let error = Profiles::load_files([(missing.clone(), true)]) - .err() - .unwrap() - .to_string(); - assert!(error.contains(missing.to_str().unwrap())); - } - - #[test] - fn malformed_and_unreadable_optional_files_fail_with_path() { - let files = Files::new(); - let malformed = files.write("malformed.toml", "[profiles."); - // Reading a directory fails even when tests run as root. - for path in [malformed, files.directory.path().to_owned()] { - let error = Profiles::load_files([(path.clone(), false)]) - .err() - .unwrap() - .to_string(); - assert!(error.contains(path.to_str().unwrap()), "{error}"); - } - } - - #[test] - fn invalid_effective_profiles_report_name_and_source() { - let files = Files::new(); - for (settings, expected) in [ - ( - "socket = '/tmp/dev.sock'\nurl = 'http://localhost'", - "exactly one socket or URL", - ), - ("timeout = '2s'", "exactly one socket or URL"), - ("url = 'invalid'", "not a valid URL"), - ( - "socket = '/tmp/dev.sock'\ntimeout = 'bad'", - "invalid timeout", - ), - ] { - let path = files.write("invalid.toml", &format!("[profiles.broken]\n{settings}")); - let error = Profiles::load_files([(path.clone(), false)]) - .err() - .unwrap() - .to_string(); - assert!( - error.contains("broken") - && error.contains(path.to_str().unwrap()) - && error.contains(expected), - "{error}" - ); - } - } -} +mod tests; diff --git a/apps/piquelctl/src/profiles/tests.rs b/apps/piquelctl/src/profiles/tests.rs new file mode 100644 index 000000000..d251636c7 --- /dev/null +++ b/apps/piquelctl/src/profiles/tests.rs @@ -0,0 +1,156 @@ +use super::Profiles; +use std::path::PathBuf; + +struct Files { + directory: tempfile::TempDir, +} + +impl Files { + fn new() -> Self { + Self { + directory: tempfile::tempdir().unwrap(), + } + } + + fn write(&self, name: &str, text: &str) -> PathBuf { + let path = self.directory.path().join(name); + std::fs::write(&path, text).unwrap(); + path + } +} + +#[test] +fn user_profiles_replace_whole_system_entries_before_validation() { + let files = Files::new(); + let system = files.write( + "system.toml", + r#" +[profiles.prod] +url = "http://127.0.0.1:7845" +timeout = "2m" +[profiles.dev] +socket = "/tmp/system.sock" +url = "invalid" +timeout = "invalid" +[profiles.system] +socket = "/tmp/system-only.sock" +"#, + ); + let user = files.write( + "user.toml", + r#" +[profiles.prod] +socket = "/tmp/user.sock" +[profiles.dev] +url = "http://localhost:7846" +[profiles.user] +socket = "/tmp/user-only.sock" +"#, + ); + let profiles = Profiles::load_files([(system.clone(), false), (user.clone(), false)]).unwrap(); + assert_eq!( + profiles + .profiles + .keys() + .map(String::as_str) + .collect::>(), + ["dev", "prod", "system", "user"] + ); + let prod = &profiles.profiles["prod"]; + assert_eq!(prod.endpoint(), "/tmp/user.sock"); + assert!(prod.url.is_none()); + assert!(prod.timeout.is_none()); + assert_eq!(prod.source, user); + assert_eq!(profiles.profiles["system"].source, system); +} + +#[test] +fn later_files_replace_the_default_which_must_name_a_merged_profile() { + let files = Files::new(); + // The system default names a profile defined only in the user file. + let system = files.write( + "system.toml", + "default = 'dev'\n[profiles.prod]\nurl = 'http://127.0.0.1:7845'", + ); + let user = files.write("user.toml", "[profiles.dev]\nsocket = '/tmp/dev.sock'"); + let profiles = Profiles::load_files([(system.clone(), false), (user.clone(), false)]).unwrap(); + assert_eq!(profiles.default_name(), "dev"); + let later = files.write("later.toml", "default = 'prod'"); + let profiles = + Profiles::load_files([(system.clone(), false), (user, false), (later, false)]).unwrap(); + assert_eq!(profiles.default_name(), "prod"); + let error = Profiles::load_files([(system.clone(), false)]) + .err() + .unwrap() + .to_string(); + assert!( + error.contains(&format!( + "Unknown default connection profile dev in {}", + system.display() + )), + "{error}" + ); +} + +#[test] +fn missing_optional_files_are_ignored_but_required_files_fail_with_path() { + let files = Files::new(); + let missing = files.directory.path().join("missing.toml"); + let valid = files.write("valid.toml", "[profiles.dev]\nsocket = '/tmp/dev.sock'"); + let profiles = Profiles::load_files([(missing.clone(), false), (valid, false)]).unwrap(); + assert!(profiles.profiles.contains_key("dev")); + assert!( + Profiles::load_files([(missing.clone(), false)]) + .unwrap() + .profiles + .is_empty() + ); + let error = Profiles::load_files([(missing.clone(), true)]) + .err() + .unwrap() + .to_string(); + assert!(error.contains(missing.to_str().unwrap())); +} + +#[test] +fn malformed_and_unreadable_optional_files_fail_with_path() { + let files = Files::new(); + let malformed = files.write("malformed.toml", "[profiles."); + // Reading a directory fails even when tests run as root. + for path in [malformed, files.directory.path().to_owned()] { + let error = Profiles::load_files([(path.clone(), false)]) + .err() + .unwrap() + .to_string(); + assert!(error.contains(path.to_str().unwrap()), "{error}"); + } +} + +#[test] +fn invalid_effective_profiles_report_name_and_source() { + let files = Files::new(); + for (settings, expected) in [ + ( + "socket = '/tmp/dev.sock'\nurl = 'http://localhost'", + "exactly one socket or URL", + ), + ("timeout = '2s'", "exactly one socket or URL"), + ("url = 'invalid'", "not a valid URL"), + ( + "socket = '/tmp/dev.sock'\ntimeout = 'bad'", + "invalid timeout", + ), + ] { + let path = files.write("invalid.toml", &format!("[profiles.broken]\n{settings}")); + let error = Profiles::load_files([(path.clone(), false)]) + .err() + .unwrap() + .to_string(); + assert!( + error.contains("broken") + && error.contains(path.to_str().unwrap()) + && error.contains(expected), + "{error}" + ); + } +} diff --git a/apps/piquelctl/src/snapshot.rs b/apps/piquelctl/src/snapshot/mod.rs similarity index 66% rename from apps/piquelctl/src/snapshot.rs rename to apps/piquelctl/src/snapshot/mod.rs index c381a774d..88fb133f0 100644 --- a/apps/piquelctl/src/snapshot.rs +++ b/apps/piquelctl/src/snapshot/mod.rs @@ -770,339 +770,4 @@ impl Git { } #[cfg(test)] -mod tests { - use super::*; - - /// Runs `script` in `directory` with a fixed Git identity, returning its - /// trimmed output. - fn sh(directory: &Path, script: &str) -> String { - let output = std::process::Command::new("sh") - .args(["-ec", script]) - .current_dir(directory) - .env("GIT_AUTHOR_NAME", "Test") - .env("GIT_AUTHOR_EMAIL", "test@example.com") - .env("GIT_COMMITTER_NAME", "Test") - .env("GIT_COMMITTER_EMAIL", "test@example.com") - .output() - .unwrap(); - assert!(output.status.success(), "{output:?}"); - String::from_utf8(output.stdout).unwrap().trim().to_owned() - } - - /// Every file of the worktree and its Git directory, with its hash: a - /// snapshot must leave refs, `HEAD`, the index, the stash, objects, - /// configuration, and the working tree as they were, and run no hook. - /// No Git command runs, since one could refresh the index itself. - fn state(work: &Path) -> String { - sh( - work, - "find . -type f -print0 | sort -z | xargs -0 sha256sum", - ) - } - - /// A clone of a two-commit repository, with an unpushed commit, a - /// modified file marked assume-unchanged, a staged, an untracked, an - /// ignored file, and a tracked one ignored since and edited. It splits - /// its index and has a hook that runs whenever the index changes. - fn fixture(root: &Path) -> PathBuf { - sh( - root, - "git init -q -b main remote - cd remote && echo one > app.toml && git add . && git commit -qm one - echo two > app.toml && git commit -qam two && cd .. - git clone -q remote work && cd work && git switch -qc feat/x - git config core.splitIndex true - printf '#!/bin/sh\ntouch hook-ran\n' > .git/hooks/post-index-change - chmod +x .git/hooks/post-index-change - printf 'ignored\n.env\n' > .gitignore && echo template > .env - git add . && git add -f .env && git commit -qm unpushed && echo secret > .env - echo changed > app.toml && git update-index --assume-unchanged app.toml - echo staged > staged.txt && git add staged.txt - echo untracked > untracked.txt && echo secret > ignored && rm hook-ran", - ); - root.join("work") - } - - /// The same worktree snapshots to the same commit, so a rerun can replay. - #[tokio::test] - async fn snapshots_of_an_unchanged_worktree_are_the_same_commit() { - let root = tempfile::tempdir().unwrap(); - let work = fixture(root.path()); - let worktree = Worktree::at(&work).await.unwrap(); - let first = worktree.snapshot("feat/x", None).await.unwrap().commit; - // Commit dates have one-second resolution. - tokio::time::sleep(std::time::Duration::from_millis(1100)).await; - let second = worktree.snapshot("feat/x", None).await.unwrap().commit; - assert_eq!(first, second); - } - - #[tokio::test] - async fn files_not_in_head_that_likely_hold_credentials_are_found() { - let root = tempfile::tempdir().unwrap(); - let work = fixture(root.path()); - // The fixture's `.env` is in `HEAD`, and `ignored` is ignored. - let worktree = Worktree::at(&work).await.unwrap(); - assert_eq!(worktree.secret_files().await.unwrap(), Vec::::new()); - // Staged but not committed counts, like untracked; source files, - // templates and other names don't. - sh( - &work, - "mkdir -p deploy && echo x > .env.local && git add .env.local \ - && echo key > deploy/server.PEM && echo key > id_ecdsa \ - && echo token > .git-credentials \ - && echo '{}' > application_default_credentials.json \ - && echo y > keys.txt && echo y > credentials.go && echo y > .env.example", - ); - assert_eq!( - worktree.secret_files().await.unwrap(), - [ - ".env.local", - ".git-credentials", - "application_default_credentials.json", - "deploy/server.PEM", - "id_ecdsa", - ] - ); - } - - #[tokio::test] - async fn snapshots_include_untracked_files_and_leave_the_repository_untouched() { - let root = tempfile::tempdir().unwrap(); - let work = fixture(root.path()); - let before = state(&work); - let worktree = Worktree::at(&work).await.unwrap(); - assert_eq!(worktree.branch().await.unwrap().as_deref(), Some("feat/x")); - let snapshot = worktree.snapshot("feat/x", None).await.unwrap(); - let thin = snapshot.bundle(History::Thin).await.unwrap(); - let complete = snapshot.bundle(History::Full).await.unwrap(); - assert_eq!(state(&work), before); - // Read from the snapshot's own repository: the worktree's lacks it. - let snapshot_git = format!( - "git --git-dir={}", - snapshot.directory.path().join("bundle.git").display() - ); - let files = sh( - &work, - &format!("{snapshot_git} ls-tree -r --name-only {}", snapshot.commit), - ); - assert_eq!( - files, - ".env\n.gitignore\napp.toml\nstaged.txt\nuntracked.txt" - ); - assert_eq!( - snapshot.uncommitted, - ["app.toml", "staged.txt", "untracked.txt"] - ); - // A tracked file ignored since is sent as committed. - let env = sh( - &work, - &format!("{snapshot_git} show {}:.env", snapshot.commit), - ); - assert_eq!(env, "template"); - // Edits hidden from `git status` by assume-unchanged are included. - let manifest = sh( - &work, - &format!("{snapshot_git} show {}:app.toml", snapshot.commit), - ); - assert_eq!(manifest, "changed"); - let parent = sh( - &work, - &format!("{snapshot_git} rev-parse {}^", snapshot.commit), - ); - assert_eq!(parent, sh(&work, "git rev-parse HEAD")); - - // Thin against the nearest commit the remote has, which is not HEAD. - let base = sh(&work, "git rev-parse origin/main"); - assert_eq!(thin.snapshot.base.as_deref(), Some(base.as_str())); - assert_eq!(complete.snapshot.base, None); - assert!(thin.length < complete.length); - // Either applies to a clone of the remote, and carries the snapshot. - for bundle in [&thin, &complete] { - let heads = sh( - &root.path().join("remote"), - &format!( - "git bundle verify -q {0} 2>/dev/null; git bundle list-heads {0}", - bundle.path.display() - ), - ); - assert_eq!(heads, format!("{} refs/heads/snapshot", snapshot.commit)); - } - // The objects of the snapshot were never written to the repository. - let written = sh( - &work, - &format!("git cat-file -e {} && echo yes || echo no", snapshot.commit), - ); - assert_eq!(written, "no"); - } - - /// Tracked files ignored since are sent as committed even when deleted - /// or staged as deleted, or named like pathspec magic, and their local - /// content does not count against the daemon's limits. - #[tokio::test] - async fn tracked_ignored_files_are_sent_as_committed() { - let root = tempfile::tempdir().unwrap(); - let work = fixture(root.path()); - sh( - &work, - "echo committed > ':(exclude)x' && git --literal-pathspecs add ':(exclude)x' - git commit -qm magic && printf ':(exclude)x\n' >> .gitignore - head -c 1048576 /dev/zero > ':(exclude)x' && git rm -q --cached .env && rm .env", - ); - let worktree = Worktree::at(&work).await.unwrap(); - let limits = SnapshotLimits { - max_upload_bytes: 1 << 20, - max_tree_bytes: 1 << 16, - max_files: 100, - }; - let snapshot = worktree.snapshot("feat/x", Some(&limits)).await.unwrap(); - snapshot.bundle(History::Thin).await.unwrap(); - // Its local content was never even staged. - let local = sh(&work, "git hash-object -- ':(exclude)x'"); - let object = snapshot.objects().join(&local[..2]).join(&local[2..]); - assert!(!object.exists()); - let snapshot_git = format!( - "git --git-dir={}", - snapshot.directory.path().join("bundle.git").display() - ); - for (path, committed) in [(".env", "template"), (":(exclude)x", "committed")] { - let content = sh( - &work, - &format!("{snapshot_git} show '{}:{path}'", snapshot.commit), - ); - assert_eq!(content, committed, "{path}"); - } - } - - /// Without remote-tracking branches, the whole history is bundled only - /// when asked for. - #[tokio::test] - async fn worktrees_without_remotes_need_the_whole_history_asked_for() { - let root = tempfile::tempdir().unwrap(); - sh( - root.path(), - "git init -q -b main work && cd work && echo a > a && git add . && git commit -qm a", - ); - let worktree = Worktree::at(&root.path().join("work")).await.unwrap(); - let snapshot = worktree.snapshot("main", None).await.unwrap(); - let Err(error) = snapshot.bundle(History::Thin).await else { - panic!("the whole history must be asked for"); - }; - assert!(error.to_string().contains("--full-history"), "{error}"); - let bundle = snapshot.bundle(History::Full).await.unwrap(); - assert_eq!(bundle.snapshot.base, None); - assert_eq!(bundle.commits, 1); - } - - /// Files over the daemon's limits are refused before anything is - /// written, naming the largest; so is a bundle over its upload limit. - #[tokio::test] - async fn snapshots_over_the_daemon_limits_are_refused_early() { - let root = tempfile::tempdir().unwrap(); - let work = fixture(root.path()); - sh(&work, "head -c 4096 /dev/zero > large.bin"); - let worktree = Worktree::at(&work).await.unwrap(); - let before = state(&work); - let limits = SnapshotLimits { - max_upload_bytes: 1 << 20, - max_tree_bytes: 4096, - max_files: 100, - }; - let Err(error) = worktree.snapshot("feat/x", Some(&limits)).await else { - panic!("files over the limit must be refused"); - }; - assert!(error.to_string().contains("large.bin (4.0 KiB)"), "{error}"); - assert_eq!(state(&work), before); - let few = SnapshotLimits { - max_files: 2, - max_tree_bytes: 1 << 20, - ..limits - }; - assert!(worktree.snapshot("feat/x", Some(&few)).await.is_err()); - - let roomy = SnapshotLimits { - max_tree_bytes: 1 << 20, - ..limits - }; - let snapshot = worktree.snapshot("feat/x", Some(&roomy)).await.unwrap(); - let bundle = snapshot.bundle(History::Thin).await.unwrap(); - assert!(bundle.check_size(Some(&roomy)).is_ok()); - let small = SnapshotLimits { - max_upload_bytes: bundle.length - 1, - ..roomy - }; - assert!(bundle.check_size(Some(&small)).is_err()); - } - - /// Detached heads have no branch, and submodules and nested - /// repositories are refused rather than half-supported. - #[tokio::test] - async fn detached_heads_have_no_branch_and_nested_repositories_are_refused() { - let root = tempfile::tempdir().unwrap(); - let work = fixture(root.path()); - sh( - &work, - "git switch -q --detach && git init -q nested && cd nested && echo n > n && git add . && git commit -qm n", - ); - let worktree = Worktree::at(&work).await.unwrap(); - assert_eq!(worktree.branch().await.unwrap(), None); - let Err(error) = worktree.snapshot("feat/x", None).await else { - panic!("nested repositories must be refused"); - }; - assert!(error.to_string().contains("nested"), "{error}"); - assert!(Worktree::at(root.path()).await.is_err()); - } - - /// Files a configured filter driver would stage, such as LFS's, partial - /// clones, and SHA-256 repositories are refused before anything is - /// written; a filter attribute without a configured driver is harmless. - #[tokio::test] - async fn filtered_files_partial_clones_and_sha256_repositories_are_refused() { - let root = tempfile::tempdir().unwrap(); - let work = fixture(root.path()); - sh( - &work, - "echo '*.bin filter=cache' > .gitattributes && echo data > big.bin", - ); - let worktree = Worktree::at(&work).await.unwrap(); - assert!(worktree.snapshot("feat/x", None).await.is_ok()); - sh( - &work, - "git config filter.cache.clean 'mkdir -p .git/filter-cache && cat'", - ); - let before = state(&work); - let Err(error) = worktree.snapshot("feat/x", None).await else { - panic!("filtered files must be refused"); - }; - assert!(error.to_string().contains("big.bin"), "{error}"); - assert_eq!(state(&work), before); - // A path starting with a space, listed first, is checked as is. - sh( - &work, - "rm big.bin && echo '\" a.bin\" filter=cache' > .gitattributes && echo data > ' a.bin'", - ); - let Err(error) = worktree.snapshot("feat/x", None).await else { - panic!("filtered files must be refused"); - }; - assert!(error.to_string().contains(" a.bin"), "{error}"); - - sh( - root.path(), - "git -C remote config uploadpack.allowFilter true && git clone -q --filter=blob:none \"file://$PWD/remote\" partial", - ); - let worktree = Worktree::at(&root.path().join("partial")).await.unwrap(); - let Err(error) = worktree.snapshot("main", None).await else { - panic!("partial clones must be refused"); - }; - assert!(error.to_string().contains("partial clone"), "{error}"); - - sh( - root.path(), - "git init -q --object-format=sha256 -b main sha256 && cd sha256 && echo a > a && git add . && git commit -qm a", - ); - let worktree = Worktree::at(&root.path().join("sha256")).await.unwrap(); - let Err(error) = worktree.snapshot("main", None).await else { - panic!("SHA-256 repositories must be refused"); - }; - assert!(error.to_string().contains("sha256"), "{error}"); - } -} +mod tests; diff --git a/apps/piquelctl/src/snapshot/tests.rs b/apps/piquelctl/src/snapshot/tests.rs new file mode 100644 index 000000000..264e212e0 --- /dev/null +++ b/apps/piquelctl/src/snapshot/tests.rs @@ -0,0 +1,334 @@ +use super::*; + +/// Runs `script` in `directory` with a fixed Git identity, returning its +/// trimmed output. +fn sh(directory: &Path, script: &str) -> String { + let output = std::process::Command::new("sh") + .args(["-ec", script]) + .current_dir(directory) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + String::from_utf8(output.stdout).unwrap().trim().to_owned() +} + +/// Every file of the worktree and its Git directory, with its hash: a +/// snapshot must leave refs, `HEAD`, the index, the stash, objects, +/// configuration, and the working tree as they were, and run no hook. +/// No Git command runs, since one could refresh the index itself. +fn state(work: &Path) -> String { + sh( + work, + "find . -type f -print0 | sort -z | xargs -0 sha256sum", + ) +} + +/// A clone of a two-commit repository, with an unpushed commit, a +/// modified file marked assume-unchanged, a staged, an untracked, an +/// ignored file, and a tracked one ignored since and edited. It splits +/// its index and has a hook that runs whenever the index changes. +fn fixture(root: &Path) -> PathBuf { + sh( + root, + "git init -q -b main remote + cd remote && echo one > app.toml && git add . && git commit -qm one + echo two > app.toml && git commit -qam two && cd .. + git clone -q remote work && cd work && git switch -qc feat/x + git config core.splitIndex true + printf '#!/bin/sh\ntouch hook-ran\n' > .git/hooks/post-index-change + chmod +x .git/hooks/post-index-change + printf 'ignored\n.env\n' > .gitignore && echo template > .env + git add . && git add -f .env && git commit -qm unpushed && echo secret > .env + echo changed > app.toml && git update-index --assume-unchanged app.toml + echo staged > staged.txt && git add staged.txt + echo untracked > untracked.txt && echo secret > ignored && rm hook-ran", + ); + root.join("work") +} + +/// The same worktree snapshots to the same commit, so a rerun can replay. +#[tokio::test] +async fn snapshots_of_an_unchanged_worktree_are_the_same_commit() { + let root = tempfile::tempdir().unwrap(); + let work = fixture(root.path()); + let worktree = Worktree::at(&work).await.unwrap(); + let first = worktree.snapshot("feat/x", None).await.unwrap().commit; + // Commit dates have one-second resolution. + tokio::time::sleep(std::time::Duration::from_millis(1100)).await; + let second = worktree.snapshot("feat/x", None).await.unwrap().commit; + assert_eq!(first, second); +} + +#[tokio::test] +async fn files_not_in_head_that_likely_hold_credentials_are_found() { + let root = tempfile::tempdir().unwrap(); + let work = fixture(root.path()); + // The fixture's `.env` is in `HEAD`, and `ignored` is ignored. + let worktree = Worktree::at(&work).await.unwrap(); + assert_eq!(worktree.secret_files().await.unwrap(), Vec::::new()); + // Staged but not committed counts, like untracked; source files, + // templates and other names don't. + sh( + &work, + "mkdir -p deploy && echo x > .env.local && git add .env.local \ + && echo key > deploy/server.PEM && echo key > id_ecdsa \ + && echo token > .git-credentials \ + && echo '{}' > application_default_credentials.json \ + && echo y > keys.txt && echo y > credentials.go && echo y > .env.example", + ); + assert_eq!( + worktree.secret_files().await.unwrap(), + [ + ".env.local", + ".git-credentials", + "application_default_credentials.json", + "deploy/server.PEM", + "id_ecdsa", + ] + ); +} + +#[tokio::test] +async fn snapshots_include_untracked_files_and_leave_the_repository_untouched() { + let root = tempfile::tempdir().unwrap(); + let work = fixture(root.path()); + let before = state(&work); + let worktree = Worktree::at(&work).await.unwrap(); + assert_eq!(worktree.branch().await.unwrap().as_deref(), Some("feat/x")); + let snapshot = worktree.snapshot("feat/x", None).await.unwrap(); + let thin = snapshot.bundle(History::Thin).await.unwrap(); + let complete = snapshot.bundle(History::Full).await.unwrap(); + assert_eq!(state(&work), before); + // Read from the snapshot's own repository: the worktree's lacks it. + let snapshot_git = format!( + "git --git-dir={}", + snapshot.directory.path().join("bundle.git").display() + ); + let files = sh( + &work, + &format!("{snapshot_git} ls-tree -r --name-only {}", snapshot.commit), + ); + assert_eq!( + files, + ".env\n.gitignore\napp.toml\nstaged.txt\nuntracked.txt" + ); + assert_eq!( + snapshot.uncommitted, + ["app.toml", "staged.txt", "untracked.txt"] + ); + // A tracked file ignored since is sent as committed. + let env = sh( + &work, + &format!("{snapshot_git} show {}:.env", snapshot.commit), + ); + assert_eq!(env, "template"); + // Edits hidden from `git status` by assume-unchanged are included. + let manifest = sh( + &work, + &format!("{snapshot_git} show {}:app.toml", snapshot.commit), + ); + assert_eq!(manifest, "changed"); + let parent = sh( + &work, + &format!("{snapshot_git} rev-parse {}^", snapshot.commit), + ); + assert_eq!(parent, sh(&work, "git rev-parse HEAD")); + + // Thin against the nearest commit the remote has, which is not HEAD. + let base = sh(&work, "git rev-parse origin/main"); + assert_eq!(thin.snapshot.base.as_deref(), Some(base.as_str())); + assert_eq!(complete.snapshot.base, None); + assert!(thin.length < complete.length); + // Either applies to a clone of the remote, and carries the snapshot. + for bundle in [&thin, &complete] { + let heads = sh( + &root.path().join("remote"), + &format!( + "git bundle verify -q {0} 2>/dev/null; git bundle list-heads {0}", + bundle.path.display() + ), + ); + assert_eq!(heads, format!("{} refs/heads/snapshot", snapshot.commit)); + } + // The objects of the snapshot were never written to the repository. + let written = sh( + &work, + &format!("git cat-file -e {} && echo yes || echo no", snapshot.commit), + ); + assert_eq!(written, "no"); +} + +/// Tracked files ignored since are sent as committed even when deleted +/// or staged as deleted, or named like pathspec magic, and their local +/// content does not count against the daemon's limits. +#[tokio::test] +async fn tracked_ignored_files_are_sent_as_committed() { + let root = tempfile::tempdir().unwrap(); + let work = fixture(root.path()); + sh( + &work, + "echo committed > ':(exclude)x' && git --literal-pathspecs add ':(exclude)x' + git commit -qm magic && printf ':(exclude)x\n' >> .gitignore + head -c 1048576 /dev/zero > ':(exclude)x' && git rm -q --cached .env && rm .env", + ); + let worktree = Worktree::at(&work).await.unwrap(); + let limits = SnapshotLimits { + max_upload_bytes: 1 << 20, + max_tree_bytes: 1 << 16, + max_files: 100, + }; + let snapshot = worktree.snapshot("feat/x", Some(&limits)).await.unwrap(); + snapshot.bundle(History::Thin).await.unwrap(); + // Its local content was never even staged. + let local = sh(&work, "git hash-object -- ':(exclude)x'"); + let object = snapshot.objects().join(&local[..2]).join(&local[2..]); + assert!(!object.exists()); + let snapshot_git = format!( + "git --git-dir={}", + snapshot.directory.path().join("bundle.git").display() + ); + for (path, committed) in [(".env", "template"), (":(exclude)x", "committed")] { + let content = sh( + &work, + &format!("{snapshot_git} show '{}:{path}'", snapshot.commit), + ); + assert_eq!(content, committed, "{path}"); + } +} + +/// Without remote-tracking branches, the whole history is bundled only +/// when asked for. +#[tokio::test] +async fn worktrees_without_remotes_need_the_whole_history_asked_for() { + let root = tempfile::tempdir().unwrap(); + sh( + root.path(), + "git init -q -b main work && cd work && echo a > a && git add . && git commit -qm a", + ); + let worktree = Worktree::at(&root.path().join("work")).await.unwrap(); + let snapshot = worktree.snapshot("main", None).await.unwrap(); + let Err(error) = snapshot.bundle(History::Thin).await else { + panic!("the whole history must be asked for"); + }; + assert!(error.to_string().contains("--full-history"), "{error}"); + let bundle = snapshot.bundle(History::Full).await.unwrap(); + assert_eq!(bundle.snapshot.base, None); + assert_eq!(bundle.commits, 1); +} + +/// Files over the daemon's limits are refused before anything is +/// written, naming the largest; so is a bundle over its upload limit. +#[tokio::test] +async fn snapshots_over_the_daemon_limits_are_refused_early() { + let root = tempfile::tempdir().unwrap(); + let work = fixture(root.path()); + sh(&work, "head -c 4096 /dev/zero > large.bin"); + let worktree = Worktree::at(&work).await.unwrap(); + let before = state(&work); + let limits = SnapshotLimits { + max_upload_bytes: 1 << 20, + max_tree_bytes: 4096, + max_files: 100, + }; + let Err(error) = worktree.snapshot("feat/x", Some(&limits)).await else { + panic!("files over the limit must be refused"); + }; + assert!(error.to_string().contains("large.bin (4.0 KiB)"), "{error}"); + assert_eq!(state(&work), before); + let few = SnapshotLimits { + max_files: 2, + max_tree_bytes: 1 << 20, + ..limits + }; + assert!(worktree.snapshot("feat/x", Some(&few)).await.is_err()); + + let roomy = SnapshotLimits { + max_tree_bytes: 1 << 20, + ..limits + }; + let snapshot = worktree.snapshot("feat/x", Some(&roomy)).await.unwrap(); + let bundle = snapshot.bundle(History::Thin).await.unwrap(); + assert!(bundle.check_size(Some(&roomy)).is_ok()); + let small = SnapshotLimits { + max_upload_bytes: bundle.length - 1, + ..roomy + }; + assert!(bundle.check_size(Some(&small)).is_err()); +} + +/// Detached heads have no branch, and submodules and nested +/// repositories are refused rather than half-supported. +#[tokio::test] +async fn detached_heads_have_no_branch_and_nested_repositories_are_refused() { + let root = tempfile::tempdir().unwrap(); + let work = fixture(root.path()); + sh( + &work, + "git switch -q --detach && git init -q nested && cd nested && echo n > n && git add . && git commit -qm n", + ); + let worktree = Worktree::at(&work).await.unwrap(); + assert_eq!(worktree.branch().await.unwrap(), None); + let Err(error) = worktree.snapshot("feat/x", None).await else { + panic!("nested repositories must be refused"); + }; + assert!(error.to_string().contains("nested"), "{error}"); + assert!(Worktree::at(root.path()).await.is_err()); +} + +/// Files a configured filter driver would stage, such as LFS's, partial +/// clones, and SHA-256 repositories are refused before anything is +/// written; a filter attribute without a configured driver is harmless. +#[tokio::test] +async fn filtered_files_partial_clones_and_sha256_repositories_are_refused() { + let root = tempfile::tempdir().unwrap(); + let work = fixture(root.path()); + sh( + &work, + "echo '*.bin filter=cache' > .gitattributes && echo data > big.bin", + ); + let worktree = Worktree::at(&work).await.unwrap(); + assert!(worktree.snapshot("feat/x", None).await.is_ok()); + sh( + &work, + "git config filter.cache.clean 'mkdir -p .git/filter-cache && cat'", + ); + let before = state(&work); + let Err(error) = worktree.snapshot("feat/x", None).await else { + panic!("filtered files must be refused"); + }; + assert!(error.to_string().contains("big.bin"), "{error}"); + assert_eq!(state(&work), before); + // A path starting with a space, listed first, is checked as is. + sh( + &work, + "rm big.bin && echo '\" a.bin\" filter=cache' > .gitattributes && echo data > ' a.bin'", + ); + let Err(error) = worktree.snapshot("feat/x", None).await else { + panic!("filtered files must be refused"); + }; + assert!(error.to_string().contains(" a.bin"), "{error}"); + + sh( + root.path(), + "git -C remote config uploadpack.allowFilter true && git clone -q --filter=blob:none \"file://$PWD/remote\" partial", + ); + let worktree = Worktree::at(&root.path().join("partial")).await.unwrap(); + let Err(error) = worktree.snapshot("main", None).await else { + panic!("partial clones must be refused"); + }; + assert!(error.to_string().contains("partial clone"), "{error}"); + + sh( + root.path(), + "git init -q --object-format=sha256 -b main sha256 && cd sha256 && echo a > a && git add . && git commit -qm a", + ); + let worktree = Worktree::at(&root.path().join("sha256")).await.unwrap(); + let Err(error) = worktree.snapshot("main", None).await else { + panic!("SHA-256 repositories must be refused"); + }; + assert!(error.to_string().contains("sha256"), "{error}"); +} diff --git a/apps/piquelctl/src/tests.rs b/apps/piquelctl/src/tests.rs new file mode 100644 index 000000000..3c691fe06 --- /dev/null +++ b/apps/piquelctl/src/tests.rs @@ -0,0 +1,183 @@ +use clap::Parser; +use std::time::Duration; + +use super::{ + cli::{Cli, parse_duration}, + support::looks_like_application_id, +}; + +/// The argument forms no command test in `tests/cli/` runs. +#[test] +fn parser_accepts_combined_exec_flags_and_build_filters() { + for arguments in [ + &["piquelctl", "builds", "list", "--environment", "app-01"][..], + &[ + "piquelctl", + "app", + "exec", + "piquel-fr", + "auth", + "-it", + "--", + "sh", + "-c", + "id", + ], + ] { + Cli::try_parse_from(arguments).expect("command parses"); + } +} + +#[test] +fn parser_takes_env_secret_targets_positionally_and_short_yes() { + for arguments in [ + &["piquelctl", "env", "secret", "list", "notes"][..], + &["piquelctl", "env", "secret", "list", "notes", "staging"], + &[ + "piquelctl", + "env", + "secret", + "regenerate", + "notes", + "staging", + "db", + "-y", + ], + &[ + "piquelctl", + "env", + "secret", + "delete", + "notes", + "staging", + "db", + "-y", + ], + &[ + "piquelctl", + "env", + "promote", + "notes", + "production", + "--force", + "-y", + ], + &["piquelctl", "app", "delete", "notes", "-y"], + ] { + Cli::try_parse_from(arguments).expect("command parses"); + } + for arguments in [ + // A generated secret is always named in one environment. + &["piquelctl", "env", "secret", "regenerate", "notes", "db"][..], + &[ + "piquelctl", + "env", + "promote", + "notes", + "production", + "--force", + "--expected-generation", + "3", + ], + ] { + assert!(Cli::try_parse_from(arguments).is_err(), "{arguments:?}"); + } +} + +#[test] +fn parser_rejects_conflicting_transports_and_invalid_timeout() { + assert!( + Cli::try_parse_from([ + "piquelctl", + "--socket", + "/tmp/piqueld.sock", + "--url", + "http://127.0.0.1:8080/", + "status", + ]) + .is_err() + ); + assert!(Cli::try_parse_from(["piquelctl", "--timeout", "zero", "status"]).is_err()); + assert!(Cli::try_parse_from(["piquelctl", "--timeout", "0s", "status"]).is_err()); + assert!(Cli::try_parse_from(["piquelctl", "app", "plan", "status"]).is_err()); + // Commands follow `--`, and services are validated logical names. + assert!(Cli::try_parse_from(["piquelctl", "app", "exec", "notes", "web"]).is_err()); + assert!(Cli::try_parse_from(["piquelctl", "app", "exec", "notes", "Web", "--", "id"]).is_err()); +} + +#[test] +fn account_targets_do_not_select_the_credential() { + use super::{accounts::AccountCommand, cli::Command}; + for (command, extra) in [ + ("access", &["--permission", "apps:read"][..]), + ("enroll", &[]), + ] { + let mut arguments = vec!["piquelctl", "--account", "alice", "account", command, "bob"]; + arguments.extend(extra); + let cli = Cli::try_parse_from(arguments).expect("command parses"); + assert_eq!(cli.auth.account.as_deref(), Some("alice")); + let Command::Account { + command: AccountCommand::Access { target, .. } | AccountCommand::Enroll { target }, + } = cli.command + else { + panic!("account command"); + }; + assert_eq!(target, "bob"); + } +} + +// Clap stores arguments by id, so a subcommand argument sharing a global's +// id silently overwrites it (`app repository connect ` once replaced `--url`). +#[test] +fn subcommand_arguments_never_reuse_global_ids() { + fn check(command: &clap::Command, globals: &[String], path: &str) { + for subcommand in command.get_subcommands() { + let path = format!("{path} {}", subcommand.get_name()); + for argument in subcommand.get_arguments() { + let id = argument.get_id().as_str(); + assert!( + !globals.iter().any(|global| global == id), + "`{path}` argument `{id}` shadows a global argument", + ); + } + check(subcommand, globals, &path); + } + } + let command = ::command(); + let globals: Vec = command + .get_arguments() + .filter(|argument| argument.is_global_set()) + .map(|argument| argument.get_id().to_string()) + .collect(); + assert!(globals.iter().any(|global| global == "url")); + check(&command, &globals, "piquelctl"); +} + +#[test] +fn timeout_parser_accepts_bounded_units() { + assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500)); + assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30)); + assert_eq!(parse_duration("2m").unwrap(), Duration::from_mins(2)); + assert_eq!(parse_duration("1").unwrap(), Duration::from_secs(1)); + assert_eq!(parse_duration("7d").unwrap(), Duration::from_hours(7 * 24)); +} + +#[test] +fn application_ids_are_distinguished_from_names() { + assert!(looks_like_application_id("app-notes-01")); + assert!(!looks_like_application_id("notes")); + assert!(!looks_like_application_id("APP-NOTES")); + assert!(!looks_like_application_id("--------")); +} + +#[tokio::test] +async fn oversized_timeout_is_an_input_error_instead_of_a_panic() { + let cli = Cli::try_parse_from(["piquelctl", "--timeout", "18446744073709551615s", "status"]) + .expect("the duration parser accepts a syntactically valid value"); + + let error = super::run_with_timeout(&cli, std::future::pending::>()) + .await + .expect_err("the platform cannot represent the deadline"); + + assert_eq!(error.to_string(), "timeout is too large"); +}