From 06db476d613299fed3f33dadb919e11031fff42f Mon Sep 17 00:00:00 2001 From: Lukas Kalbertodt Date: Fri, 18 Oct 2024 14:18:41 +0200 Subject: [PATCH] Add docs and tests about "empty var" behavior --- src/lib.rs | 3 +++ tests/env.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index bff0f51..abec6f3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 diff --git a/tests/env.rs b/tests/env.rs index 91a4ca9..9a5bced 100644 --- a/tests/env.rs +++ b/tests/env.rs @@ -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 } @@ -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 { + 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 = ::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()), + }); +}