Fix ChatPrivate serialization

This commit is contained in:
Maybe Waffle 2022-06-16 13:02:17 +04:00
parent 5e5b8e46a3
commit ddaf78d891
2 changed files with 35 additions and 1 deletions

View file

@ -7,9 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## unreleased
- Fix `ChatPrivate` serialization ([#226][pr226])
- Build with particular crates versions (enable `"codec"` feature of `tokio-util`) ([#225][pr225])
- Fix incorrect panic in `User::is_channel` ([#222][pr222])
[pr226]: https://github.com/teloxide/teloxide-core/pull/226
[pr225]: https://github.com/teloxide/teloxide-core/pull/225
[pr222]: https://github.com/teloxide/teloxide-core/pull/222

View file

@ -81,6 +81,8 @@ pub struct ChatPrivate {
/// `private`.
#[serde(rename = "type")]
#[serde(deserialize_with = "assert_private_field")]
#[serde(serialize_with = "serialize_private_field")]
// FIXME(waffle): remove this entirely (replace with custom De/Serialize impl)
pub type_: (),
/// A username, for private chats, supergroups and channels if
@ -210,6 +212,13 @@ where
des.deserialize_str(PrivateChatKindVisitor)
}
fn serialize_private_field<S>(_: &(), ser: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
ser.serialize_str("private")
}
impl Chat {
pub fn is_private(&self) -> bool {
matches!(self.kind, ChatKind::Private(_))
@ -443,7 +452,7 @@ impl Chat {
#[cfg(test)]
mod tests {
use serde_json::from_str;
use serde_json::{from_str, to_string};
use crate::types::*;
@ -491,6 +500,29 @@ mod tests {
);
}
#[test]
fn private_roundtrip() {
let chat = Chat {
id: ChatId(0),
kind: ChatKind::Private(ChatPrivate {
type_: (),
username: Some("username".into()),
first_name: Some("Anon".into()),
last_name: None,
bio: None,
has_private_forwards: None,
}),
photo: None,
pinned_message: None,
message_auto_delete_time: None,
};
let json = to_string(&chat).unwrap();
let chat2 = from_str::<Chat>(&json).unwrap();
assert_eq!(chat, chat2);
}
#[test]
fn private_chat_de_wrong_type_field() {
assert!(from_str::<Chat>(r#"{"id":0,"type":"WRONG"}"#).is_err());