Skip to content

Commit

Permalink
add some serialization/deserialization tests
Browse files Browse the repository at this point in the history
  • Loading branch information
gjcolombo committed Dec 2, 2024
1 parent 4da775b commit de183a9
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/propolis-api-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,6 @@ serde.workspace = true
serde_with.workspace = true
thiserror.workspace = true
uuid.workspace = true

[dev-dependencies]
serde_json.workspace = true
54 changes: 54 additions & 0 deletions crates/propolis-api-types/src/instance_spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,57 @@ impl From<Uuid> for SpecKey {
pub enum VersionedInstanceSpec {
V0(v0::InstanceSpecV0),
}

#[cfg(test)]
mod test {
use std::collections::BTreeMap;

use uuid::Uuid;

use super::{components::devices::QemuPvpanic, v0::ComponentV0, SpecKey};

type TestMap = BTreeMap<SpecKey, ComponentV0>;

// Verifies that UUID-type spec keys that are serialized and deserialized
// continue to be interpreted as UUID-type spec keys.
#[test]
fn spec_key_uuid_roundtrip() {
let id = Uuid::new_v4();
let mut map = TestMap::new();
map.insert(
SpecKey::Uuid(id),
ComponentV0::QemuPvpanic(QemuPvpanic { enable_isa: true }),
);

let ser = serde_json::to_string(&map).unwrap();
let unser: TestMap = serde_json::from_str(&ser).unwrap();
let key = unser.keys().next().expect("one key in the map");
let SpecKey::Uuid(got_id) = key else {
panic!("expected SpecKey::Uuid, got {}", key);
};

assert_eq!(*got_id, id);
}

// Verifies that serializing a name-type spec key that happens to be the
// string representation of a UUID causes the key to deserialize as a
// UUID-type key.
#[test]
fn spec_key_uuid_string_deserializes_as_uuid_variant() {
let id = Uuid::new_v4();
let mut map = TestMap::new();
map.insert(
SpecKey::Name(id.to_string()),
ComponentV0::QemuPvpanic(QemuPvpanic { enable_isa: true }),
);

let ser = serde_json::to_string(&map).unwrap();
let unser: TestMap = serde_json::from_str(&ser).unwrap();
let key = unser.keys().next().expect("one key in the map");
let SpecKey::Uuid(got_id) = key else {
panic!("expected SpecKey::Uuid, got {}", key);
};

assert_eq!(*got_id, id);
}
}

0 comments on commit de183a9

Please sign in to comment.