Skip to content

Commit

Permalink
Unit tests for cli_v4::utils
Browse files Browse the repository at this point in the history
1. Added Unit tests for `AuthToken` APIs we are using
2. Added Unit tests for `BldrUrl` APIs we are using
3. Added Unit tests for `PkgDownloadOptions`

This covers unit tests for *new* logic we have written during the
porting activities.

Signed-off-by: Abhijit Gadgil <[email protected]>
  • Loading branch information
agadgil-progress committed Aug 14, 2024
1 parent a19507b commit 85003b9
Show file tree
Hide file tree
Showing 2 changed files with 260 additions and 16 deletions.
49 changes: 49 additions & 0 deletions components/hab/src/cli_v4/pkg/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,52 @@ impl PkgDownloadOptions {
Ok(sources)
}
}

#[cfg(test)]
mod tests {
use super::{PackageTarget,
Parser,
PkgDownloadOptions};
use std::{collections::HashMap,
path::Path};

#[test]
fn test_package_sets_from_file_e2e_tests_toml() {
let mut toml_files_map = HashMap::<String, bool>::new();
toml_files_map.insert("bad_header.toml".to_string(), false);
toml_files_map.insert("bad_ident.toml".to_string(), false);
toml_files_map.insert("bad_target.toml".to_string(), false);
toml_files_map.insert("no_header.toml".to_string(), false);
toml_files_map.insert("no_target.toml".to_string(), true);
toml_files_map.insert("happy_path.toml".to_string(), true);

let tomls_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let tomls_dir = Path::new(&tomls_dir).join("../../test/end-to-end/fixtures/pkg_download/");
assert!(tomls_dir.is_dir());

let no_header_toml_string = "no_header.toml".to_string();
let _ = toml_files_map.get(&no_header_toml_string);
for toml in tomls_dir.read_dir().unwrap() {
if let Ok(toml) = toml {
let key = toml.file_name().into_string().unwrap();
let path = toml.path().into_os_string().into_string();
eprintln!("{}: {:#?}", key, path);
if let Ok(path) = path {
let args = ["download", "--file", &path];
let result = PkgDownloadOptions::try_parse_from(args);
assert!(result.is_ok(), "{:#?}", result.err().unwrap());

let pkg_download = result.unwrap();
let result =
pkg_download.idents_from_file_matches(PackageTarget::active_target());
let should_be_ok = toml_files_map.get(&key).unwrap();
assert_eq!(result.is_ok(),
*should_be_ok,
"{}: {:#?}",
key,
result.err().unwrap());
}
}
}
}
}
227 changes: 211 additions & 16 deletions components/hab/src/cli_v4/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ use habitat_core::{crypto::CACHE_KEY_PATH_ENV_VAR,
env as hcore_env,
fs::CACHE_KEY_PATH,
url::{BLDR_URL_ENVVAR,
DEFAULT_BLDR_URL}};
DEFAULT_BLDR_URL},
AUTH_TOKEN_ENVVAR};

use crate::error::{Error as HabError,
Result as HabResult};
Expand Down Expand Up @@ -77,35 +78,229 @@ impl BldrUrl {
pub(crate) struct AuthToken {
// TODO: Add Validator for this?
/// Authentication token for Builder.
#[arg(name = "AUTH_TOKEN",
short = 'z',
long = "auth",
env = "HAB_AUTH_TOKEN")]
#[arg(name = "AUTH_TOKEN", short = 'z', long = "auth")]
auth_token: Option<String>,
}

impl AuthToken {
// This function returns a result. Use this when `auth_token` is required. Either as a command
// line option or env or from config.
pub(crate) fn from_cli_or_config(&self) -> HabResult<String> {
if self.auth_token.is_some() {
Ok(self.auth_token.clone().expect("TOKEN EXPECTED"))
if let Some(auth_token) = &self.auth_token {
Ok(auth_token.clone())
} else {
CliConfig::load()?.auth_token
.ok_or_else(|| HabError::ArgumentError("No auth token specified".into()))
match hcore_env::var(AUTH_TOKEN_ENVVAR) {
Ok(v) => Ok(v),
Err(_) => {
CliConfig::load()?.auth_token.ok_or_else(|| {
HabError::ArgumentError("No auth token \
specified"
.into())
})
}
}
}
}

// This function returns an `Option`, so if there is any "error" reading from config or env is
// not set simply returns a None.
pub(crate) fn try_from_cli_or_config(&self) -> Option<String> {
if self.auth_token.is_some() {
self.auth_token.clone()
} else {
match CliConfig::load() {
Ok(result) => result.auth_token,
Err(_) => None,
}
match self.from_cli_or_config() {
Ok(v) => Some(v),
Err(_) => None,
}
}
}

#[cfg(test)]
mod tests {
mod auth_token {

use crate::cli_v4::utils::AuthToken;

use clap_v4 as clap;

use clap::Parser;

habitat_core::locked_env_var!(HAB_AUTH_TOKEN, locked_auth_token);

#[derive(Debug, Clone, Parser)]
struct TestAuthToken {
#[command(flatten)]
a: AuthToken,
}

#[test]
fn required_env_no_cli_success() {
let env_var = locked_auth_token();
env_var.set("env-auth-token");

let args = ["test-auth-token"];
let result = TestAuthToken::try_parse_from(args);
assert!(result.is_ok(), "{:?}", result.err().unwrap());

let test_auth_token = result.unwrap();
let auth_token = test_auth_token.a.from_cli_or_config();
assert!(auth_token.is_ok(), "{:#?}", auth_token.err().unwrap());
}

#[test]
fn required_no_env_cli_success() {
let env_var = locked_auth_token();
env_var.unset();

let args = ["test-auth-token", "--auth", "foo-bar"];
let result = TestAuthToken::try_parse_from(args);
assert!(result.is_ok(), "{:?}", result.err().unwrap());
}

#[test]
fn required_no_env_no_cli_error() {
let env_var = locked_auth_token();
env_var.unset();

let args = ["test-auth-token"];
let result = TestAuthToken::try_parse_from(args);
assert!(result.is_ok(), "{:?}", result.err().unwrap());

let test_auth_token = result.unwrap();
let auth_token = test_auth_token.a.from_cli_or_config();
assert!(auth_token.is_err(), "{:#?}", auth_token.ok().unwrap());
}

#[test]
fn required_empty_env_no_cli_error() {
let env_var = locked_auth_token();
env_var.set("");

let args = ["test-auth-token"];
let result = TestAuthToken::try_parse_from(args);
assert!(result.is_ok(), "{:?}", result.err().unwrap());

let test_auth_token = result.unwrap();
let auth_token = test_auth_token.a.from_cli_or_config();
assert!(auth_token.is_err(), "{:#?}", auth_token.ok().unwrap());
}
#[test]
fn optional_empty_env_no_cli_none() {
let env_var = locked_auth_token();
env_var.set("");

let args = ["test-auth-token"];
let result = TestAuthToken::try_parse_from(args);
assert!(result.is_ok(), "{:?}", result.err().unwrap());

let test_auth_token = result.unwrap();
let auth_token = test_auth_token.a.try_from_cli_or_config();
assert!(auth_token.is_none(), "{:#?}", auth_token.unwrap());
}

#[test]
fn tok_optional_from_env_no_cli_some() {
let env_var = locked_auth_token();
env_var.set("env-auth-token");

let args = ["test-auth-token"];
let result = TestAuthToken::try_parse_from(args);
assert!(result.is_ok(), "{:?}", result.err().unwrap());

let test_auth_token = result.unwrap();
let auth_token = test_auth_token.a.try_from_cli_or_config();
assert_eq!(Some("env-auth-token".to_string()),
auth_token,
"{:#?}",
auth_token);
}

#[test]
fn optional_no_env_from_cli_some() {
let env_var = locked_auth_token();
env_var.set("env-auth-token");

let args = ["test-auth-token", "--auth", "foo-bar"];
let result = TestAuthToken::try_parse_from(args);
assert!(result.is_ok(), "{:?}", result.err().unwrap());

let test_auth_token = result.unwrap();
let auth_token = test_auth_token.a.try_from_cli_or_config();
assert_eq!(Some("foo-bar".to_string()), auth_token, "{:#?}", auth_token);
}
}

mod bldr_url {

use crate::cli_v4::utils::{BldrUrl,
DEFAULT_BLDR_URL};

use clap_v4 as clap;

use clap::Parser;

habitat_core::locked_env_var!(HAB_BLDR_URL, locked_bldr_url);

#[derive(Debug, Clone, Parser)]
struct TestBldrUrl {
#[command(flatten)]
u: BldrUrl,
}

#[test]
fn no_env_no_cli_default() {
let env_var = locked_bldr_url();
env_var.unset();

let args = ["test-bldr-url"];
let result = TestBldrUrl::try_parse_from(args);
assert!(result.is_ok(), "{:#?}", result.err().unwrap());

let test_bldr_url = result.unwrap();
let bldr_url = test_bldr_url.u.to_string();
assert_eq!(bldr_url.as_str(), DEFAULT_BLDR_URL, "{:#?}", bldr_url);
}

#[test]
fn empty_env_no_cli_default() {
let env_var = locked_bldr_url();
env_var.set("");

let args = ["test-bldr-url"];
let result = TestBldrUrl::try_parse_from(args);
assert!(result.is_ok(), "{:#?}", result.err().unwrap());

let test_bldr_url = result.unwrap();
let bldr_url = test_bldr_url.u.to_string();
assert_eq!(bldr_url.as_str(), DEFAULT_BLDR_URL, "{:#?}", bldr_url);
}

#[test]
fn env_cli_passed_value() {
let test_bldr_url_val = "https://test.bldr.habitat.sh/";
let cli_bldr_url_val = "https://cli.bldr.habitat.sh/";
let env_var = locked_bldr_url();
env_var.set(test_bldr_url_val);

let args = ["test-bldr-url", "--url", cli_bldr_url_val];
let result = TestBldrUrl::try_parse_from(args);
assert!(result.is_ok(), "{:#?}", result.err().unwrap());

let test_bldr_url = result.unwrap();
let bldr_url = test_bldr_url.u.to_string();
assert_eq!(bldr_url.as_str(), cli_bldr_url_val, "{:#?}", bldr_url);
}

#[test]
fn env_no_cli_env_value() {
let test_bldr_url_val = "https://test.bldr.habitat.sh/";
let env_var = locked_bldr_url();
env_var.set(test_bldr_url_val);

let args = ["test-bldr-url"];
let result = TestBldrUrl::try_parse_from(args);
assert!(result.is_ok(), "{:#?}", result.err().unwrap());

let test_bldr_url = result.unwrap();
let bldr_url = test_bldr_url.u.to_string();
assert_eq!(bldr_url.as_str(), test_bldr_url_val, "{:#?}", bldr_url);
}
}
}

0 comments on commit 85003b9

Please sign in to comment.