From 15167131f9356656b242298d32d3dfb2ad107f73 Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Tue, 2 Jan 2024 02:24:05 +0530 Subject: [PATCH] wip: Testing json parser --- src/types.rs | 47 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/src/types.rs b/src/types.rs index 6c8aca7..2dd231e 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,6 +1,7 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct Message { pub src: String, pub dest: String, @@ -9,17 +10,27 @@ pub struct Message { #[derive(Debug, Serialize, Deserialize)] pub(crate) struct MessageBody { - #[serde(rename = "type")] - message_type: String, - msg_id: i64, + msg_id: Option, in_reply_to: Option, + #[serde(rename = "type")] + message_type: String, + #[serde(flatten)] - pub message: MessageEnum, + pub message_body: MessageEnum, } #[derive(Debug, Serialize, Deserialize)] -pub enum MessageEnum {} +#[serde(untagged, deny_unknown_fields)] +pub enum MessageEnum { + Echo(EchoMessage), +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EchoMessage { + echo: String, +} #[cfg(test)] mod test { @@ -34,7 +45,8 @@ mod test { \"body\": { \"type\": \"echo\", \"msg_id\": 1, - \"echo\": \"Please echo 35\" + \"echo\": \"Please echo 35\", + \"extraneous\": \"hi\" } }"; @@ -44,8 +56,27 @@ mod test { eprintln!("successfully parsed into Message {:#?}", resp); } - eprintln!("{:#?}", resp); - assert!(resp.is_err()); } + + #[test] + pub fn parse_echo() { + let body = "{ + \"src\": \"c1\", + \"dest\": \"n1\", + \"body\": { + \"type\": \"echo\", + \"msg_id\": 1, + \"echo\": \"Please echo 35\" + } +}"; + + let resp: Result = serde_json::from_str(body); + + if resp.is_err() { + eprintln!("failed to parsed into Echo Message {:#?}", resp); + } + + assert!(resp.is_ok()); + } }