Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add config test and rewrite logging test #266

Merged
merged 7 commits into from
Aug 31, 2024
Merged
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
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ time = "0.3.36"
assert_cmd = "2.0.14"
criterion = { version = "0.5.1", features = ["html_reports"] }
rstest = "0.22.0"
temp-env = "0.3.6"

[[bench]]
name = "main"
Expand Down
21 changes: 21 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,24 @@ impl RunoConfig {
}
}
}

#[cfg(test)]
mod tests {
use rstest::*;

use crate::k8s::K8s;

use super::RunoConfig;

#[fixture]
fn valid_k8s() -> K8s {
return K8s { dry_run: false };
}

#[rstest]
#[case(10)]
fn build_valid_requeue_duration(valid_k8s: K8s, #[case] requeue_duration: u64) {
let config = RunoConfig::build(valid_k8s, requeue_duration);
assert_eq!(config.requeue_duration, requeue_duration)
}
}
9 changes: 9 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,12 @@ impl fmt::Display for CantCreateStringFromRegex {
write!(f, "Can't create random string from specified regex")
}
}

#[derive(Debug, Clone)]
pub struct LogLevelMissing;

impl fmt::Display for LogLevelMissing {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RUST_LOG is not set properly!")
}
}
58 changes: 38 additions & 20 deletions src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,48 @@
use tracing::error;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::{EnvFilter, Registry};
use tracing_subscriber::fmt::format::{DefaultFields, Format};
use tracing_subscriber::{EnvFilter, FmtSubscriber};

pub fn set_logger() -> bool {
let logger = tracing_subscriber::fmt::layer().json();
match EnvFilter::try_from_default_env().or_else(|_| EnvFilter::try_new("info")) {
Ok(env_filter) => {
let collector = Registry::default().with(logger).with(env_filter);
tracing::subscriber::set_global_default(collector).is_ok()
}
Err(e) => {
error!(
"Can't attach logger. No additional logs will be written!: {}",
e
);
false
use crate::errors::LogLevelMissing;

pub fn get_subscriber(
or_default: bool,
) -> Result<FmtSubscriber<DefaultFields, Format, EnvFilter>, LogLevelMissing> {
match EnvFilter::try_from_default_env() {
Ok(ef) => Ok(tracing_subscriber::fmt().with_env_filter(ef).finish()),
Err(_) => {
if or_default {
Ok(tracing_subscriber::fmt()
.with_env_filter(EnvFilter::new("INFO"))
.finish())
} else {
Err(LogLevelMissing)
}
}
}
}

#[cfg(test)]
mod tests {
use crate::logging::set_logger;
use crate::logging::get_subscriber;
use rstest::*;
use std::env;

#[rstest]
#[case("ERROR")]
#[case("WARN")]
#[case("INFO")]
#[case("DEBUG")]
#[case("TRACE")]
fn get_valid_subscriber(#[case] log_level: String) {
temp_env::with_var("RUST_LOG", Some(&log_level), || {
assert!(get_subscriber(false).is_ok());
env::remove_var("RUST_LOG");
});
}

#[test]
fn is_logger_set() {
assert!(set_logger());
#[rstest]
fn err_if_level_not_set() {
temp_env::with_var("RUST_LOG", None::<&str>, || {
assert!(get_subscriber(false).is_err());
});
}
}
14 changes: 10 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ use crate::k8s::K8s;
use anyhow::anyhow;
use clap::Parser;
use config::RunoConfig;
use errors::LogLevelMissing;
use tracing::info;
use tracing_subscriber::util::SubscriberInitExt;

#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
Expand All @@ -31,10 +33,14 @@ struct MainArgs {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = MainArgs::parse();
match logging::set_logger() {
true => info!("Logging initialized.."),
false => panic!("Logging not initialized properly!. Exiting..."),
}
let subscriber = match logging::get_subscriber(true) {
Ok(s) => {
info!("Logging initialized..");
s
}
Err(LogLevelMissing) => panic!("RUST_LOG is not set properly!"),
};
subscriber.init();
let k8s = K8s::build(args.dry_run);
let config = RunoConfig::build(k8s, args.requeue_duration);
match args.mode.as_str() {
Expand Down
Loading