Skip to content

Commit

Permalink
feat: validate config
Browse files Browse the repository at this point in the history
  • Loading branch information
kasbuunk committed Dec 14, 2024
1 parent 1cddd36 commit 16e542a
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
66 changes: 66 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,69 @@ pub enum Repository {
pub enum Metrics {
Prometheus(metrics::Config),
}

pub fn validate(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
if config.clock_cycle_interval.is_zero() {
return Err("clock cycle interval cannot be zero".into());
}

Ok(())
}

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

fn config() -> Config {
Config {
automigrate: true,
log_level: log::Level::Info,
clock_cycle_interval: time::Duration::from_millis(100),
metrics: Metrics::Prometheus(metrics::Config {
port: 3000,
endpoint: String::from("/metrics"),
}),
repository: Repository::InMemory,
reset_state: true,
transmitter: Transmitter::Nats(nats::Config {
port: 3001,
host: String::from("127.0.0.1"),
}),
transport: Transport::Grpc(grpc::Config { port: 3002 }),
}
}

#[test]
fn test_validate_config() {
struct TestCase {
name: String,
config: Config,
expected_valid: bool,
}

let test_cases = vec![
TestCase {
name: String::from("valid"),
config: config(),
expected_valid: true,
},
TestCase {
name: String::from("zero duration"),
config: Config {
clock_cycle_interval: time::Duration::from_secs(0),
..config()
},
expected_valid: false,
},
];

for test_case in test_cases {
let valid = validate(&test_case.config).is_ok();
assert_eq!(
valid, test_case.expected_valid,
"test case failed: {}",
test_case.name
);
}
}
}
6 changes: 5 additions & 1 deletion src/load_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ pub fn load_config(file_path: &str) -> Result<config::Config, Box<dyn Error>> {

let secrets = load_secrets_from_env()?;

derive_config(config, secrets)
let config = derive_config(config, secrets)?;

config::validate(&config)?;

Ok(config)
}

fn derive_config(config: FileConfig, secrets: EnvConfig) -> Result<config::Config, Box<dyn Error>> {
Expand Down

0 comments on commit 16e542a

Please sign in to comment.