Rewrite tests to use serde_json::json! instead of raw strings

This commit is contained in:
Akshay 2020-03-31 19:37:09 +05:30 committed by GitHub
parent 8effddb5ec
commit 8915339e56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 745 additions and 393 deletions

View File

@ -25,7 +25,7 @@ mod tests {
use std::collections::HashMap;
use ruma_identifiers::{RoomId, UserId};
use serde_json::to_string;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{DirectEvent, DirectEventContent};
use crate::EventResult;
@ -39,15 +39,14 @@ mod tests {
content.insert(alice.clone(), room.clone());
let event = DirectEvent { content };
let json_data = json!({
"content": {
alice.to_string(): vec![room[0].to_string()],
},
"type": "m.direct"
});
assert_eq!(
to_string(&event).unwrap(),
format!(
r#"{{"type":"m.direct","content":{{"{}":["{}"]}}}}"#,
alice.to_string(),
room[0].to_string()
)
);
assert_eq!(to_json_value(&event).unwrap(), json_data);
}
#[test]
@ -58,17 +57,14 @@ mod tests {
RoomId::new("ruma.io").unwrap(),
];
let json_data = format!(
r#"{{
"type": "m.direct",
"content": {{ "{}": ["{}", "{}"] }}
}}"#,
alice.to_string(),
rooms[0].to_string(),
rooms[1].to_string()
);
let json_data = json!({
"content": {
alice.to_string(): vec![rooms[0].to_string(), rooms[1].to_string()],
},
"type": "m.direct"
});
let event: DirectEvent = serde_json::from_str::<EventResult<_>>(&json_data)
let event: DirectEvent = from_json_value::<EventResult<_>>(json_data)
.unwrap()
.into_result()
.unwrap();

View File

@ -29,21 +29,29 @@ mod tests {
use super::{DummyEvent, Empty};
use crate::EventResult;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
#[test]
fn serialization() {
let dummy_event = DummyEvent { content: Empty };
let actual = to_json_value(dummy_event).unwrap();
let actual = serde_json::to_string(&dummy_event).unwrap();
let expected = r#"{"type":"m.dummy","content":{}}"#;
let expected = json!({
"content": {},
"type": "m.dummy"
});
assert_eq!(actual, expected);
}
#[test]
fn deserialization() {
let json = r#"{"content":{},"type":"m.dummy"}"#;
let json = json!({
"content": {},
"type": "m.dummy"
});
assert!(serde_json::from_str::<EventResult<DummyEvent>>(json)
assert!(from_json_value::<EventResult<DummyEvent>>(json)
.unwrap()
.into_result()
.is_ok());

View File

@ -84,6 +84,7 @@ mod tests {
use std::convert::TryFrom;
use ruma_identifiers::UserId;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{IgnoredUserListEvent, IgnoredUserListEventContent};
use crate::EventResult;
@ -96,19 +97,30 @@ mod tests {
},
};
let json = serde_json::to_string(&ignored_user_list_event).unwrap();
let json_data = json!({
"content": {
"ignored_users": {
"@carl:example.com": {}
}
},
"type": "m.ignored_user_list"
});
assert_eq!(
json,
r#"{"content":{"ignored_users":{"@carl:example.com":{}}},"type":"m.ignored_user_list"}"#
);
assert_eq!(to_json_value(ignored_user_list_event).unwrap(), json_data);
}
#[test]
fn deserialization() {
let json = r#"{"content":{"ignored_users":{"@carl:example.com":{}}},"type":"m.ignored_user_list"}"#;
let json_data = json!({
"content": {
"ignored_users": {
"@carl:example.com": {}
}
},
"type": "m.ignored_user_list"
});
let actual = serde_json::from_str::<EventResult<IgnoredUserListEvent>>(json)
let actual = from_json_value::<EventResult<IgnoredUserListEvent>>(json_data)
.unwrap()
.into_result()
.unwrap();

View File

@ -134,27 +134,27 @@ impl From<CancelCode> for String {
#[cfg(test)]
mod tests {
use serde_json::{from_str, to_string};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::CancelCode;
#[test]
fn cancel_codes_serialize_to_display_form() {
assert_eq!(to_string(&CancelCode::User).unwrap(), r#""m.user""#);
assert_eq!(to_json_value(&CancelCode::User).unwrap(), json!("m.user"));
}
#[test]
fn custom_cancel_codes_serialize_to_display_form() {
assert_eq!(
to_string(&CancelCode::Custom("io.ruma.test".to_string())).unwrap(),
r#""io.ruma.test""#
to_json_value(&CancelCode::Custom("io.ruma.test".to_string())).unwrap(),
json!("io.ruma.test")
);
}
#[test]
fn cancel_codes_deserialize_from_display_form() {
assert_eq!(
from_str::<CancelCode>(r#""m.user""#).unwrap(),
from_json_value::<CancelCode>(json!("m.user")).unwrap(),
CancelCode::User
);
}
@ -162,7 +162,7 @@ mod tests {
#[test]
fn custom_cancel_codes_deserialize_from_display_form() {
assert_eq!(
from_str::<CancelCode>(r#""io.ruma.test""#).unwrap(),
from_json_value::<CancelCode>(json!("io.ruma.test")).unwrap(),
CancelCode::Custom("io.ruma.test".to_string())
)
}

View File

@ -325,7 +325,7 @@ impl Serialize for MSasV1Content {
#[cfg(test)]
mod tests {
use serde_json::to_string;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{
HashAlgorithm, KeyAgreementProtocol, MSasV1Content, MSasV1ContentOptions,
@ -415,10 +415,20 @@ mod tests {
content: key_verification_start_content,
};
assert_eq!(
to_string(&key_verification_start).unwrap(),
r#"{"content":{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]},"type":"m.key.verification.start"}"#
);
let json_data = json!({
"content": {
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"key_agreement_protocols": ["curve25519"],
"hashes": ["sha256"],
"message_authentication_codes": ["hkdf-hmac-sha256"],
"short_authentication_string": ["decimal"]
},
"type": "m.key.verification.start"
});
assert_eq!(to_json_value(&key_verification_start).unwrap(), json_data);
}
#[test]
@ -435,11 +445,19 @@ mod tests {
.unwrap(),
);
let json_data = json!({
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"hashes": ["sha256"],
"key_agreement_protocols": ["curve25519"],
"message_authentication_codes": ["hkdf-hmac-sha256"],
"short_authentication_string": ["decimal"]
});
// Deserialize the content struct separately to verify `TryFromRaw` is implemented for it.
assert_eq!(
serde_json::from_str::<EventResult<StartEventContent>>(
r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","hashes":["sha256"],"key_agreement_protocols":["curve25519"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]}"#
)
from_json_value::<EventResult<StartEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap(),
@ -450,10 +468,21 @@ mod tests {
content: key_verification_start_content,
};
let json_data = json!({
"content": {
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"key_agreement_protocols": ["curve25519"],
"hashes": ["sha256"],
"message_authentication_codes": ["hkdf-hmac-sha256"],
"short_authentication_string": ["decimal"]
},
"type": "m.key.verification.start"
});
assert_eq!(
serde_json::from_str::<EventResult<StartEvent>>(
r#"{"content":{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]},"type":"m.key.verification.start"}"#
)
from_json_value::<EventResult<StartEvent>>(json_data)
.unwrap()
.into_result()
.unwrap(),
@ -471,7 +500,7 @@ mod tests {
fn deserialization_structure_mismatch() {
// Missing several required fields.
let error =
serde_json::from_str::<EventResult<StartEventContent>>(r#"{"from_device":"123"}"#)
from_json_value::<EventResult<StartEventContent>>(json!({"from_device": "123"}))
.unwrap()
.into_result()
.unwrap_err();
@ -482,13 +511,20 @@ mod tests {
#[test]
fn deserialization_validation_missing_required_key_agreement_protocols() {
let error =
serde_json::from_str::<EventResult<StartEventContent>>(
r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":[],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]}"#
)
.unwrap()
.into_result()
.unwrap_err();
let json_data = json!({
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"key_agreement_protocols": [],
"hashes": ["sha256"],
"message_authentication_codes": ["hkdf-hmac-sha256"],
"short_authentication_string": ["decimal"]
});
let error = from_json_value::<EventResult<StartEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap_err();
assert!(error.message().contains("key_agreement_protocols"));
assert!(error.is_validation());
@ -496,13 +532,19 @@ mod tests {
#[test]
fn deserialization_validation_missing_required_hashes() {
let error =
serde_json::from_str::<EventResult<StartEventContent>>(
r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":[],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]}"#
)
.unwrap()
.into_result()
.unwrap_err();
let json_data = json!({
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"key_agreement_protocols": ["curve25519"],
"hashes": [],
"message_authentication_codes": ["hkdf-hmac-sha256"],
"short_authentication_string": ["decimal"]
});
let error = from_json_value::<EventResult<StartEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap_err();
assert!(error.message().contains("hashes"));
assert!(error.is_validation());
@ -510,13 +552,19 @@ mod tests {
#[test]
fn deserialization_validation_missing_required_message_authentication_codes() {
let error =
serde_json::from_str::<EventResult<StartEventContent>>(
r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":[],"short_authentication_string":["decimal"]}"#
)
.unwrap()
.into_result()
.unwrap_err();
let json_data = json!({
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"key_agreement_protocols": ["curve25519"],
"hashes": ["sha256"],
"message_authentication_codes": [],
"short_authentication_string": ["decimal"]
});
let error = from_json_value::<EventResult<StartEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap_err();
assert!(error.message().contains("message_authentication_codes"));
assert!(error.is_validation());
@ -524,13 +572,19 @@ mod tests {
#[test]
fn deserialization_validation_missing_required_short_authentication_string() {
let error =
serde_json::from_str::<EventResult<StartEventContent>>(
r#"{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":["curve25519"],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":[]}"#
)
.unwrap()
.into_result()
.unwrap_err();
let json_data = json!({
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"key_agreement_protocols": ["curve25519"],
"hashes": ["sha256"],
"message_authentication_codes": ["hkdf-hmac-sha256"],
"short_authentication_string": []
});
let error = from_json_value::<EventResult<StartEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap_err();
assert!(error.message().contains("short_authentication_string"));
assert!(error.is_validation());
@ -539,13 +593,22 @@ mod tests {
#[test]
fn deserialization_of_event_validates_content() {
// This JSON is missing the required value of "curve25519" for "key_agreement_protocols".
let error =
serde_json::from_str::<EventResult<StartEvent>>(
r#"{"content":{"from_device":"123","transaction_id":"456","method":"m.sas.v1","key_agreement_protocols":[],"hashes":["sha256"],"message_authentication_codes":["hkdf-hmac-sha256"],"short_authentication_string":["decimal"]},"type":"m.key.verification.start"}"#
)
.unwrap()
.into_result()
.unwrap_err();
let json_data = json!({
"content": {
"from_device": "123",
"transaction_id": "456",
"method": "m.sas.v1",
"key_agreement_protocols": [],
"hashes": ["sha256"],
"message_authentication_codes": ["hkdf-hmac-sha256"],
"short_authentication_string": ["decimal"]
},
"type": "m.key.verification.start"
});
let error = from_json_value::<EventResult<StartEvent>>(json_data)
.unwrap()
.into_result()
.unwrap_err();
assert!(error.message().contains("key_agreement_protocols"));
assert!(error.is_validation());

View File

@ -109,6 +109,7 @@
//! However, the `ruma_events::collections::only::Event` enum does *not* include *m.room.message*,
//! because *m.room.message* implements a *more specific* event trait than `Event`.
#![recursion_limit = "1024"]
#![warn(rust_2018_idioms)]
#![deny(missing_debug_implementations, missing_docs)]
// Since we support Rust 1.36.0, we can't apply this suggestion yet

View File

@ -77,7 +77,7 @@ mod tests {
use js_int::UInt;
use ruma_identifiers::UserId;
use serde_json::to_string;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{PresenceEvent, PresenceEventContent, PresenceState};
use crate::EventResult;
@ -96,9 +96,19 @@ mod tests {
sender: UserId::try_from("@example:localhost").unwrap(),
};
let json = r#"{"type":"m.presence","content":{"avatar_url":"mxc://localhost:wefuiwegh8742w","currently_active":false,"last_active_ago":2478593,"presence":"online","status_msg":"Making cupcakes"},"sender":"@example:localhost"}"#;
let json = json!({
"content": {
"avatar_url": "mxc://localhost:wefuiwegh8742w",
"currently_active": false,
"last_active_ago": 2_478_593,
"presence": "online",
"status_msg": "Making cupcakes"
},
"sender": "@example:localhost",
"type": "m.presence"
});
assert_eq!(to_string(&event).unwrap(), json);
assert_eq!(to_json_value(&event).unwrap(), json);
}
#[test]
@ -115,10 +125,20 @@ mod tests {
sender: UserId::try_from("@example:localhost").unwrap(),
};
let json = r#"{"type":"m.presence","content":{"avatar_url":"mxc://localhost:wefuiwegh8742w","currently_active":false,"last_active_ago":2478593,"presence":"online","status_msg":"Making cupcakes"},"sender":"@example:localhost"}"#;
let json = json!({
"content": {
"avatar_url": "mxc://localhost:wefuiwegh8742w",
"currently_active": false,
"last_active_ago": 2_478_593,
"presence": "online",
"status_msg": "Making cupcakes"
},
"sender": "@example:localhost",
"type": "m.presence"
});
assert_eq!(
serde_json::from_str::<EventResult<PresenceEvent>>(json)
from_json_value::<EventResult<PresenceEvent>>(json)
.unwrap()
.into_result()
.unwrap(),

View File

@ -434,7 +434,7 @@ impl Serialize for SenderNotificationPermissionCondition {
#[cfg(test)]
mod tests {
use serde_json::{from_str, to_string};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{
Action, EventMatchCondition, PushCondition, PushRulesEvent, RoomMemberCountCondition,
@ -444,37 +444,47 @@ mod tests {
#[test]
fn serialize_string_action() {
assert_eq!(to_string(&Action::Notify).unwrap(), r#""notify""#);
assert_eq!(to_json_value(&Action::Notify).unwrap(), json!("notify"));
}
#[test]
fn serialize_tweak_sound_action() {
assert_eq!(
to_string(&Action::SetTweak(Tweak::Sound {
to_json_value(&Action::SetTweak(Tweak::Sound {
value: "default".to_string()
}))
.unwrap(),
r#"{"set_tweak":"sound","value":"default"}"#
json!({
"set_tweak": "sound",
"value": "default"
})
);
}
#[test]
fn serialize_tweak_highlight_action() {
assert_eq!(
to_string(&Action::SetTweak(Tweak::Highlight { value: true })).unwrap(),
r#"{"set_tweak":"highlight","value":true}"#
to_json_value(&Action::SetTweak(Tweak::Highlight { value: true })).unwrap(),
json!({"set_tweak": "highlight", "value": true})
);
}
#[test]
fn deserialize_string_action() {
assert_eq!(from_str::<Action>(r#""notify""#).unwrap(), Action::Notify);
assert_eq!(
from_json_value::<Action>(json!("notify")).unwrap(),
Action::Notify
);
}
#[test]
fn deserialize_tweak_sound_action() {
let json_data = json!({
"set_tweak": "sound",
"value": "default"
});
assert_eq!(
from_str::<Action>(r#"{"set_tweak":"sound","value":"default"}"#).unwrap(),
from_json_value::<Action>(json_data).unwrap(),
Action::SetTweak(Tweak::Sound {
value: "default".to_string()
})
@ -483,8 +493,12 @@ mod tests {
#[test]
fn deserialize_tweak_highlight_action() {
let json_data = json!({
"set_tweak": "highlight",
"value": true
});
assert_eq!(
from_str::<Action>(r#"{"set_tweak":"highlight","value":true}"#).unwrap(),
from_json_value::<Action>(json_data).unwrap(),
Action::SetTweak(Tweak::Highlight { value: true })
);
}
@ -492,62 +506,77 @@ mod tests {
#[test]
fn deserialize_tweak_highlight_action_with_default_value() {
assert_eq!(
from_str::<Action>(r#"{"set_tweak":"highlight"}"#).unwrap(),
from_json_value::<Action>(json!({"set_tweak": "highlight"})).unwrap(),
Action::SetTweak(Tweak::Highlight { value: true })
);
}
#[test]
fn serialize_event_match_condition() {
let json_data = json!({
"key": "content.msgtype",
"kind": "event_match",
"pattern": "m.notice"
});
assert_eq!(
to_string(&PushCondition::EventMatch(EventMatchCondition {
to_json_value(&PushCondition::EventMatch(EventMatchCondition {
key: "content.msgtype".to_string(),
pattern: "m.notice".to_string(),
}))
.unwrap(),
r#"{"key":"content.msgtype","kind":"event_match","pattern":"m.notice"}"#
json_data
);
}
#[test]
fn serialize_contains_display_name_condition() {
assert_eq!(
to_string(&PushCondition::ContainsDisplayName).unwrap(),
r#"{"kind":"contains_display_name"}"#
to_json_value(&PushCondition::ContainsDisplayName).unwrap(),
json!({"kind": "contains_display_name"})
);
}
#[test]
fn serialize_room_member_count_condition() {
let json_data = json!({
"is": "2",
"kind": "room_member_count"
});
assert_eq!(
to_string(&PushCondition::RoomMemberCount(RoomMemberCountCondition {
to_json_value(&PushCondition::RoomMemberCount(RoomMemberCountCondition {
is: "2".to_string(),
}))
.unwrap(),
r#"{"is":"2","kind":"room_member_count"}"#
json_data
);
}
#[test]
fn serialize_sender_notification_permission_condition() {
let json_data = json!({
"key": "room",
"kind": "sender_notification_permission"
});
assert_eq!(
r#"{"key":"room","kind":"sender_notification_permission"}"#,
to_string(&PushCondition::SenderNotificationPermission(
json_data,
to_json_value(&PushCondition::SenderNotificationPermission(
SenderNotificationPermissionCondition {
key: "room".to_string(),
}
))
.unwrap(),
.unwrap()
);
}
#[test]
fn deserialize_event_match_condition() {
let json_data = json!({
"key": "content.msgtype",
"kind": "event_match",
"pattern": "m.notice"
});
assert_eq!(
from_str::<PushCondition>(
r#"{"key":"content.msgtype","kind":"event_match","pattern":"m.notice"}"#
)
.unwrap(),
from_json_value::<PushCondition>(json_data).unwrap(),
PushCondition::EventMatch(EventMatchCondition {
key: "content.msgtype".to_string(),
pattern: "m.notice".to_string(),
@ -558,15 +587,19 @@ mod tests {
#[test]
fn deserialize_contains_display_name_condition() {
assert_eq!(
from_str::<PushCondition>(r#"{"kind":"contains_display_name"}"#).unwrap(),
from_json_value::<PushCondition>(json!({"kind": "contains_display_name"})).unwrap(),
PushCondition::ContainsDisplayName,
);
}
#[test]
fn deserialize_room_member_count_condition() {
let json_data = json!({
"is": "2",
"kind": "room_member_count"
});
assert_eq!(
from_str::<PushCondition>(r#"{"is":"2","kind":"room_member_count"}"#).unwrap(),
from_json_value::<PushCondition>(json_data).unwrap(),
PushCondition::RoomMemberCount(RoomMemberCountCondition {
is: "2".to_string(),
})
@ -575,9 +608,12 @@ mod tests {
#[test]
fn deserialize_sender_notification_permission_condition() {
let json_data = json!({
"key": "room",
"kind": "sender_notification_permission"
});
assert_eq!(
from_str::<PushCondition>(r#"{"key":"room","kind":"sender_notification_permission"}"#)
.unwrap(),
from_json_value::<PushCondition>(json_data).unwrap(),
PushCondition::SenderNotificationPermission(SenderNotificationPermissionCondition {
key: "room".to_string(),
})
@ -587,134 +623,134 @@ mod tests {
#[test]
fn sanity_check() {
// This is a full example of a push rules event from the specification.
let json = r#"{
"content": {
"global": {
"content": [
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
}
let json_data = json!({
"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"
}
],
"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": [
"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"
}
],
"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": [
"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",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight"
}
],
"conditions": [
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.call"
},
{
"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"
},
{
"actions": [
"notify",
{
"set_tweak": "sound",
"value": "default"
},
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
],
"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": [
],
"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",
@ -730,55 +766,55 @@ mod tests {
"kind": "event_match",
"pattern": "@alice:example.com"
}
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.invite_for_me"
},
{
"actions": [
"notify",
{
"set_tweak": "highlight",
"value": false
}
],
"conditions": [
],
"default": true,
"enabled": true,
"rule_id": ".m.rule.invite_for_me"
},
{
"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": [
],
"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!(serde_json::from_str::<EventResult<PushRulesEvent>>(json)
},
"type": "m.push_rules"
});
assert!(from_json_value::<EventResult<PushRulesEvent>>(json_data)
.unwrap()
.into_result()
.is_ok());

View File

@ -174,7 +174,7 @@ mod tests {
use js_int::UInt;
use ruma_identifiers::{EventId, RoomAliasId, UserId};
use serde_json::Map;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value, Map};
use super::{CanonicalAliasEvent, CanonicalAliasEventContent};
use crate::EventResult;
@ -194,18 +194,34 @@ mod tests {
unsigned: Map::new(),
};
let actual = serde_json::to_string(&canonical_alias_event).unwrap();
let expected = r##"{"content":{"alias":"#somewhere:localhost"},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.canonical_alias"}"##;
let actual = to_json_value(&canonical_alias_event).unwrap();
let expected = json!({
"content": {
"alias": "#somewhere:localhost"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.canonical_alias"
});
assert_eq!(actual, expected);
}
#[test]
fn absent_field_as_none() {
let json_data = json!({
"content": {},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.canonical_alias"
});
assert_eq!(
serde_json::from_str::<EventResult<CanonicalAliasEvent>>(
r#"{"content":{},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.canonical_alias"}"#
)
from_json_value::<EventResult<CanonicalAliasEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()
@ -217,10 +233,18 @@ mod tests {
#[test]
fn null_field_as_none() {
let json_data = json!({
"content": {
"alias": null
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.canonical_alias"
});
assert_eq!(
serde_json::from_str::<EventResult<CanonicalAliasEvent>>(
r#"{"content":{"alias":null},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.canonical_alias"}"#
)
from_json_value::<EventResult<CanonicalAliasEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()
@ -232,10 +256,18 @@ mod tests {
#[test]
fn empty_field_as_none() {
let json_data = json!({
"content": {
"alias": ""
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.canonical_alias"
});
assert_eq!(
serde_json::from_str::<EventResult<CanonicalAliasEvent>>(
r#"{"content":{"alias":""},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.canonical_alias"}"#
)
from_json_value::<EventResult<CanonicalAliasEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()
@ -248,11 +280,18 @@ mod tests {
#[test]
fn nonempty_field_as_some() {
let alias = Some(RoomAliasId::try_from("#somewhere:localhost").unwrap());
let json_data = json!({
"content": {
"alias": "#somewhere:localhost"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.canonical_alias"
});
assert_eq!(
serde_json::from_str::<EventResult<CanonicalAliasEvent>>(
r##"{"content":{"alias":"#somewhere:localhost"},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.canonical_alias"}"##
)
from_json_value::<EventResult<CanonicalAliasEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()

View File

@ -54,6 +54,7 @@ mod tests {
use std::convert::TryFrom;
use ruma_identifiers::{RoomVersionId, UserId};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::CreateEventContent;
use crate::EventResult;
@ -67,9 +68,13 @@ mod tests {
predecessor: None,
};
let json = r#"{"creator":"@carl:example.com","m.federate":true,"room_version":"4"}"#;
let json = json!({
"creator": "@carl:example.com",
"m.federate": true,
"room_version": "4"
});
assert_eq!(serde_json::to_string(&content).unwrap(), json);
assert_eq!(to_json_value(&content).unwrap(), json);
}
#[test]
@ -81,10 +86,14 @@ mod tests {
predecessor: None,
};
let json = r#"{"creator":"@carl:example.com","m.federate":true,"room_version":"4"}"#;
let json = json!({
"creator": "@carl:example.com",
"m.federate": true,
"room_version": "4"
});
assert_eq!(
serde_json::from_str::<EventResult<CreateEventContent>>(json)
from_json_value::<EventResult<CreateEventContent>>(json)
.unwrap()
.into_result()
.unwrap(),

View File

@ -278,7 +278,7 @@ pub struct MegolmV1AesSha2Content {
#[cfg(test)]
mod tests {
use serde_json::to_string;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{Algorithm, EncryptedEventContent, MegolmV1AesSha2Content};
use crate::EventResult;
@ -294,9 +294,17 @@ mod tests {
session_id: "session_id".to_string(),
});
let json_data = json!({
"algorithm": "m.megolm.v1.aes-sha2",
"ciphertext": "ciphertext",
"sender_key": "sender_key",
"device_id": "device_id",
"session_id": "session_id"
});
assert_eq!(
to_string(&key_verification_start_content).unwrap(),
r#"{"algorithm":"m.megolm.v1.aes-sha2","ciphertext":"ciphertext","sender_key":"sender_key","device_id":"device_id","session_id":"session_id"}"#
to_json_value(&key_verification_start_content).unwrap(),
json_data
);
}
@ -311,22 +319,36 @@ mod tests {
session_id: "session_id".to_string(),
});
let json_data = json!({
"algorithm": "m.megolm.v1.aes-sha2",
"ciphertext": "ciphertext",
"sender_key": "sender_key",
"device_id": "device_id",
"session_id": "session_id"
});
assert_eq!(
serde_json::from_str::<EventResult<EncryptedEventContent>>(
r#"{"algorithm":"m.megolm.v1.aes-sha2","ciphertext":"ciphertext","sender_key":"sender_key","device_id":"device_id","session_id":"session_id"}"#
)
.unwrap()
.into_result()
.unwrap(),
from_json_value::<EventResult<EncryptedEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap(),
key_verification_start_content
);
}
#[test]
fn deserialization_olm() {
let content = serde_json::from_str::<EventResult<EncryptedEventContent>>(
r#"{"sender_key":"test_key", "ciphertext":{ "test_curve_key": { "body": "encrypted_body", "type": 1 }},"algorithm": "m.olm.v1.curve25519-aes-sha2"}"#
)
let json_data = json!({
"sender_key": "test_key",
"ciphertext": {
"test_curve_key": {
"body": "encrypted_body",
"type": 1
}
},
"algorithm": "m.olm.v1.curve25519-aes-sha2"
});
let content = from_json_value::<EventResult<EncryptedEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap();
@ -345,8 +367,8 @@ mod tests {
#[test]
fn deserialization_failure() {
assert!(serde_json::from_str::<EventResult<EncryptedEventContent>>(
r#"{"algorithm":"m.megolm.v1.aes-sha2"}"#
assert!(from_json_value::<EventResult<EncryptedEventContent>>(
json!({"algorithm": "m.megolm.v1.aes-sha2"})
)
.unwrap()
.into_result()

View File

@ -357,7 +357,7 @@ mod tests {
}
},
"event_id": "$143273582443PhrSn:example.org",
"origin_server_ts":233,
"origin_server_ts": 233,
"room_id": "!jEsUZKDJdhlrceRyVU:example.org",
"sender": "@alice:example.org",
"state_key": "@alice:example.org"

View File

@ -1047,7 +1047,7 @@ impl Serialize for VideoMessageEventContent {
#[cfg(test)]
mod tests {
use serde_json::to_string;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{AudioMessageEventContent, MessageEventContent};
use crate::room::message::{InReplyTo, RelatesTo, TextMessageEventContent};
@ -1065,8 +1065,12 @@ mod tests {
});
assert_eq!(
to_string(&message_event_content).unwrap(),
r#"{"body":"test","msgtype":"m.audio","url":"http://example.com/audio.mp3"}"#
to_json_value(&message_event_content).unwrap(),
json!({
"body": "test",
"msgtype": "m.audio",
"url": "http://example.com/audio.mp3"
})
);
}
@ -1077,8 +1081,11 @@ mod tests {
));
assert_eq!(
to_string(&message_event_content).unwrap(),
r#"{"body":"> <@test:example.com> test\n\ntest reply","msgtype":"m.text"}"#
to_json_value(&message_event_content).unwrap(),
json!({
"body": "> <@test:example.com> test\n\ntest reply",
"msgtype": "m.text"
})
);
}
@ -1095,10 +1102,17 @@ mod tests {
}),
});
assert_eq!(
to_string(&message_event_content).unwrap(),
r#"{"body":"> <@test:example.com> test\n\ntest reply","msgtype":"m.text","m.relates_to":{"m.in_reply_to":{"event_id":"$15827405538098VGFWH:example.com"}}}"#
);
let json_data = json!({
"body": "> <@test:example.com> test\n\ntest reply",
"msgtype": "m.text",
"m.relates_to": {
"m.in_reply_to": {
"event_id": "$15827405538098VGFWH:example.com"
}
}
});
assert_eq!(to_json_value(&message_event_content).unwrap(), json_data);
}
#[test]
@ -1110,24 +1124,32 @@ mod tests {
file: None,
});
let json_data = json!({
"body": "test",
"msgtype": "m.audio",
"url": "http://example.com/audio.mp3"
});
assert_eq!(
serde_json::from_str::<EventResult<MessageEventContent>>(
r#"{"body":"test","msgtype":"m.audio","url":"http://example.com/audio.mp3"}"#
)
.unwrap()
.into_result()
.unwrap(),
from_json_value::<EventResult<MessageEventContent>>(json_data)
.unwrap()
.into_result()
.unwrap(),
message_event_content
);
}
#[test]
fn deserialization_failure() {
assert!(serde_json::from_str::<EventResult<MessageEventContent>>(
r#"{"body":"test","msgtype":"m.location","url":"http://example.com/audio.mp3"}"#
)
.unwrap()
.into_result()
.is_err());
let json_data = json!({
"body": "test","msgtype": "m.location",
"url": "http://example.com/audio.mp3"
});
assert!(
from_json_value::<EventResult<MessageEventContent>>(json_data)
.unwrap()
.into_result()
.is_err()
);
}
}

View File

@ -197,7 +197,7 @@ mod tests {
use js_int::UInt;
use ruma_identifiers::{EventId, RoomId, UserId};
use serde_json::Map;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value, Map};
use crate::EventResult;
@ -218,8 +218,17 @@ mod tests {
unsigned: Map::new(),
};
let actual = serde_json::to_string(&name_event).unwrap();
let expected = r#"{"content":{"name":"The room name"},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.name"}"#;
let actual = to_json_value(&name_event).unwrap();
let expected = json!({
"content": {
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(actual, expected);
}
@ -238,21 +247,41 @@ mod tests {
room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
sender: UserId::try_from("@carl:example.com").unwrap(),
state_key: "".to_string(),
unsigned: serde_json::from_str(r#"{"foo":"bar"}"#).unwrap(),
unsigned: serde_json::from_str(r#"{"foo": "bar"}"#).unwrap(),
};
let actual = serde_json::to_string(&name_event).unwrap();
let expected = r#"{"content":{"name":"The room name"},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"prev_content":{"name":"The old name"},"room_id":"!n8f893n9:example.com","sender":"@carl:example.com","state_key":"","type":"m.room.name","unsigned":{"foo":"bar"}}"#;
let actual = to_json_value(&name_event).unwrap();
let expected = json!({
"content": {
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"prev_content": {"name": "The old name"},
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name",
"unsigned": {
"foo": "bar"
}
});
assert_eq!(actual, expected);
}
#[test]
fn absent_field_as_none() {
let json_data = json!({
"content": {},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
serde_json::from_str::<EventResult<NameEvent>>(
r#"{"content":{},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.name"}"#
)
from_json_value::<EventResult<NameEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()
@ -300,10 +329,18 @@ mod tests {
#[test]
fn null_field_as_none() {
let json_data = json!({
"content": {
"name": null
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
serde_json::from_str::<EventResult<NameEvent>>(
r#"{"content":{"name":null},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.name"}"#
)
from_json_value::<EventResult<NameEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()
@ -315,10 +352,18 @@ mod tests {
#[test]
fn empty_string_as_none() {
let json_data = json!({
"content": {
"name": ""
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
serde_json::from_str::<EventResult<NameEvent>>(
r#"{"content":{"name":""},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.name"}"#
)
from_json_value::<EventResult<NameEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()
@ -331,11 +376,19 @@ mod tests {
#[test]
fn nonempty_field_as_some() {
let name = Some("The room name".to_string());
let json_data = json!({
"content": {
"name": "The room name"
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.name"
});
assert_eq!(
serde_json::from_str::<EventResult<NameEvent>>(
r#"{"content":{"name":"The room name"},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.name"}"#
)
from_json_value::<EventResult<NameEvent>>(json_data)
.unwrap()
.into_result()
.unwrap()

View File

@ -308,7 +308,7 @@ mod tests {
use js_int::{Int, UInt};
use maplit::hashmap;
use ruma_identifiers::{EventId, RoomId, UserId};
use serde_json::Map;
use serde_json::{json, to_value as to_json_value, Map};
use super::{
default_power_level, NotificationPowerLevels, PowerLevelsEvent, PowerLevelsEventContent,
@ -341,8 +341,15 @@ mod tests {
state_key: "".to_string(),
};
let actual = serde_json::to_string(&power_levels_event).unwrap();
let expected = r#"{"content":{},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.power_levels"}"#;
let actual = to_json_value(&power_levels_event).unwrap();
let expected = json!({
"content": {},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.power_levels"
});
assert_eq!(actual, expected);
}
@ -391,13 +398,59 @@ mod tests {
},
}),
room_id: Some(RoomId::try_from("!n8f893n9:example.com").unwrap()),
unsigned: serde_json::from_str(r#"{"foo":"bar"}"#).unwrap(),
unsigned: serde_json::from_str(r#"{"foo": "bar"}"#).unwrap(),
sender: user,
state_key: "".to_string(),
};
let actual = serde_json::to_string(&power_levels_event).unwrap();
let expected = r#"{"content":{"ban":23,"events":{"m.dummy":23},"events_default":23,"invite":23,"kick":23,"redact":23,"state_default":23,"users":{"@carl:example.com":23},"users_default":23,"notifications":{"room":23}},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"prev_content":{"ban":42,"events":{"m.dummy":42},"events_default":42,"invite":42,"kick":42,"redact":42,"state_default":42,"users":{"@carl:example.com":42},"users_default":42,"notifications":{"room":42}},"room_id":"!n8f893n9:example.com","sender":"@carl:example.com","state_key":"","type":"m.room.power_levels","unsigned":{"foo":"bar"}}"#;
let actual = to_json_value(&power_levels_event).unwrap();
let expected = json!({
"content": {
"ban": 23,
"events": {
"m.dummy": 23
},
"events_default": 23,
"invite": 23,
"kick": 23,
"redact": 23,
"state_default": 23,
"users": {
"@carl:example.com": 23
},
"users_default": 23,
"notifications": {
"room": 23
}
},
"event_id": "$h29iv0s8:example.com",
"origin_server_ts": 1,
"prev_content": {
"ban": 42,
"events": {
"m.dummy": 42
},
"events_default": 42,
"invite": 42,
"kick": 42,
"redact": 42,
"state_default": 42,
"users": {
"@carl:example.com": 42
},
"users_default": 42,
"notifications": {
"room": 42
}
},
"room_id": "!n8f893n9:example.com",
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.power_levels",
"unsigned": {
"foo": "bar"
}
});
assert_eq!(actual, expected);
}

View File

@ -180,14 +180,24 @@ pub(crate) mod raw {
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json};
use super::ServerAclEvent;
use crate::EventResult;
#[test]
fn default_values() {
let server_acl_event: ServerAclEvent =
serde_json::from_str::<EventResult<_>>(r#"{"content":{},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.server_acl"}"#)
.unwrap().into_result().unwrap();
let json_data = json!({
"content": {},
"event_id": "$h29iv0s8:example.com","origin_server_ts":1,
"sender": "@carl:example.com",
"state_key": "",
"type": "m.room.server_acl"
});
let server_acl_event: ServerAclEvent = from_json_value::<EventResult<_>>(json_data)
.unwrap()
.into_result()
.unwrap();
assert_eq!(server_acl_event.content.allow_ip_literals, true);
assert!(server_acl_event.content.allow.is_empty());

View File

@ -312,7 +312,7 @@ mod tests {
use js_int::UInt;
use ruma_identifiers::UserId;
use serde_json::to_string;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use super::{AnyStrippedStateEvent, StrippedRoomName, StrippedRoomTopic};
use crate::{
@ -333,29 +333,35 @@ mod tests {
let event = AnyStrippedStateEvent::RoomTopic(content);
assert_eq!(
to_string(&event).unwrap(),
r#"{"content":{"topic":"Testing room"},"type":"m.room.topic","state_key":"","sender":"@example:localhost"}"#
);
let json_data = json!({
"content": {
"topic": "Testing room"
},
"type": "m.room.topic",
"state_key": "",
"sender": "@example:localhost"
});
assert_eq!(to_json_value(&event).unwrap(), json_data);
}
#[test]
fn deserialize_stripped_state_events() {
let name_event = r#"{
let name_event = json!({
"type": "m.room.name",
"state_key": "",
"sender": "@example:localhost",
"content": {"name": "Ruma"}
}"#;
});
let join_rules_event = r#"{
let join_rules_event = json!({
"type": "m.room.join_rules",
"state_key": "",
"sender": "@example:localhost",
"content": { "join_rule": "public" }
}"#;
});
let avatar_event = r#"{
let avatar_event = json!({
"type": "m.room.avatar",
"state_key": "",
"sender": "@example:localhost",
@ -382,9 +388,9 @@ mod tests {
"thumbnail_url": "https://example.com/image-thumbnail.jpg",
"url": "https://example.com/image.jpg"
}
}"#;
});
match serde_json::from_str::<EventResult<_>>(name_event)
match from_json_value::<EventResult<_>>(name_event.clone())
.unwrap()
.into_result()
.unwrap()
@ -399,14 +405,12 @@ mod tests {
};
// Ensure `StrippedStateContent` can be parsed, not just `StrippedState`.
assert!(
serde_json::from_str::<EventResult<StrippedRoomName>>(name_event)
.unwrap()
.into_result()
.is_ok()
);
assert!(from_json_value::<EventResult<StrippedRoomName>>(name_event)
.unwrap()
.into_result()
.is_ok());
match serde_json::from_str::<EventResult<_>>(join_rules_event)
match from_json_value::<EventResult<_>>(join_rules_event)
.unwrap()
.into_result()
.unwrap()
@ -420,7 +424,7 @@ mod tests {
_ => unreachable!(),
};
match serde_json::from_str::<EventResult<_>>(avatar_event)
match from_json_value::<EventResult<_>>(avatar_event)
.unwrap()
.into_result()
.unwrap()

View File

@ -261,6 +261,7 @@ mod tests {
use js_int::UInt;
use ruma_identifiers::{RoomId, UserId};
use serde_json::{from_value as from_json_value, json};
use super::AnyToDeviceEvent;
use crate::{
@ -275,10 +276,10 @@ mod tests {
macro_rules! deserialize {
($source:ident, $($target:tt)*) => {{
let event = serde_json::from_str::<EventResult<AnyToDeviceEvent>>($source)
let event = from_json_value::<EventResult<AnyToDeviceEvent>>($source)
.expect(&format!(
"Can't deserialize to-device event: {} from source {}",
stringify!($($target)*), $source
stringify!($($target)*), stringify!($source)
));
let event = event
@ -303,11 +304,11 @@ mod tests {
#[test]
fn dummy() {
let dummy = r#"{
let dummy = json!({
"content": {},
"sender": "@alice:example.org",
"type": "m.dummy"
}"#;
});
let event = deserialize! {dummy, AnyToDeviceEvent::Dummy};
@ -316,7 +317,7 @@ mod tests {
#[test]
fn room_key() {
let room_key = r#"{
let room_key = json!({
"content": {
"algorithm": "m.megolm.v1.aes-sha2",
"room_id": "!test:localhost",
@ -325,7 +326,7 @@ mod tests {
},
"sender": "@alice:example.org",
"type": "m.room_key"
}"#;
});
let event = deserialize! {room_key, AnyToDeviceEvent::RoomKey};
@ -340,7 +341,7 @@ mod tests {
#[test]
fn encrypted_olm() {
let source = r#"{
let source = json!({
"content": {
"sender_key": "test_sender_key",
"ciphertext": {
@ -357,7 +358,7 @@ mod tests {
},
"type": "m.room.encrypted",
"sender": "@alice:example.org"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::RoomEncrypted};
@ -377,7 +378,7 @@ mod tests {
#[test]
fn forwarded_room_key() {
let source = r#"{
let source = json!({
"content": {
"algorithm": "m.megolm.v1.aes-sha2",
"forwarding_curve25519_key_chain": [
@ -391,7 +392,7 @@ mod tests {
},
"sender": "@alice:example.org",
"type": "m.forwarded_room_key"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::ForwardedRoomKey};
@ -414,7 +415,7 @@ mod tests {
#[test]
fn key_request() {
let source = r#"{
let source = json!({
"sender": "@alice:example.org",
"content": {
"action": "request",
@ -428,7 +429,7 @@ mod tests {
"requesting_device_id": "RJYKSTBOIE"
},
"type": "m.room_key_request"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::RoomKeyRequest};
let body = event.content.body.as_ref().unwrap();
@ -449,7 +450,7 @@ mod tests {
#[test]
fn key_request_cancel() {
let source = r#"{
let source = json!({
"sender": "@alice:example.org",
"content": {
"action": "request_cancellation",
@ -457,7 +458,7 @@ mod tests {
"requesting_device_id": "RJYKSTBOIE"
},
"type": "m.room_key_request"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::RoomKeyRequest};
assert_eq!(event.content.action, Action::CancelRequest);
@ -467,7 +468,7 @@ mod tests {
#[test]
fn key_verification_start() {
let source = r#"{
let source = json!({
"content": {
"from_device": "AliceDevice1",
"hashes": [
@ -488,7 +489,7 @@ mod tests {
},
"type": "m.key.verification.start",
"sender": "@alice:example.org"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::KeyVerificationStart};
@ -519,7 +520,7 @@ mod tests {
#[test]
fn key_verification_accept() {
let source = r#"{
let source = json!({
"content": {
"commitment": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg",
"hash": "sha256",
@ -534,7 +535,7 @@ mod tests {
},
"type": "m.key.verification.accept",
"sender": "@alice:example.org"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::KeyVerificationAccept};
assert_eq!(event.content.hash, HashAlgorithm::Sha256);
@ -563,14 +564,14 @@ mod tests {
#[test]
fn key_verification_key() {
let source = r#"{
let source = json!({
"content": {
"key": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg",
"transaction_id": "S0meUniqueAndOpaqueString"
},
"type": "m.key.verification.key",
"sender": "@alice:example.org"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::KeyVerificationKey};
@ -583,7 +584,7 @@ mod tests {
#[test]
fn key_verification_mac() {
let source = r#"{
let source = json!({
"content": {
"keys": "2Wptgo4CwmLo/Y8B8qinxApKaCkBG2fjTWB7AbP5Uy+aIbygsSdLOFzvdDjww8zUVKCmI02eP9xtyJxc/cLiBA",
"mac": {
@ -593,7 +594,7 @@ mod tests {
},
"type": "m.key.verification.mac",
"sender": "@alice:example.org"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::KeyVerificationMac};
assert_eq!(event.content.transaction_id, "S0meUniqueAndOpaqueString");
@ -609,7 +610,7 @@ mod tests {
#[test]
fn key_verification_cancel() {
let source = r#"{
let source = json!({
"content": {
"code": "m.user",
"reason": "Some reason",
@ -617,7 +618,7 @@ mod tests {
},
"type": "m.key.verification.cancel",
"sender": "@alice:example.org"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::KeyVerificationCancel};
assert_eq!(event.content.transaction_id, "S0meUniqueAndOpaqueString");
@ -627,23 +628,26 @@ mod tests {
#[test]
fn key_verification_request() {
let source = r#"{
let source = json!({
"content": {
"from_device": "AliceDevice2",
"methods": [
"m.sas.v1"
],
"timestamp": 1559598944869,
"timestamp": 1_559_598_944_869_u64,
"transaction_id": "S0meUniqueAndOpaqueString"
},
"type": "m.key.verification.request",
"sender": "@alice:example.org"
}"#;
});
let event = deserialize! {source, AnyToDeviceEvent::KeyVerificationRequest};
assert_eq!(event.content.transaction_id, "S0meUniqueAndOpaqueString");
assert_eq!(event.content.from_device, "AliceDevice2");
assert_eq!(event.content.methods, &[VerificationMethod::MSasV1]);
assert_eq!(event.content.timestamp, UInt::new(1559_598944869).unwrap());
assert_eq!(
event.content.timestamp,
UInt::new(1_559_598_944_869).unwrap()
);
}
}