Skip to content

Commit

Permalink
Add docs and tests about "empty var" behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
LukasKalbertodt committed Oct 18, 2024
1 parent 035fd45 commit 06db476
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,9 @@ pub use crate::{
/// Assigns an environment variable to this field. In [`Partial::from_env`], the
/// variable is checked and deserialized into the field if present.
///
/// If the env var is set to an empty string and if the field fails to
/// parse/deserialize from it, it is treated as unset.
///
/// ### `parse_env`
///
/// ```ignore
Expand Down
47 changes: 46 additions & 1 deletion tests/env.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use serde::Deserialize;
use confique::{Config};
use confique::{Config, Partial};
use pretty_assertions::assert_eq;

#[derive(Debug, Deserialize)]
enum Foo { A, B, C }
Expand All @@ -17,3 +18,47 @@ fn enum_env() {
let conf = Conf::builder().env().load();
assert!(matches!(conf, Ok(Conf { foo: Foo::B })));
}

fn my_parser(s: &str) -> Result<u32, impl std::error::Error> {
s.trim().parse()
}

#[test]
fn empty_error_is_unset() {
#[derive(Config)]
#[config(partial_attr(derive(PartialEq, Debug)))]
#[allow(dead_code)]
struct Conf {
#[config(env = "EMPTY_ERROR_IS_UNSET_FOO")]
foo: u32,

#[config(env = "EMPTY_ERROR_IS_UNSET_BAR", parse_env = my_parser)]
bar: u32,

#[config(env = "EMPTY_ERROR_IS_UNSET_BAZ")]
baz: String,
}

type Partial = <Conf as Config>::Partial;

std::env::set_var("EMPTY_ERROR_IS_UNSET_FOO", "");
assert_eq!(Partial::from_env().unwrap(), Partial {
foo: None,
bar: None,
baz: None,
});

std::env::set_var("EMPTY_ERROR_IS_UNSET_BAR", "");
assert_eq!(Partial::from_env().unwrap(), Partial {
foo: None,
bar: None,
baz: None,
});

std::env::set_var("EMPTY_ERROR_IS_UNSET_BAZ", "");
assert_eq!(Partial::from_env().unwrap(), Partial {
foo: None,
bar: None,
baz: Some("".into()),
});
}

0 comments on commit 06db476

Please sign in to comment.