#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Environment {
Production,
Test,
}
impl Environment {
pub fn from_env() -> Self {
match std::env::var("NUWAX_CLI_ENV")
.unwrap_or_default()
.to_lowercase()
.as_str()
{
"testing" | "test" => Environment::Test,
"production" | "prod" | "" => Environment::Production,
_ => {
tracing::warn!("Unknown NUWAX_CLI_ENV value, defaulting to Production environment");
Environment::Production
}
}
}
pub fn is_testing(&self) -> bool {
matches!(self, Environment::Test)
}
pub fn is_production(&self) -> bool {
matches!(self, Environment::Production)
}
pub fn as_str(&self) -> &'static str {
match self {
Environment::Production => "production",
Environment::Test => "testing",
}
}
pub fn display_name(&self) -> &'static str {
match self {
Environment::Production => "Production",
Environment::Test => "Testing",
}
}
}
impl Default for Environment {
fn default() -> Self {
Environment::Production
}
}
impl std::fmt::Display for Environment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.display_name())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_env_production() {
unsafe {
std::env::remove_var("NUWAX_CLI_ENV");
}
assert_eq!(Environment::from_env(), Environment::Production);
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "production");
}
assert_eq!(Environment::from_env(), Environment::Production);
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "prod");
}
assert_eq!(Environment::from_env(), Environment::Production);
}
#[test]
fn test_from_env_testing() {
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "testing");
}
assert_eq!(Environment::from_env(), Environment::Test);
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "test");
}
assert_eq!(Environment::from_env(), Environment::Test);
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "TESTING");
}
assert_eq!(Environment::from_env(), Environment::Test);
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "Test");
}
assert_eq!(Environment::from_env(), Environment::Test);
}
#[test]
fn test_from_env_unknown() {
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "staging");
}
assert_eq!(Environment::from_env(), Environment::Production);
unsafe {
std::env::set_var("NUWAX_CLI_ENV", "development");
}
assert_eq!(Environment::from_env(), Environment::Production);
}
#[test]
fn test_environment_methods() {
let prod = Environment::Production;
let test = Environment::Test;
assert!(prod.is_production());
assert!(!prod.is_testing());
assert_eq!(prod.as_str(), "production");
assert_eq!(prod.display_name(), "Production");
assert!(test.is_testing());
assert!(!test.is_production());
assert_eq!(test.as_str(), "testing");
assert_eq!(test.display_name(), "Testing");
}
#[test]
fn test_default() {
assert_eq!(Environment::default(), Environment::Production);
}
#[test]
fn test_display() {
assert_eq!(format!("{}", Environment::Production), "Production");
assert_eq!(format!("{}", Environment::Test), "Testing");
}
}