1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
pub mod cmdline;
52
pub mod derive;
53
mod err;
54
#[macro_use]
55
pub mod extend_builder;
56
pub mod file_watcher;
57
mod flatten;
58
pub mod list_builder;
59
mod listen;
60
pub mod load;
61
pub mod map_builder;
62
mod misc;
63
pub mod mistrust;
64
mod mut_cfg;
65
pub mod setter_traits;
66
pub mod sources;
67
#[cfg(feature = "testing")]
68
pub mod testing;
69

            
70
#[doc(hidden)]
71
pub mod deps {
72
    pub use educe;
73
    pub use figment;
74
    pub use itertools::Itertools;
75
    pub use paste::paste;
76
    pub use serde;
77
    pub use serde_value;
78
    pub use tor_basic_utils::{if_empty, macro_first_nonempty};
79
}
80

            
81
pub use cmdline::CmdLine;
82
pub use err::{ConfigBuildError, ConfigError, ConfigGetValueError, ReconfigureError};
83
pub use flatten::{Flatten, Flattenable};
84
pub use list_builder::{MultilineListBuilder, MultilineListBuilderError};
85
pub use listen::*;
86
pub use load::{resolve, resolve_ignore_warnings, resolve_return_results};
87
pub use misc::*;
88
pub use mut_cfg::MutCfg;
89
use serde::de::DeserializeOwned;
90
pub use sources::{ConfigurationSource, ConfigurationSources};
91
use tor_error::into_internal;
92

            
93
#[doc(hidden)]
94
pub use derive_deftly;
95
#[doc(hidden)]
96
pub use flatten::flattenable_extract_fields;
97

            
98
derive_deftly::template_export_semver_check! { "0.12.1" }
99

            
100
/// A set of configuration fields, represented as a set of nested K=V
101
/// mappings.
102
///
103
/// (This is a wrapper for an underlying type provided by the library that
104
/// actually does our configuration.)
105
#[derive(Clone, Debug, Default)]
106
#[must_use] // to prevent errors from merge_from.
107
pub struct ConfigurationTree(figment::Figment);
108

            
109
impl ConfigurationTree {
110
    #[cfg(test)]
111
14
    pub(crate) fn get_string(&self, key: &str) -> Result<String, crate::ConfigError> {
112
        use figment::value::Value as V;
113
14
        let val = self.0.find_value(key).map_err(ConfigError::from_cfg_err)?;
114
12
        Ok(match val {
115
8
            V::String(_, s) => s.clone(),
116
4
            V::Num(_, n) => n.to_i128().expect("Failed to extract i128").to_string(),
117
            _ => format!("{:?}", val),
118
        })
119
14
    }
120

            
121
    /// Return the value with a given key as some type that implements Deserialize.
122
    ///
123
    /// Return `None` if no such value is set in this tree.
124
8
    pub fn get_serde_value<T: DeserializeOwned>(
125
8
        &self,
126
8
        key: &str,
127
8
    ) -> Result<Option<T>, ConfigGetValueError> {
128
        use figment::error::{Error as FError, Kind::MissingField};
129
8
        match self.0.extract_inner(key) {
130
2
            Ok(v) => Ok(Some(v)),
131
            Err(FError {
132
                kind: MissingField(..),
133
                ..
134
6
            }) => Ok(None),
135
            Err(e) => Err(into_internal!("Unexpected error looking up config value")(e).into()),
136
        }
137
8
    }
138

            
139
    /// Override our current tree with the settings in `config`.
140
    ///
141
    /// `config` must be implement [`Serialize`](serde::Serialize),
142
    /// and must serialize to a map.
143
    ///
144
    /// This operation follows the same as are used when reading
145
    /// multiple configuration files in sequence,
146
    /// where option settings in later files replace earlier ones.
147
    #[allow(clippy::unnecessary_wraps)]
148
12
    pub fn merge_from<T>(&mut self, config: &T) -> Result<(), ConfigError>
149
12
    where
150
12
        T: serde::Serialize,
151
    {
152
12
        let provider = figment::providers::Serialized::from(config, figment::Profile::Default);
153
12
        let mut orig = figment::Figment::new();
154
12
        std::mem::swap(&mut orig, &mut self.0);
155
12
        self.0 = orig.merge(provider);
156
        // Figment::merge handles errors by making the type of the figment itself into an error...
157
        // but we don't want our API to rely on that, so we let method returna Result.
158
12
        Ok(())
159
12
    }
160
}
161

            
162
/// Rules for reconfiguring a running Arti instance.
163
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
164
#[non_exhaustive]
165
pub enum Reconfigure {
166
    /// Perform no reconfiguration unless we can guarantee that all changes will be successful.
167
    AllOrNothing,
168
    /// Try to reconfigure as much as possible; warn on fields that we cannot reconfigure.
169
    WarnOnFailures,
170
    /// Don't reconfigure anything: Only check whether we can guarantee that all changes will be successful.
171
    CheckAllOrNothing,
172
}
173

            
174
impl Reconfigure {
175
    /// Called when we see a disallowed attempt to change `field`: either give a ReconfigureError,
176
    /// or warn and return `Ok(())`, depending on the value of `self`.
177
4
    pub fn cannot_change<S: AsRef<str>>(self, field: S) -> Result<(), ReconfigureError> {
178
4
        match self {
179
            Reconfigure::AllOrNothing | Reconfigure::CheckAllOrNothing => {
180
2
                Err(ReconfigureError::CannotChange {
181
2
                    field: field.as_ref().to_owned(),
182
2
                })
183
            }
184
            Reconfigure::WarnOnFailures => {
185
2
                tracing::warn!("Cannot change {} on a running client.", field.as_ref());
186
2
                Ok(())
187
            }
188
        }
189
4
    }
190

            
191
    /// As `cannot_change`, but return a [`ReconfigureError::CannotChangeToValue`] variant.
192
    ///
193
    /// `manner` should be an adverbial preprositional phrase,
194
    /// like "from on to off" or "while arti is running".
195
    pub fn cannot_change_specific<S, T>(self, field: S, manner: T) -> Result<(), ReconfigureError>
196
    where
197
        S: AsRef<str>,
198
        T: AsRef<str>,
199
    {
200
        match self {
201
            Reconfigure::AllOrNothing | Reconfigure::CheckAllOrNothing => {
202
                Err(ReconfigureError::CannotChangeToValue {
203
                    field: field.as_ref().to_owned(),
204
                    manner: manner.as_ref().to_owned(),
205
                })
206
            }
207
            Reconfigure::WarnOnFailures => {
208
                tracing::warn!(
209
                    "Cannot change {} {} on a running client.",
210
                    field.as_ref(),
211
                    manner.as_ref()
212
                );
213
                Ok(())
214
            }
215
        }
216
    }
217
}
218

            
219
/// Resolves an `Option<Option<T>>` (in a builder) into an `Option<T>`
220
///
221
///  * If the input is `None`, this indicates that the user did not specify a value,
222
///    and we therefore use `def` to obtain the default value.
223
///
224
///  * If the input is `Some(None)`, or `Some(Some(Default::default()))`,
225
///    the user has explicitly specified that this config item should be null/none/nothing,
226
///    so we return `None`.
227
///
228
///  * Otherwise the user provided an actual value, and we return `Some` of it.
229
///
230
/// See <https://gitlab.torproject.org/tpo/core/arti/-/issues/488>
231
///
232
/// For consistency with other APIs in Arti, when using this,
233
/// do not pass `setter(strip_option)` to derive_builder.
234
///
235
/// # âš  Stability Warning âš 
236
///
237
/// We may significantly change this so that it is an method in an extension trait.
238
//
239
// This is an annoying AOI right now because you have to write things like
240
//     #[builder(field(build = r#"tor_config::resolve_option(&self.dns_port, || None)"#))]
241
//     pub(crate) dns_port: Option<u16>,
242
// which recapitulates the field name.  That is very much a bug hazard (indeed, in an
243
// early version of some of this code I perpetrated precisely that bug).
244
// Fixing this involves a derive_builder feature.
245
368
pub fn resolve_option<T, DF>(input: &Option<Option<T>>, def: DF) -> Option<T>
246
368
where
247
368
    T: Clone + Default + PartialEq,
248
368
    DF: FnOnce() -> Option<T>,
249
{
250
368
    resolve_option_general(
251
368
        input.as_ref().map(|ov| ov.as_ref()),
252
12
        |v| v == &T::default(),
253
368
        def,
254
    )
255
368
}
256

            
257
/// Resolves an `Option<Option<&T>>` (in a builder) into an `Option<T>`, more generally
258
///
259
/// Like [`resolve_option`], but:
260
///
261
///  * Doesn't rely on `T` being `Default + PartialEq`
262
///    to determine whether it's the sentinel value;
263
///    instead, takes `is_sentinel`.
264
///
265
///  * Takes `Option<Option<&T>>` which is more general, but less like the usual call sites.
266
///
267
/// # Behavior
268
///
269
///  * If the input is `None`, this indicates that the user did not specify a value,
270
///    and we therefore use `def` to obtain the default value.
271
///
272
///  * If the input is `Some(None)`, or `Some(Some(v))` where `is_sentinel(v)` returns true,
273
///    the user has explicitly specified that this config item should be null/none/nothing,
274
///    so we return `None`.
275
///
276
///  * Otherwise the user provided an actual value, and we return `Some` of it.
277
///
278
/// See <https://gitlab.torproject.org/tpo/core/arti/-/issues/488>
279
///
280
/// # âš  Stability Warning âš 
281
///
282
/// We may significantly change this so that it is an method in an extension trait.
283
///
284
/// # Example
285
/// ```
286
/// use tor_config::resolve_option_general;
287
///
288
/// // Use 0 as a sentinel meaning "explicitly clear" in this example
289
/// let is_sentinel = |v: &i32| *v == 0;
290
///
291
/// // No value provided: use default
292
/// assert_eq!(
293
///     resolve_option_general(None, is_sentinel, || Some(10)),
294
///     Some(10),
295
/// );
296
///
297
/// // Explicitly None
298
/// assert_eq!(
299
///     resolve_option_general(Some(None), is_sentinel, || Some(10)),
300
///     None,
301
/// );
302
///
303
/// // Sentinel value (0) -> return None
304
/// assert_eq!(
305
///     resolve_option_general(Some(Some(&0)), is_sentinel, || Some(10)),
306
///     None,
307
/// );
308
///
309
/// // Set to actual value -> return that value
310
/// assert_eq!(
311
///     resolve_option_general(Some(Some(&5)), is_sentinel, || Some(10)),
312
///     Some(5),
313
/// );
314
/// ```
315
368
pub fn resolve_option_general<T, ISF, DF>(
316
368
    input: Option<Option<&T>>,
317
368
    is_sentinel: ISF,
318
368
    def: DF,
319
368
) -> Option<T>
320
368
where
321
368
    T: Clone,
322
368
    DF: FnOnce() -> Option<T>,
323
368
    ISF: FnOnce(&T) -> bool,
324
{
325
12
    match input {
326
352
        None => def(),
327
4
        Some(None) => None,
328
12
        Some(Some(v)) if is_sentinel(v) => None,
329
4
        Some(Some(v)) => Some(v.clone()),
330
    }
331
368
}
332

            
333
/// Defines standard impls for a struct with a `Builder`, incl `Default`
334
///
335
/// **Use this.**  Do not `#[derive(Builder, Default)]`.  That latter approach would produce
336
/// wrong answers if builder attributes are used to specify non-`Default` default values.
337
///
338
/// # Input syntax
339
///
340
/// ```
341
/// use derive_builder::Builder;
342
/// use serde::{Deserialize, Serialize};
343
/// use tor_config::impl_standard_builder;
344
/// use tor_config::ConfigBuildError;
345
///
346
/// #[derive(Debug, Builder, Clone, Eq, PartialEq)]
347
/// #[builder(derive(Serialize, Deserialize, Debug))]
348
/// #[builder(build_fn(error = "ConfigBuildError"))]
349
/// struct SomeConfigStruct { }
350
/// impl_standard_builder! { SomeConfigStruct }
351
///
352
/// #[derive(Debug, Builder, Clone, Eq, PartialEq)]
353
/// struct UnusualStruct { }
354
/// impl_standard_builder! { UnusualStruct: !Deserialize + !Builder }
355
/// ```
356
///
357
/// # Requirements
358
///
359
/// `$Config`'s builder must have default values for all the fields,
360
/// or this macro-generated self-test will fail.
361
/// This should be OK for all principal elements of our configuration.
362
///
363
/// `$ConfigBuilder` must have an appropriate `Deserialize` impl.
364
///
365
/// # Options
366
///
367
///  * `!Default` suppresses the `Default` implementation, and the corresponding tests.
368
///    This should be done within Arti's configuration only for sub-structures which
369
///    contain mandatory fields (and are themselves optional).
370
///
371
///  * `!Deserialize` suppresses the test case involving `Builder: Deserialize`.
372
///    This should not be done for structs which are part of Arti's configuration,
373
///    but can be appropriate for other types that use [`derive_builder`].
374
///
375
///  * `!Builder` suppresses the impl of the [`tor_config::load::Builder`](load::Builder) trait
376
///    This will be necessary if the error from the builder is not [`ConfigBuildError`].
377
///
378
/// # Generates
379
///
380
///  * `impl Default for $Config`
381
///  * `impl Builder for $ConfigBuilder`
382
///  * a self-test that the `Default` impl actually works
383
///  * a test that the `Builder` can be deserialized from an empty [`ConfigurationTree`],
384
///    and then built, and that the result is the same as the ordinary default.
385
//
386
// The implementation munches fake "trait bounds" (`: !Deserialize + !Wombat ...`) off the RHS.
387
// We're going to add at least one more option.
388
//
389
// When run with `!Default`, this only generates a `builder` impl and an impl of
390
// the `Resolvable` trait which probably won't be used anywhere.  That may seem
391
// like a poor tradeoff (much fiddly macro code to generate a trivial function in
392
// a handful of call sites).  However, this means that `impl_standard_builder!`
393
// can be used in more places.  That sets a good example: always use the macro.
394
//
395
// That is a good example because we want `impl_standard_builder!` to be
396
// used elsewhere because it generates necessary tests of properties
397
// which might otherwise be violated.  When adding code, people add according to the
398
// patterns they see.
399
//
400
// (We, sadly, don't have a good way to *ensure* use of `impl_standard_builder`.)
401
#[macro_export]
402
macro_rules! impl_standard_builder {
403
    // Convert the input into the "being processed format":
404
    {
405
        $Config:ty $(: $($options:tt)* )?
406
    } => { $crate::impl_standard_builder!{
407
        // ^Being processed format:
408
        @ ( Builder                    )
409
          ( default                    )
410
          ( extract                    ) $Config    :                 $( $( $options    )* )?
411
        //  ~~~~~~~~~~~~~~~              ^^^^^^^    ^   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
412
        // present iff not !Builder, !Default
413
        // present iff not !Default
414
        // present iff not !Deserialize  type      always present    options yet to be parsed
415
    } };
416
    // If !Deserialize is the next option, implement it by making $try_deserialize absent
417
    {
418
        @ ( $($Builder        :ident)? )
419
          ( $($default        :ident)? )
420
          ( $($try_deserialize:ident)? ) $Config:ty : $(+)? !Deserialize $( $options:tt )*
421
    } => {  $crate::impl_standard_builder!{
422
        @ ( $($Builder              )? )
423
          ( $($default              )? )
424
          (                            ) $Config    :                    $( $options    )*
425
    } };
426
    // If !Builder is the next option, implement it by making $Builder absent
427
    {
428
        @ ( $($Builder        :ident)? )
429
          ( $($default        :ident)? )
430
          ( $($try_deserialize:ident)? ) $Config:ty : $(+)? !Builder     $( $options:tt )*
431
    } => {  $crate::impl_standard_builder!{
432
        @ (                            )
433
          ( $($default              )? )
434
          ( $($try_deserialize      )? ) $Config    :                    $( $options    )*
435
    } };
436
    // If !Default is the next option, implement it by making $default absent
437
    {
438
        @ ( $($Builder        :ident)? )
439
          ( $($default        :ident)? )
440
          ( $($try_deserialize:ident)? ) $Config:ty : $(+)? !Default     $( $options:tt )*
441
    } => {  $crate::impl_standard_builder!{
442
        @ ( $($Builder              )? )
443
          (                            )
444
          ( $($try_deserialize      )? ) $Config    :                    $( $options    )*
445
    } };
446
    // Having parsed all options, produce output:
447
    {
448
        @ ( $($Builder        :ident)? )
449
          ( $($default        :ident)? )
450
          ( $($try_deserialize:ident)? ) $Config:ty : $(+)?
451
    } => { $crate::deps::paste!{
452
        impl $Config {
453
            /// Returns a fresh, default, builder
454
69372
            pub fn builder() -> [< $Config Builder >] {
455
69372
                Default::default()
456
69372
            }
457
        }
458

            
459
        $( // expands iff there was $default, which is always default
460
            impl Default for $Config {
461
66
                fn $default() -> Self {
462
                    // unwrap is good because one of the test cases above checks that it works!
463
66
                    [< $Config Builder >]::default().build().unwrap()
464
66
                }
465
            }
466
        )?
467

            
468
        $( // expands iff there was $Builder, which is always Builder
469
            impl $crate::load::$Builder for [< $Config Builder >] {
470
                type Built = $Config;
471
                fn build(&self) -> std::result::Result<$Config, $crate::ConfigBuildError> {
472
                    [< $Config Builder >]::build(self)
473
                }
474
            }
475
        )?
476

            
477
        #[test]
478
        #[allow(non_snake_case)]
479
24
        fn [< test_impl_Default_for_ $Config >] () {
480
            #[allow(unused_variables)]
481
24
            let def = None::<$Config>;
482
            $( // expands iff there was $default, which is always default
483
2
                let def = Some($Config::$default());
484
            )?
485

            
486
24
            if let Some(def) = def {
487
2
                $( // expands iff there was $try_deserialize, which is always extract
488
2
                    let empty_config = $crate::deps::figment::Figment::new();
489
2
                    let builder: [< $Config Builder >] = empty_config.$try_deserialize().unwrap();
490
2
                    let from_empty = builder.build().unwrap();
491
2
                    assert_eq!(def, from_empty);
492
2
                )*
493
23
            }
494
24
        }
495
    } };
496
}
497

            
498
#[cfg(test)]
499
mod test {
500
    // @@ begin test lint list maintained by maint/add_warning @@
501
    #![allow(clippy::bool_assert_comparison)]
502
    #![allow(clippy::clone_on_copy)]
503
    #![allow(clippy::dbg_macro)]
504
    #![allow(clippy::mixed_attributes_style)]
505
    #![allow(clippy::print_stderr)]
506
    #![allow(clippy::print_stdout)]
507
    #![allow(clippy::single_char_pattern)]
508
    #![allow(clippy::unwrap_used)]
509
    #![allow(clippy::unchecked_time_subtraction)]
510
    #![allow(clippy::useless_vec)]
511
    #![allow(clippy::needless_pass_by_value)]
512
    #![allow(clippy::string_slice)] // See arti#2571
513
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
514
    use super::*;
515
    use crate::{self as tor_config, sources::MustRead};
516
    use derive_builder::Builder;
517
    use serde::{Deserialize, Serialize};
518
    use serde_json::json;
519
    use tracing_test::traced_test;
520

            
521
    #[test]
522
    #[traced_test]
523
    fn reconfigure_helpers() {
524
        let how = Reconfigure::AllOrNothing;
525
        let err = how.cannot_change("the_laws_of_physics").unwrap_err();
526
        assert_eq!(
527
            err.to_string(),
528
            "Cannot change the_laws_of_physics on a running client.".to_owned()
529
        );
530

            
531
        let how = Reconfigure::WarnOnFailures;
532
        let ok = how.cannot_change("stuff");
533
        assert!(ok.is_ok());
534
        assert!(logs_contain("Cannot change stuff on a running client."));
535
    }
536

            
537
    #[test]
538
    #[rustfmt::skip] // autoformatting obscures the regular structure
539
    fn resolve_option_test() {
540
        #[derive(Debug, Clone, Builder, Eq, PartialEq)]
541
        #[builder(build_fn(error = "ConfigBuildError"))]
542
        #[builder(derive(Debug, Serialize, Deserialize, Eq, PartialEq))]
543
        struct TestConfig {
544
            #[builder(field(build = r#"tor_config::resolve_option(&self.none, || None)"#))]
545
            none: Option<u32>,
546

            
547
            #[builder(field(build = r#"tor_config::resolve_option(&self.four, || Some(4))"#))]
548
            four: Option<u32>,
549
        }
550

            
551
        // defaults
552
        {
553
            let builder_from_json: TestConfigBuilder = serde_json::from_value(
554
                json!{ { } }
555
            ).unwrap();
556

            
557
            let builder_from_methods = TestConfigBuilder::default();
558

            
559
            assert_eq!(builder_from_methods, builder_from_json);
560
            assert_eq!(builder_from_methods.build().unwrap(),
561
                        TestConfig { none: None, four: Some(4) });
562
        }
563

            
564
        // explicit positive values
565
        {
566
            let builder_from_json: TestConfigBuilder = serde_json::from_value(
567
                json!{ { "none": 123, "four": 456 } }
568
            ).unwrap();
569

            
570
            let mut builder_from_methods = TestConfigBuilder::default();
571
            builder_from_methods.none(Some(123));
572
            builder_from_methods.four(Some(456));
573

            
574
            assert_eq!(builder_from_methods, builder_from_json);
575
            assert_eq!(builder_from_methods.build().unwrap(),
576
                       TestConfig { none: Some(123), four: Some(456) });
577
        }
578

            
579
        // explicit "null" values
580
        {
581
            let builder_from_json: TestConfigBuilder = serde_json::from_value(
582
                json!{ { "none": 0, "four": 0 } }
583
            ).unwrap();
584

            
585
            let mut builder_from_methods = TestConfigBuilder::default();
586
            builder_from_methods.none(Some(0));
587
            builder_from_methods.four(Some(0));
588

            
589
            assert_eq!(builder_from_methods, builder_from_json);
590
            assert_eq!(builder_from_methods.build().unwrap(),
591
                       TestConfig { none: None, four: None });
592
        }
593

            
594
        // explicit None (API only, serde can't do this for Option)
595
        {
596
            let mut builder_from_methods = TestConfigBuilder::default();
597
            builder_from_methods.none(None);
598
            builder_from_methods.four(None);
599

            
600
            assert_eq!(builder_from_methods.build().unwrap(),
601
                       TestConfig { none: None, four: None });
602
        }
603
    }
604

            
605
    #[test]
606
    fn get_value() {
607
        use serde_value::Value as V;
608
        let to_value = |json_str: &str| {
609
            serde_value::to_value(serde_json::from_str::<serde_json::Value>(json_str).unwrap())
610
                .unwrap()
611
        };
612
        let mut sources = ConfigurationSources::new_empty();
613

            
614
        let source = "
615
        [foo]
616
        bar.baz = 7
617
        quux = [[],[],{}]
618
        ";
619
        let source = ConfigurationSource::from_verbatim(source.to_string());
620
        sources.push_source(source, MustRead::MustRead);
621

            
622
        let tree = sources.load().unwrap();
623

            
624
        {
625
            let v1 = tree.get_serde_value::<V>("foo.quux").unwrap().unwrap();
626
            let v2 = to_value(r#"[[], [], {}]"#);
627
            assert_eq!(v1, v2);
628
        }
629

            
630
        assert!(tree.get_serde_value::<V>("nonexist").unwrap().is_none());
631
        assert!(tree.get_serde_value::<V>("foo.nonexist").unwrap().is_none());
632
        assert!(
633
            tree.get_serde_value::<V>("foo.quux.nonexist")
634
                .unwrap()
635
                .is_none()
636
        );
637
    }
638
}