diff options
author | Kesavan Yogeswaran <hikes@google.com> | 2022-06-28 00:18:48 -0400 |
---|---|---|
committer | Kesavan Yogeswaran <hikes@google.com> | 2022-06-28 23:34:17 -0400 |
commit | 7db2e8bfb46d9364ddc3419d3186b150141cc890 (patch) | |
tree | 3f9b94b879bbe6a73814d90402b77fed586038a0 /tests/env.rs | |
parent | 8b41015dbb231a2e5e0be37698d49924a10b290f (diff) |
Use TryInto for more permissive deserialization for integers
* Attempt to convert between integer types using `TryInto`-based
conversions rather than blanket failing for some source and
destination types.
* Use `into_uint` instead of `into_int` in `Value` Deserialize
implementations for unsigned integer types. Previously, we were
converting from signed types to unsigned types using `as`, which can
lead to surprise integer values conversions (#93).
Fixes #352 and #93
Diffstat (limited to 'tests/env.rs')
-rw-r--r-- | tests/env.rs | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/tests/env.rs b/tests/env.rs index ad252e4..2ee67de 100644 --- a/tests/env.rs +++ b/tests/env.rs @@ -131,6 +131,39 @@ fn test_parse_int() { } #[test] +fn test_parse_uint() { + // using a struct in an enum here to make serde use `deserialize_any` + #[derive(Deserialize, Debug)] + #[serde(tag = "tag")] + enum TestUintEnum { + Uint(TestUint), + } + + #[derive(Deserialize, Debug)] + struct TestUint { + int_val: u32, + } + + temp_env::with_var("INT_VAL", Some("42"), || { + let environment = Environment::default().try_parsing(true); + + let config = Config::builder() + .set_default("tag", "Uint") + .unwrap() + .add_source(environment) + .build() + .unwrap(); + + let config: TestUintEnum = config.try_deserialize().unwrap(); + + assert!(matches!( + config, + TestUintEnum::Uint(TestUint { int_val: 42 }) + )); + }) +} + +#[test] fn test_parse_float() { // using a struct in an enum here to make serde use `deserialize_any` #[derive(Deserialize, Debug)] @@ -535,3 +568,43 @@ fn test_parse_off_string() { } }) } + +#[test] +fn test_parse_int_default() { + #[derive(Deserialize, Debug)] + struct TestInt { + int_val: i32, + } + + let environment = Environment::default().try_parsing(true); + + let config = Config::builder() + .set_default("int_val", 42_i32) + .unwrap() + .add_source(environment) + .build() + .unwrap(); + + let config: TestInt = config.try_deserialize().unwrap(); + assert_eq!(config.int_val, 42); +} + +#[test] +fn test_parse_uint_default() { + #[derive(Deserialize, Debug)] + struct TestUint { + int_val: u32, + } + + let environment = Environment::default().try_parsing(true); + + let config = Config::builder() + .set_default("int_val", 42_u32) + .unwrap() + .add_source(environment) + .build() + .unwrap(); + + let config: TestUint = config.try_deserialize().unwrap(); + assert_eq!(config.int_val, 42); +} |