From 9a48cc944fc446dfb1322c6b1c7b46eb1fa38f4e Mon Sep 17 00:00:00 2001 From: Eguo Wang Date: Wed, 16 Aug 2023 22:35:52 +0800 Subject: [PATCH] Add unit tests for HostRequirements --- src/devcontainer/requirements.rs | 84 ++++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 3 deletions(-) diff --git a/src/devcontainer/requirements.rs b/src/devcontainer/requirements.rs index 0f1c478..b9c7275 100644 --- a/src/devcontainer/requirements.rs +++ b/src/devcontainer/requirements.rs @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; /// Host hardware requirements. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct HostRequirements { /// Number of required CPUs. minimum: 1 @@ -36,7 +36,8 @@ pub struct HostRequirements { pub gpu: Option, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] +#[serde(untagged)] pub enum GPUVar { /// Indicates whether a GPU is required. Boolean(bool), @@ -46,7 +47,7 @@ pub enum GPUVar { Config(GPUConfig), } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct GPUConfig { /// Number of required cores. minimum: 1 @@ -57,3 +58,80 @@ pub struct GPUConfig { #[serde(skip_serializing_if = "Option::is_none")] pub memory: Option, } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_host_requirements() { + use serde_json::json; + + let json = json!({ + "cpus": 1, + "memory": "1gb", + "storage": "1gb", + "gpu": { + "cores": 1, + "memory": "1gb" + } + }); + let host_requirements: HostRequirements = serde_json::from_value(json).unwrap(); + assert_eq!( + host_requirements, + HostRequirements { + cpus: Some(1), + memory: Some("1gb".to_string()), + storage: Some("1gb".to_string()), + gpu: Some(GPUVar::Config(GPUConfig { + cores: Some(1), + memory: Some("1gb".to_string()), + })), + } + ); + } + + #[test] + fn test_host_requirements_gpu_boolean() { + use serde_json::json; + + let json = json!({ + "cpus": 1, + "memory": "1gb", + "storage": "1gb", + "gpu": true + }); + let host_requirements: HostRequirements = serde_json::from_value(json).unwrap(); + assert_eq!( + host_requirements, + HostRequirements { + cpus: Some(1), + memory: Some("1gb".to_string()), + storage: Some("1gb".to_string()), + gpu: Some(GPUVar::Boolean(true)), + } + ); + } + + #[test] + fn test_host_requirements_gpu_string() { + use serde_json::json; + + let json = json!({ + "cpus": 1, + "memory": "1gb", + "storage": "1gb", + "gpu": "optional" + }); + let host_requirements: HostRequirements = serde_json::from_value(json).unwrap(); + assert_eq!( + host_requirements, + HostRequirements { + cpus: Some(1), + memory: Some("1gb".to_string()), + storage: Some("1gb".to_string()), + gpu: Some(GPUVar::String("optional".to_string())), + } + ); + } +}