summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/config.rs11
-rw-r--r--tests/defaults.rs35
-rw-r--r--tests/empty.rs21
3 files changed, 64 insertions, 3 deletions
diff --git a/src/config.rs b/src/config.rs
index f19e59a..2ce73f1 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -10,7 +10,7 @@ use ser::ConfigSerializer;
use source::Source;
use path;
-use value::{Value, ValueKind, ValueWithKey};
+use value::{Table, Value, ValueKind, ValueWithKey};
#[derive(Clone, Debug)]
enum ConfigKind {
@@ -49,7 +49,12 @@ pub struct Config {
impl Config {
pub fn new() -> Self {
- Config::default()
+ Self {
+ kind: ConfigKind::default(),
+ // Config root should be instantiated as an empty table
+ // to avoid deserialization errors.
+ cache: Value::new(None, Table::new()),
+ }
}
/// Merge in a configuration property source.
@@ -192,7 +197,7 @@ impl Config {
T::deserialize(self)
}
- /// Attempt to deserialize the entire configuration into the requested type.
+ /// Attempt to serialize the entire configuration from the given type.
pub fn try_from<T: Serialize>(from: &T) -> Result<Self> {
let mut serializer = ConfigSerializer::default();
from.serialize(&mut serializer)?;
diff --git a/tests/defaults.rs b/tests/defaults.rs
new file mode 100644
index 0000000..8d863ae
--- /dev/null
+++ b/tests/defaults.rs
@@ -0,0 +1,35 @@
+extern crate config;
+
+#[macro_use]
+extern crate serde_derive;
+
+use config::*;
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Settings {
+ pub db_host: String,
+}
+
+impl Default for Settings {
+ fn default() -> Self {
+ Settings {
+ db_host: String::from("default"),
+ }
+ }
+}
+
+#[test]
+fn set_defaults() {
+ let c = Config::new();
+ let s: Settings = c.try_into().expect("Deserialization failed");
+
+ assert_eq!(s.db_host, "default");
+}
+
+#[test]
+fn try_from_defaults() {
+ let c = Config::try_from(&Settings::default()).expect("Serialization failed");
+ let s: Settings = c.try_into().expect("Deserialization failed");
+ assert_eq!(s.db_host, "default");
+}
diff --git a/tests/empty.rs b/tests/empty.rs
new file mode 100644
index 0000000..1f56d38
--- /dev/null
+++ b/tests/empty.rs
@@ -0,0 +1,21 @@
+extern crate config;
+
+#[macro_use]
+extern crate serde_derive;
+
+use config::*;
+
+#[derive(Debug, Serialize, Deserialize)]
+struct Settings {
+ #[serde(skip)]
+ foo: isize,
+ #[serde(skip)]
+ bar: u8,
+}
+
+#[test]
+fn empty_deserializes() {
+ let s: Settings = Config::new().try_into().expect("Deserialization failed");
+ assert_eq!(s.foo, 0);
+ assert_eq!(s.bar, 0);
+}