Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 1 addition & 188 deletions apps/piquelctl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <URL>` 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 = <Cli as clap::CommandFactory>::command();
let globals: Vec<String> = 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::<Result<(), _>>())
.await
.expect_err("the platform cannot represent the deadline");

assert_eq!(error.to_string(), "timeout is too large");
}
}
mod tests;
161 changes: 1 addition & 160 deletions apps/piquelctl/src/profiles.rs → apps/piquelctl/src/profiles/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>(),
["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;
Loading
Loading