Stop relying on PartialEq for tests

This commit is contained in:
Jonas Platte 2020-05-02 00:08:03 +02:00
parent 752ea73010
commit 8e4ff82a83
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
10 changed files with 518 additions and 451 deletions

View File

@ -15,14 +15,15 @@ edition = "2018"
[dependencies]
js_int = { version = "0.1.5", features = ["serde"] }
ruma-events-macros = { path = "ruma-events-macros", version = "=0.21.0-beta.1" }
ruma-identifiers = "0.16.0"
ruma-identifiers = "0.16.1"
ruma-serde = "0.1.2"
serde = { version = "1.0.106", features = ["derive"] }
serde_json = { version = "1.0.52", features = ["raw_value"] }
[dev-dependencies]
maplit = "1.0.2"
ruma-identifiers = { version = "0.16.0", features = ["rand"] }
matches = "0.1.8"
ruma-identifiers = { version = "0.16.1", features = ["rand"] }
[workspace]
members = [

View File

@ -76,6 +76,7 @@ mod tests {
use std::convert::TryFrom;
use js_int::UInt;
use matches::assert_matches;
use ruma_identifiers::UserId;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -113,18 +114,6 @@ mod tests {
#[test]
fn deserialization() {
let event = PresenceEvent {
content: PresenceEventContent {
avatar_url: Some("mxc://localhost:wefuiwegh8742w".to_string()),
currently_active: Some(false),
displayname: None,
last_active_ago: Some(UInt::try_from(2_478_593).unwrap()),
presence: PresenceState::Online,
status_msg: Some("Making cupcakes".to_string()),
},
sender: UserId::try_from("@example:localhost").unwrap(),
};
let json = json!({
"content": {
"avatar_url": "mxc://localhost:wefuiwegh8742w",
@ -137,12 +126,25 @@ mod tests {
"type": "m.presence"
});
assert_eq!(
assert_matches!(
from_json_value::<EventJson<PresenceEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
event
PresenceEvent {
content: PresenceEventContent {
avatar_url: Some(avatar_url),
currently_active: Some(false),
displayname: None,
last_active_ago: Some(last_active_ago),
presence: PresenceState::Online,
status_msg: Some(status_msg),
},
sender,
} if avatar_url == "mxc://localhost:wefuiwegh8742w"
&& status_msg == "Making cupcakes"
&& sender == "@example:localhost"
&& last_active_ago == UInt::from(2_478_593u32)
);
}
}

View File

@ -393,6 +393,7 @@ pub struct SenderNotificationPermissionCondition {
#[cfg(test)]
mod tests {
use matches::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{
@ -410,13 +411,10 @@ mod tests {
fn serialize_tweak_sound_action() {
assert_eq!(
to_json_value(&Action::SetTweak(Tweak::Sound {
value: "default".to_string()
value: "default".into()
}))
.unwrap(),
json!({
"set_tweak": "sound",
"value": "default"
})
json!({ "set_tweak": "sound", "value": "default" })
);
}
@ -424,13 +422,13 @@ mod tests {
fn serialize_tweak_highlight_action() {
assert_eq!(
to_json_value(&Action::SetTweak(Tweak::Highlight { value: true })).unwrap(),
json!({"set_tweak": "highlight", "value": true})
json!({ "set_tweak": "highlight", "value": true })
);
}
#[test]
fn deserialize_string_action() {
assert_eq!(
assert_matches!(
from_json_value::<Action>(json!("notify")).unwrap(),
Action::Notify
);
@ -442,11 +440,9 @@ mod tests {
"set_tweak": "sound",
"value": "default"
});
assert_eq!(
from_json_value::<Action>(json_data).unwrap(),
Action::SetTweak(Tweak::Sound {
value: "default".to_string()
})
assert_matches!(
&from_json_value::<Action>(json_data).unwrap(),
Action::SetTweak(Tweak::Sound { value }) if value == "default"
);
}
@ -456,7 +452,7 @@ mod tests {
"set_tweak": "highlight",
"value": true
});
assert_eq!(
assert_matches!(
from_json_value::<Action>(json_data).unwrap(),
Action::SetTweak(Tweak::Highlight { value: true })
);
@ -464,8 +460,8 @@ mod tests {
#[test]
fn deserialize_tweak_highlight_action_with_default_value() {
assert_eq!(
from_json_value::<Action>(json!({"set_tweak": "highlight"})).unwrap(),
assert_matches!(
from_json_value::<Action>(json!({ "set_tweak": "highlight" })).unwrap(),
Action::SetTweak(Tweak::Highlight { value: true })
);
}
@ -534,20 +530,18 @@ mod tests {
"kind": "event_match",
"pattern": "m.notice"
});
assert_eq!(
assert_matches!(
from_json_value::<PushCondition>(json_data).unwrap(),
PushCondition::EventMatch(EventMatchCondition {
key: "content.msgtype".to_string(),
pattern: "m.notice".to_string(),
})
PushCondition::EventMatch(EventMatchCondition { key, pattern })
if key == "content.msgtype" && pattern == "m.notice"
);
}
#[test]
fn deserialize_contains_display_name_condition() {
assert_eq!(
assert_matches!(
from_json_value::<PushCondition>(json!({"kind": "contains_display_name"})).unwrap(),
PushCondition::ContainsDisplayName,
PushCondition::ContainsDisplayName
);
}
@ -557,11 +551,10 @@ mod tests {
"is": "2",
"kind": "room_member_count"
});
assert_eq!(
assert_matches!(
from_json_value::<PushCondition>(json_data).unwrap(),
PushCondition::RoomMemberCount(RoomMemberCountCondition {
is: "2".to_string(),
})
PushCondition::RoomMemberCount(RoomMemberCountCondition { is })
if is == "2"
);
}
@ -571,11 +564,11 @@ mod tests {
"key": "room",
"kind": "sender_notification_permission"
});
assert_eq!(
assert_matches!(
from_json_value::<PushCondition>(json_data).unwrap(),
PushCondition::SenderNotificationPermission(SenderNotificationPermissionCondition {
key: "room".to_string(),
})
key
}) if key == "room"
);
}
@ -586,196 +579,197 @@ mod tests {
"content": {
"global": {
"content": [
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
}
],
"default": true,
"enabled": true,
"pattern": "alice",
"rule_id": ".m.rule.contains_user_name"
}
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
}
],
"default": true,
"enabled": true,
"pattern": "alice",
"rule_id": ".m.rule.contains_user_name"
}
],
"override": [
{
"actions": [
"dont_notify"
],
"conditions": [],
"default": true,
"enabled": false,
"rule_id": ".m.rule.master"
},
{
"actions": [
"dont_notify"
],
"conditions": [
{
"key": "content.msgtype",
"kind": "event_match",
"pattern": "m.notice"
"actions": [
"dont_notify"
],
"conditions": [],
"default": true,
"enabled": false,
"rule_id": ".m.rule.master"
},
{
"actions": [
"dont_notify"
],
"conditions": [
{
"key": "content.msgtype",
"kind": "event_match",
"pattern": "m.notice"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.suppress_notices"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.suppress_notices"
}
],
"room": [],
"sender": [],
"underride": [
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "ring"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.call.invite"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.call"
},
{
"actions": [
"notify",
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "ring"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
"key": "type",
"kind": "event_match",
"pattern": "m.call.invite"
}
],
"conditions": [
{
"kind": "contains_display_name"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.contains_display_name"
},
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"is": "2",
"kind": "room_member_count"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.room_one_to_one"
},
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.member"
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.call"
},
{
"key": "content.membership",
"kind": "event_match",
"pattern": "invite"
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
}
],
"conditions": [
{
"kind": "contains_display_name"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.contains_display_name"
},
{
"key": "state_key",
"kind": "event_match",
"pattern": "@alice:example.com"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.invite_for_me"
},
{
"actions": [
"notify",
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"set_tweak": "highlight",
"value": false
"is": "2",
"kind": "room_member_count"
}
],
"conditions": [
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.room_one_to_one"
},
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.member"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.member_event"
},
{
"actions": [
"notify",
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"set_tweak": "highlight",
"value": false
"key": "type",
"kind": "event_match",
"pattern": "m.room.member"
},
{
"key": "content.membership",
"kind": "event_match",
"pattern": "invite"
},
{
"key": "state_key",
"kind": "event_match",
"pattern": "@alice:example.com"
}
],
"conditions": [
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.invite_for_me"
},
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.message"
"actions": [
"notify",
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.member"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.member_event"
},
{
"actions": [
"notify",
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
{
"key": "type",
"kind": "event_match",
"pattern": "m.room.message"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.message"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.message"
}
]
}
},
"type": "m.push_rules"
});
assert!(from_json_value::<EventJson<PushRulesEvent>>(json_data)
let _ = from_json_value::<EventJson<PushRulesEvent>>(json_data)
.unwrap()
.deserialize()
.is_ok());
.unwrap();
}
}

View File

@ -50,6 +50,7 @@ fn default_room_version_id() -> RoomVersionId {
mod tests {
use std::convert::TryFrom;
use matches::assert_matches;
use ruma_identifiers::{RoomVersionId, UserId};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -76,25 +77,24 @@ mod tests {
#[test]
fn deserialization() {
let content = CreateEventContent {
creator: UserId::try_from("@carl:example.com").unwrap(),
federate: true,
room_version: RoomVersionId::version_4(),
predecessor: None,
};
let json = json!({
"creator": "@carl:example.com",
"m.federate": true,
"room_version": "4"
});
assert_eq!(
assert_matches!(
from_json_value::<EventJson<CreateEventContent>>(json)
.unwrap()
.deserialize()
.unwrap(),
content
CreateEventContent {
creator,
federate: true,
room_version,
predecessor: None,
} if creator == "@carl:example.com"
&& room_version == RoomVersionId::version_4()
);
}
}

View File

@ -238,13 +238,14 @@ pub struct MegolmV1AesSha2Content {
#[cfg(test)]
mod tests {
use matches::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{Algorithm, EncryptedEventContent, MegolmV1AesSha2Content};
use crate::EventJson;
#[test]
fn serializtion() {
fn serialization() {
let key_verification_start_content =
EncryptedEventContent::MegolmV1AesSha2(MegolmV1AesSha2Content {
algorithm: Algorithm::MegolmV1AesSha2,
@ -270,15 +271,6 @@ mod tests {
#[test]
fn deserialization() {
let key_verification_start_content =
EncryptedEventContent::MegolmV1AesSha2(MegolmV1AesSha2Content {
algorithm: Algorithm::MegolmV1AesSha2,
ciphertext: "ciphertext".to_string(),
sender_key: "sender_key".to_string(),
device_id: "device_id".to_string(),
session_id: "session_id".to_string(),
});
let json_data = json!({
"algorithm": "m.megolm.v1.aes-sha2",
"ciphertext": "ciphertext",
@ -287,12 +279,21 @@ mod tests {
"session_id": "session_id"
});
assert_eq!(
assert_matches!(
from_json_value::<EventJson<EncryptedEventContent>>(json_data)
.unwrap()
.deserialize()
.unwrap(),
key_verification_start_content
EncryptedEventContent::MegolmV1AesSha2(MegolmV1AesSha2Content {
algorithm: Algorithm::MegolmV1AesSha2,
ciphertext,
sender_key,
device_id,
session_id,
}) if ciphertext == "ciphertext"
&& sender_key == "sender_key"
&& device_id == "device_id"
&& session_id == "session_id"
);
}

View File

@ -219,35 +219,19 @@ impl MemberEvent {
#[cfg(test)]
mod tests {
use std::{
convert::TryFrom,
time::{Duration, UNIX_EPOCH},
use std::time::{Duration, UNIX_EPOCH};
use maplit::btreemap;
use matches::assert_matches;
use serde_json::{from_value as from_json_value, json};
use super::{
MemberEvent, MemberEventContent, MembershipState, SignedContent, ThirdPartyInvite,
};
use ruma_identifiers::{EventId, RoomId, UserId};
use serde_json::json;
use super::*;
use crate::{util::serde_json_eq_try_from_raw, UnsignedData};
use crate::EventJson;
#[test]
fn serde_with_no_prev_content() {
let event = MemberEvent {
content: MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
},
event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(1),
room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
sender: UserId::try_from("@carl:example.com").unwrap(),
state_key: "example.com".to_string(),
unsigned: UnsignedData::default(),
prev_content: None,
};
let json = json!({
"type": "m.room.member",
"content": {
@ -259,33 +243,38 @@ mod tests {
"sender": "@carl:example.com",
"state_key": "example.com"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<MemberEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
MemberEvent {
content: MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
},
event_id,
origin_server_ts,
room_id: Some(room_id),
sender,
state_key,
unsigned,
prev_content: None,
} if event_id == "$h29iv0s8:example.com"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(1)
&& room_id == "!n8f893n9:example.com"
&& sender == "@carl:example.com"
&& state_key == "example.com"
&& unsigned.is_empty()
);
}
#[test]
fn serde_with_prev_content() {
let event = MemberEvent {
content: MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
},
event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(1),
room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
sender: UserId::try_from("@carl:example.com").unwrap(),
state_key: "example.com".to_string(),
unsigned: UnsignedData::default(),
prev_content: Some(MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
}),
};
let json = json!({
"type": "m.room.member",
"content": {
@ -300,42 +289,44 @@ mod tests {
"sender": "@carl:example.com",
"state_key": "example.com"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<MemberEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
MemberEvent {
content: MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
},
event_id,
origin_server_ts,
room_id: Some(room_id),
sender,
state_key,
unsigned,
prev_content: Some(MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
}),
} if event_id == "$h29iv0s8:example.com"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(1)
&& room_id == "!n8f893n9:example.com"
&& sender == "@carl:example.com"
&& state_key == "example.com"
&& unsigned.is_empty()
);
}
#[test]
fn serde_with_content_full() {
let signatures = vec![(
"magic.forest".to_owned(),
vec![("ed25519:3".to_owned(), "foobar".to_owned())]
.into_iter()
.collect(),
)]
.into_iter()
.collect();
let event = MemberEvent {
content: MemberEventContent {
avatar_url: Some("mxc://example.org/SEsfnsuifSDFSSEF".to_owned()),
displayname: Some("Alice Margatroid".to_owned()),
is_direct: Some(true),
membership: MembershipState::Invite,
third_party_invite: Some(ThirdPartyInvite {
display_name: "alice".to_owned(),
signed: SignedContent {
mxid: UserId::try_from("@alice:example.org").unwrap(),
signatures,
token: "abc123".to_owned(),
},
}),
},
event_id: EventId::try_from("$143273582443PhrSn:example.org").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(233),
room_id: Some(RoomId::try_from("!jEsUZKDJdhlrceRyVU:example.org").unwrap()),
sender: UserId::try_from("@alice:example.org").unwrap(),
state_key: "@alice:example.org".to_string(),
unsigned: UnsignedData::default(),
prev_content: None,
};
let json = json!({
"type": "m.room.member",
"content": {
@ -362,48 +353,51 @@ mod tests {
"sender": "@alice:example.org",
"state_key": "@alice:example.org"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<MemberEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
MemberEvent {
content: MemberEventContent {
avatar_url: Some(avatar_url),
displayname: Some(displayname),
is_direct: Some(true),
membership: MembershipState::Invite,
third_party_invite: Some(ThirdPartyInvite {
display_name: third_party_displayname,
signed: SignedContent { mxid, signatures, token },
}),
},
event_id,
origin_server_ts,
room_id: Some(room_id),
sender,
state_key,
unsigned,
prev_content: None,
} if avatar_url == "mxc://example.org/SEsfnsuifSDFSSEF"
&& displayname == "Alice Margatroid"
&& third_party_displayname == "alice"
&& mxid == "@alice:example.org"
&& signatures == btreemap! {
"magic.forest".to_owned() => btreemap! {
"ed25519:3".to_owned() => "foobar".to_owned()
}
}
&& token == "abc123"
&& event_id == "$143273582443PhrSn:example.org"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(233)
&& room_id == "!jEsUZKDJdhlrceRyVU:example.org"
&& sender == "@alice:example.org"
&& state_key == "@alice:example.org"
&& unsigned.is_empty()
)
}
#[test]
fn serde_with_prev_content_full() {
let signatures = vec![(
"magic.forest".to_owned(),
vec![("ed25519:3".to_owned(), "foobar".to_owned())]
.into_iter()
.collect(),
)]
.into_iter()
.collect();
let event = MemberEvent {
content: MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
},
event_id: EventId::try_from("$143273582443PhrSn:example.org").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(233),
room_id: Some(RoomId::try_from("!jEsUZKDJdhlrceRyVU:example.org").unwrap()),
sender: UserId::try_from("@alice:example.org").unwrap(),
state_key: "@alice:example.org".to_string(),
unsigned: UnsignedData::default(),
prev_content: Some(MemberEventContent {
avatar_url: Some("mxc://example.org/SEsfnsuifSDFSSEF".to_owned()),
displayname: Some("Alice Margatroid".to_owned()),
is_direct: Some(true),
membership: MembershipState::Invite,
third_party_invite: Some(ThirdPartyInvite {
display_name: "alice".to_owned(),
signed: SignedContent {
mxid: UserId::try_from("@alice:example.org").unwrap(),
signatures,
token: "abc123".to_owned(),
},
}),
}),
};
let json = json!({
"type": "m.room.member",
"content": {
@ -433,6 +427,52 @@ mod tests {
"sender": "@alice:example.org",
"state_key": "@alice:example.org"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<MemberEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
MemberEvent {
content: MemberEventContent {
avatar_url: None,
displayname: None,
is_direct: None,
membership: MembershipState::Join,
third_party_invite: None,
},
event_id,
origin_server_ts,
room_id: Some(room_id),
sender,
state_key,
unsigned,
prev_content: Some(MemberEventContent {
avatar_url: Some(avatar_url),
displayname: Some(displayname),
is_direct: Some(true),
membership: MembershipState::Invite,
third_party_invite: Some(ThirdPartyInvite {
display_name: third_party_displayname,
signed: SignedContent { mxid, signatures, token },
}),
}),
} if event_id == "$143273582443PhrSn:example.org"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(233)
&& room_id == "!jEsUZKDJdhlrceRyVU:example.org"
&& sender == "@alice:example.org"
&& state_key == "@alice:example.org"
&& unsigned.is_empty()
&& avatar_url == "mxc://example.org/SEsfnsuifSDFSSEF"
&& displayname == "Alice Margatroid"
&& third_party_displayname == "alice"
&& mxid == "@alice:example.org"
&& signatures == btreemap! {
"magic.forest".to_owned() => btreemap! {
"ed25519:3".to_owned() => "foobar".to_owned()
}
}
&& token == "abc123"
);
}
}

View File

@ -657,6 +657,7 @@ impl TextMessageEventContent {
#[cfg(test)]
mod tests {
use matches::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{AudioMessageEventContent, MessageEventContent};
@ -727,25 +728,23 @@ mod tests {
#[test]
fn deserialization() {
let message_event_content = MessageEventContent::Audio(AudioMessageEventContent {
body: "test".to_string(),
info: None,
url: Some("http://example.com/audio.mp3".to_string()),
file: None,
});
let json_data = json!({
"body": "test",
"msgtype": "m.audio",
"url": "http://example.com/audio.mp3"
});
assert_eq!(
assert_matches!(
from_json_value::<EventJson<MessageEventContent>>(json_data)
.unwrap()
.deserialize()
.unwrap(),
message_event_content
MessageEventContent::Audio(AudioMessageEventContent {
body,
info: None,
url: Some(url),
file: None,
}) if body == "test" && url == "http://example.com/audio.mp3"
);
}

View File

@ -55,7 +55,6 @@ mod tests {
assert_eq!(parsed_event.event_id(), event.event_id());
assert_eq!(parsed_event.room_id(), event.room_id());
assert_eq!(parsed_event.sender(), event.sender());
assert_eq!(parsed_event.unsigned(), event.unsigned());
assert_eq!(parsed_event.state_key(), event.state_key());
assert_eq!(parsed_event.origin_server_ts(), event.origin_server_ts());

View File

@ -1,9 +1,7 @@
use std::fmt::Debug;
use serde::{de::DeserializeOwned, Serialize};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::{EventJson, TryFromRaw};
use crate::TryFromRaw;
pub fn try_convert_variant<Enum: TryFromRaw, Content: TryFromRaw>(
variant: fn(Content) -> Enum,
@ -41,18 +39,3 @@ where
)
.map_err(serde_json_error_to_generic_de_error)
}
// This would be #[cfg(test)] if it wasn't used from external tests
pub fn serde_json_eq_try_from_raw<T>(de: T, se: serde_json::Value)
where
T: Clone + Debug + PartialEq + Serialize + TryFromRaw,
{
assert_eq!(se, serde_json::to_value(de.clone()).unwrap());
assert_eq!(
de,
serde_json::from_value::<EventJson<_>>(se)
.unwrap()
.deserialize()
.unwrap()
);
}

View File

@ -5,11 +5,12 @@ use std::{
};
use js_int::Int;
use ruma_events::util::serde_json_eq_try_from_raw;
use ruma_events::UnsignedData;
use maplit::btreemap;
use matches::assert_matches;
use ruma_events::{EventJson, UnsignedData};
use ruma_events_macros::ruma_event;
use ruma_identifiers::{EventId, RoomAliasId, RoomId, UserId};
use serde_json::json;
use ruma_identifiers::{RoomAliasId, RoomId, UserId};
use serde_json::{from_value as from_json_value, json};
// See note about wrapping macro expansion in a module from `src/lib.rs`
mod common_case {
@ -29,18 +30,6 @@ mod common_case {
#[test]
fn optional_fields_as_none() {
let event = AliasesEvent {
content: AliasesEventContent {
aliases: Vec::with_capacity(0),
},
event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(1),
prev_content: None,
room_id: None,
sender: UserId::try_from("@carl:example.com").unwrap(),
state_key: "example.com".to_string(),
unsigned: UnsignedData::default(),
};
let json = json!({
"content": {
"aliases": []
@ -51,25 +40,32 @@ mod common_case {
"state_key": "example.com",
"type": "m.room.aliases"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<AliasesEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
AliasesEvent {
content: AliasesEventContent { aliases },
event_id,
origin_server_ts,
prev_content: None,
room_id: None,
sender,
state_key,
unsigned,
} if aliases.is_empty()
&& event_id == "$h29iv0s8:example.com"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(1)
&& sender == "@carl:example.com"
&& state_key == "example.com"
&& unsigned.is_empty()
)
}
#[test]
fn some_optional_fields_as_some() {
let event = AliasesEvent {
content: AliasesEventContent {
aliases: vec![RoomAliasId::try_from("#room:example.org").unwrap()],
},
event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(1),
prev_content: Some(AliasesEventContent {
aliases: Vec::with_capacity(0),
}),
room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
sender: UserId::try_from("@carl:example.com").unwrap(),
state_key: "example.com".to_string(),
unsigned: UnsignedData::default(),
};
let json = json!({
"content": {
"aliases": ["#room:example.org"]
@ -84,28 +80,34 @@ mod common_case {
"state_key": "example.com",
"type": "m.room.aliases"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<AliasesEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
AliasesEvent {
content: AliasesEventContent { aliases, },
event_id,
origin_server_ts,
prev_content: Some(AliasesEventContent { aliases: prev_aliases }),
room_id: Some(room_id),
sender,
state_key,
unsigned,
} if aliases == vec![RoomAliasId::try_from("#room:example.org").unwrap()]
&& event_id == "$h29iv0s8:example.com"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(1)
&& prev_aliases.is_empty()
&& room_id == "!n8f893n9:example.com"
&& sender == "@carl:example.com"
&& state_key == "example.com"
&& unsigned.is_empty()
);
}
#[test]
fn all_optional_fields_as_some() {
let event = AliasesEvent {
content: AliasesEventContent {
aliases: vec![RoomAliasId::try_from("#room:example.org").unwrap()],
},
event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(1),
prev_content: Some(AliasesEventContent {
aliases: Vec::with_capacity(0),
}),
room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
sender: UserId::try_from("@carl:example.com").unwrap(),
state_key: "example.com".to_string(),
unsigned: UnsignedData {
age: Some(Int::from(100)),
..UnsignedData::default()
},
};
let json = json!({
"content": {
"aliases": ["#room:example.org"]
@ -123,7 +125,34 @@ mod common_case {
},
"type": "m.room.aliases"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<AliasesEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
AliasesEvent {
content: AliasesEventContent { aliases },
event_id,
origin_server_ts,
prev_content: Some(AliasesEventContent { aliases: prev_aliases }),
room_id: Some(room_id),
sender,
state_key,
unsigned: UnsignedData {
age: Some(age),
redacted_because: None,
transaction_id: None,
},
} if aliases == vec![RoomAliasId::try_from("#room:example.org").unwrap()]
&& event_id == "$h29iv0s8:example.com"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(1)
&& prev_aliases.is_empty()
&& room_id == "!n8f893n9:example.com"
&& sender == "@carl:example.com"
&& state_key == "example.com"
&& age == Int::from(100)
);
}
}
@ -148,18 +177,6 @@ mod extra_fields {
#[test]
fn field_serialization_deserialization() {
let event = RedactionEvent {
content: RedactionEventContent { reason: None },
redacts: EventId::try_from("$h29iv0s8:example.com").unwrap(),
event_id: EventId::try_from("$h29iv0s8:example.com").unwrap(),
origin_server_ts: UNIX_EPOCH + Duration::from_millis(1),
room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
sender: UserId::try_from("@carl:example.com").unwrap(),
unsigned: UnsignedData {
age: Some(Int::from(100)),
..UnsignedData::default()
},
};
let json = json!({
"content": {
"reason": null
@ -174,7 +191,31 @@ mod extra_fields {
},
"type": "m.room.redaction"
});
serde_json_eq_try_from_raw(event, json);
assert_matches!(
from_json_value::<EventJson<RedactionEvent>>(json)
.unwrap()
.deserialize()
.unwrap(),
RedactionEvent {
content: RedactionEventContent { reason: None },
redacts,
event_id,
origin_server_ts,
room_id: Some(room_id),
sender,
unsigned: UnsignedData {
age: Some(age),
redacted_because: None,
transaction_id: None,
},
} if redacts == "$h29iv0s8:example.com"
&& event_id == "$h29iv0s8:example.com"
&& origin_server_ts == UNIX_EPOCH + Duration::from_millis(1)
&& room_id == "!n8f893n9:example.com"
&& sender == "@carl:example.com"
&& age == Int::from(100)
);
}
}
@ -198,31 +239,38 @@ mod type_alias {
#[test]
fn alias_is_not_empty() {
let content = vec![(
UserId::try_from("@bob:example.com").unwrap(),
vec![RoomId::try_from("!n8f893n9:example.com").unwrap()],
)]
.into_iter()
.collect();
let event = DirectEvent { content };
let json = json!({
"content": {
"@bob:example.com": ["!n8f893n9:example.com"]
},
"type": "m.direct"
});
serde_json_eq_try_from_raw(event, json);
let event = from_json_value::<EventJson<DirectEvent>>(json)
.unwrap()
.deserialize()
.unwrap();
assert_eq!(
event.content,
btreemap! {
UserId::try_from("@bob:example.com").unwrap() => vec![
RoomId::try_from("!n8f893n9:example.com").unwrap()
]
}
);
}
#[test]
fn alias_empty() {
let content = Default::default();
let event = DirectEvent { content };
let json = json!({
"content": {},
"type": "m.direct"
});
serde_json_eq_try_from_raw(event, json);
let _ = from_json_value::<EventJson<DirectEvent>>(json)
.unwrap()
.deserialize()
.unwrap();
}
}