client-api: Split some test assertions

This commit is contained in:
Kévin Commaille 2022-06-04 23:08:18 +02:00 committed by Kévin Commaille
parent 63ec3a43aa
commit c1d10b1061
10 changed files with 205 additions and 257 deletions

View File

@ -57,8 +57,6 @@ pub mod v3 {
#[cfg(all(test, any(feature = "client", feature = "server")))]
mod tests {
use assert_matches::assert_matches;
#[cfg(feature = "server")]
#[test]
fn deserialize_request() {
@ -66,17 +64,15 @@ pub mod v3 {
use super::IncomingRequest;
let req = assert_matches!(
IncomingRequest::try_from_http_request(
http::Request::builder()
.method(http::Method::POST)
.uri("https://matrix.org/_matrix/client/r0/user/@foo:bar.com/filter")
.body(b"{}" as &[u8])
.unwrap(),
&["@foo:bar.com"]
),
Ok(req) => req
);
let req = IncomingRequest::try_from_http_request(
http::Request::builder()
.method(http::Method::POST)
.uri("https://matrix.org/_matrix/client/r0/user/@foo:bar.com/filter")
.body(b"{}" as &[u8])
.unwrap(),
&["@foo:bar.com"],
)
.unwrap();
assert_eq!(req.user_id, "@foo:bar.com");
assert!(req.filter.is_empty());
@ -92,15 +88,14 @@ pub mod v3 {
use crate::filter::FilterDefinition;
assert_matches!(
super::Request::new(user_id!("@foo:bar.com"), FilterDefinition::default())
.try_into_http_request::<Vec<u8>>(
"https://matrix.org",
SendAccessToken::IfRequired("tok"),
&[MatrixVersion::V1_1]
),
Ok(res) if res.body() == b"{}"
);
let req = super::Request::new(user_id!("@foo:bar.com"), FilterDefinition::default())
.try_into_http_request::<Vec<u8>>(
"https://matrix.org",
SendAccessToken::IfRequired("tok"),
&[MatrixVersion::V1_1],
)
.unwrap();
assert_eq!(req.body(), b"{}");
}
}
}

View File

@ -56,19 +56,16 @@ pub mod v3 {
#[cfg(all(test, any(feature = "client", feature = "server")))]
mod tests {
use assert_matches::assert_matches;
#[cfg(feature = "client")]
#[test]
fn deserialize_response() {
use ruma_common::api::IncomingResponse;
assert_matches!(
super::Response::try_from_http_response(
http::Response::builder().body(b"{}" as &[u8]).unwrap(),
),
Ok(super::Response { filter }) if filter.is_empty()
);
let res = super::Response::try_from_http_response(
http::Response::builder().body(b"{}" as &[u8]).unwrap(),
)
.unwrap();
assert!(res.filter.is_empty());
}
#[cfg(feature = "server")]
@ -78,11 +75,10 @@ pub mod v3 {
use crate::filter::IncomingFilterDefinition;
assert_matches!(
super::Response::new(IncomingFilterDefinition::default())
.try_into_http_response::<Vec<u8>>(),
Ok(res) if res.body() == b"{}"
);
let res = super::Response::new(IncomingFilterDefinition::default())
.try_into_http_response::<Vec<u8>>()
.unwrap();
assert_eq!(res.body(), b"{}");
}
}
}

View File

@ -102,7 +102,6 @@ pub mod v3 {
#[cfg(all(test, feature = "server"))]
mod tests {
use assert_matches::assert_matches;
use ruma_common::api::IncomingRequest as _;
use super::{IncomingRequest, MembershipEventFilter};
@ -123,17 +122,13 @@ pub mod v3 {
let req = IncomingRequest::try_from_http_request(
http::Request::builder().uri(uri).body(&[] as &[u8]).unwrap(),
&["!dummy:example.org"],
);
)
.unwrap();
assert_matches!(
req,
Ok(IncomingRequest {
room_id,
at: Some(at),
membership: None,
not_membership: Some(MembershipEventFilter::Leave),
}) if room_id == "!dummy:example.org" && at == "1026"
);
assert_eq!(req.room_id, "!dummy:example.org");
assert_eq!(req.at.as_deref(), Some("1026"));
assert_eq!(req.membership, None);
assert_eq!(req.not_membership, Some(MembershipEventFilter::Leave));
}
}
}

View File

@ -79,7 +79,7 @@ pub mod v3 {
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use ruma_common::{thirdparty::Medium, user_id};
use ruma_common::thirdparty::Medium;
use serde_json::{from_value as from_json_value, json};
use super::IncomingInvitationRecipient;
@ -91,11 +91,11 @@ pub mod v3 {
)
.unwrap();
assert_matches!(
let user_id = assert_matches!(
incoming,
IncomingInvitationRecipient::UserId { user_id }
if user_id == user_id!("@carl:example.org")
IncomingInvitationRecipient::UserId { user_id } => user_id
);
assert_eq!(user_id, "@carl:example.org");
}
#[test]
@ -108,10 +108,10 @@ pub mod v3 {
}))
.unwrap();
let third_party_id = match incoming {
IncomingInvitationRecipient::UserId { .. } => panic!("wrong variant"),
IncomingInvitationRecipient::ThirdPartyId(id) => id,
};
let third_party_id = assert_matches!(
incoming,
IncomingInvitationRecipient::ThirdPartyId(id) => id
);
assert_eq!(third_party_id.id_server, "example.org");
assert_eq!(third_party_id.id_access_token, "abcdefghijklmnop");

View File

@ -80,36 +80,34 @@ pub mod v3 {
#[cfg(test)]
mod test {
use assert_matches::assert_matches;
use ruma_common::mxc_uri;
use serde_json::{from_value as from_json_value, json};
use super::RoomMember;
#[test]
fn deserialize_room_member() {
assert_matches!(
from_json_value::<RoomMember>(json!({
"display_name": "alice",
"avatar_url": "mxc://localhost/wefuiwegh8742w",
})).unwrap(),
RoomMember {
display_name: Some(display_name),
avatar_url: Some(avatar_url),
} if display_name == "alice"
&& avatar_url == "mxc://localhost/wefuiwegh8742w"
let member = from_json_value::<RoomMember>(json!({
"display_name": "alice",
"avatar_url": "mxc://localhost/wefuiwegh8742w",
}))
.unwrap();
assert_eq!(member.display_name.as_deref(), Some("alice"));
assert_eq!(
member.avatar_url.as_deref(),
Some(mxc_uri!("mxc://localhost/wefuiwegh8742w"))
);
#[cfg(feature = "compat")]
assert_matches!(
from_json_value::<RoomMember>(json!({
{
let member = from_json_value::<RoomMember>(json!({
"display_name": "alice",
"avatar_url": "",
})).unwrap(),
RoomMember {
display_name: Some(display_name),
avatar_url: None,
} if display_name == "alice"
);
}))
.unwrap();
assert_eq!(member.display_name.as_deref(), Some("alice"));
assert_eq!(member.avatar_url, None);
}
}
}
}

View File

@ -84,36 +84,38 @@ pub mod v3 {
#[cfg(all(test, feature = "server"))]
mod tests {
use assert_matches::assert_matches;
use ruma_common::api::IncomingRequest as _;
use super::IncomingRequest;
#[test]
fn deserialize_unset_request() {
assert_matches!(
IncomingRequest::try_from_http_request(
http::Request::builder()
.method("PUT")
.uri("https://bar.org/_matrix/client/r0/profile/@foo:bar.org/avatar_url")
.body(&[] as &[u8]).unwrap(),
&["@foo:bar.org"],
).unwrap(),
IncomingRequest { user_id, avatar_url: None, .. } if user_id == "@foo:bar.org"
);
let req = IncomingRequest::try_from_http_request(
http::Request::builder()
.method("PUT")
.uri("https://bar.org/_matrix/client/r0/profile/@foo:bar.org/avatar_url")
.body(&[] as &[u8])
.unwrap(),
&["@foo:bar.org"],
)
.unwrap();
assert_eq!(req.user_id, "@foo:bar.org");
assert_eq!(req.avatar_url, None);
#[cfg(feature = "compat")]
assert_matches!(
IncomingRequest::try_from_http_request(
{
let req = IncomingRequest::try_from_http_request(
http::Request::builder()
.method("PUT")
.uri("https://bar.org/_matrix/client/r0/profile/@foo:bar.org/avatar_url")
.body(serde_json::to_vec(&serde_json::json!({ "avatar_url": "" })).unwrap())
.unwrap(),
&["@foo:bar.org"],
).unwrap(),
IncomingRequest { user_id, avatar_url: None, .. } if user_id == "@foo:bar.org"
);
)
.unwrap();
assert_eq!(req.user_id, "@foo:bar.org");
assert_eq!(req.avatar_url, None);
}
}
}
}

View File

@ -286,12 +286,14 @@ pub mod v3 {
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use ruma_common::mxc_uri;
use serde::{Deserialize, Serialize};
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use serde_json::{
from_value as from_json_value, json, to_value as to_json_value, Value as JsonValue,
};
use super::{
CustomLoginType, IdentityProvider, IdentityProviderBrand, LoginType, PasswordLoginType,
SsoLoginType, TokenLoginType,
IdentityProvider, IdentityProviderBrand, LoginType, SsoLoginType, TokenLoginType,
};
#[derive(Debug, Deserialize, Serialize)]
@ -301,43 +303,40 @@ pub mod v3 {
#[test]
fn deserialize_password_login_type() {
assert_matches!(
from_json_value::<Wrapper>(json!({
"flows": [
{ "type": "m.login.password" }
],
})),
Ok(Wrapper { flows })
if flows.len() == 1
&& matches!(flows[0], LoginType::Password(PasswordLoginType {}))
);
let wrapper = from_json_value::<Wrapper>(json!({
"flows": [
{ "type": "m.login.password" }
],
}))
.unwrap();
assert_eq!(wrapper.flows.len(), 1);
assert_matches!(wrapper.flows[0], LoginType::Password(_));
}
#[test]
fn deserialize_custom_login_type() {
assert_matches!(
from_json_value::<Wrapper>(json!({
"flows": [
{
"type": "io.ruma.custom",
"color": "green",
}
],
})),
Ok(Wrapper { flows })
if flows.len() == 1
&& matches!(
&flows[0],
LoginType::_Custom(CustomLoginType { type_, data })
if type_ == "io.ruma.custom"
&& data == json!({ "color": "green" }).as_object().unwrap()
)
let wrapper = from_json_value::<Wrapper>(json!({
"flows": [
{
"type": "io.ruma.custom",
"color": "green",
}
],
}))
.unwrap();
assert_eq!(wrapper.flows.len(), 1);
let custom = assert_matches!(
&wrapper.flows[0],
LoginType::_Custom(custom) => custom
);
assert_eq!(custom.type_, "io.ruma.custom");
assert_eq!(custom.data.len(), 1);
assert_eq!(custom.data.get("color"), Some(&JsonValue::from("green")));
}
#[test]
fn deserialize_sso_login_type() {
let mut wrapper = from_json_value::<Wrapper>(json!({
let wrapper = from_json_value::<Wrapper>(json!({
"flows": [
{
"type": "m.login.sso",
@ -357,39 +356,26 @@ pub mod v3 {
],
}))
.unwrap();
assert_eq!(wrapper.flows.len(), 1);
let flow = &wrapper.flows[0];
let flow = wrapper.flows.pop();
assert_matches!(wrapper.flows.as_slice(), []);
let mut identity_providers = match flow {
Some(LoginType::Sso(SsoLoginType { identity_providers })) => identity_providers,
_ => panic!("unexpected enum variant: {flow:?}"),
};
let provider = identity_providers.pop();
assert_matches!(
provider,
Some(IdentityProvider {
id,
name,
icon: None,
brand: None,
}) if id == "custom"
&& name == "Custom"
let identity_providers = assert_matches!(
flow,
LoginType::Sso(SsoLoginType { identity_providers }) => identity_providers
);
assert_eq!(identity_providers.len(), 2);
let provider = identity_providers.pop();
assert_matches!(
provider,
Some(IdentityProvider {
id,
name,
icon: Some(icon),
brand: Some(IdentityProviderBrand::GitLab),
}) if id == "oidc-gitlab"
&& name == "GitLab"
&& icon == "mxc://localhost/gitlab-icon"
);
let provider = &identity_providers[0];
assert_eq!(provider.id, "oidc-gitlab");
assert_eq!(provider.name, "GitLab");
assert_eq!(provider.icon.as_deref(), Some(mxc_uri!("mxc://localhost/gitlab-icon")));
assert_eq!(provider.brand, Some(IdentityProviderBrand::GitLab));
let provider = &identity_providers[1];
assert_eq!(provider.id, "custom");
assert_eq!(provider.name, "Custom");
assert_eq!(provider.icon, None);
assert_eq!(provider.brand, None);
}
#[test]

View File

@ -323,12 +323,12 @@ pub mod v3 {
use assert_matches::assert_matches;
use serde_json::{from_value as from_json_value, json};
use super::{IncomingLoginInfo, IncomingPassword, IncomingToken};
use super::{IncomingLoginInfo, IncomingToken};
use crate::uiaa::IncomingUserIdentifier;
#[test]
fn deserialize_login_type() {
assert_matches!(
let login = assert_matches!(
from_json_value(json!({
"type": "m.login.password",
"identifier": {
@ -338,19 +338,24 @@ pub mod v3 {
"password": "ilovebananas"
}))
.unwrap(),
IncomingLoginInfo::Password(IncomingPassword { identifier: IncomingUserIdentifier::UserIdOrLocalpart(user), password })
if user == "cheeky_monkey" && password == "ilovebananas"
IncomingLoginInfo::Password(login) => login
);
let user = assert_matches!(
login.identifier,
IncomingUserIdentifier::UserIdOrLocalpart(user) => user
);
assert_eq!(user, "cheeky_monkey");
assert_eq!(login.password, "ilovebananas");
assert_matches!(
let token = assert_matches!(
from_json_value(json!({
"type": "m.login.token",
"token": "1234567890abcdef"
}))
.unwrap(),
IncomingLoginInfo::Token(IncomingToken { token })
if token == "1234567890abcdef"
IncomingLoginInfo::Token(IncomingToken { token }) => token
);
assert_eq!(token, "1234567890abcdef");
}
#[test]

View File

@ -612,7 +612,6 @@ pub mod v3 {
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use assign::assign;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
@ -624,14 +623,14 @@ pub mod v3 {
let timeline_serialized = json!({ "limited": true });
assert_eq!(to_json_value(timeline).unwrap(), timeline_serialized);
let timeline_deserialized = from_json_value(timeline_serialized);
assert_matches!(timeline_deserialized, Ok(Timeline { limited: true, .. }));
let timeline_deserialized = from_json_value::<Timeline>(timeline_serialized).unwrap();
assert!(timeline_deserialized.limited);
let timeline_default = Timeline::default();
assert_eq!(to_json_value(timeline_default).unwrap(), json!({}));
let timeline_default_deserialized = from_json_value(json!({}));
assert_matches!(timeline_default_deserialized, Ok(Timeline { limited: false, .. }));
let timeline_default_deserialized = from_json_value::<Timeline>(json!({})).unwrap();
assert!(!timeline_default_deserialized.limited);
}
}
@ -702,8 +701,9 @@ pub mod v3 {
)
.unwrap();
assert_matches!(req.filter, Some(IncomingFilter::FilterId(id)) if id == "myfilter");
assert_eq!(req.since, Some("myts".into()));
let id = assert_matches!(req.filter, Some(IncomingFilter::FilterId(id)) => id);
assert_eq!(id, "myfilter");
assert_eq!(req.since.as_deref(), Some("myts"));
assert!(!req.full_state);
assert_eq!(req.set_presence, PresenceState::Offline);
assert_eq!(req.timeout, Some(Duration::from_millis(5000)));
@ -750,7 +750,8 @@ pub mod v3 {
)
.unwrap();
assert_matches!(req.filter, Some(IncomingFilter::FilterId(id)) if id == "EOKFFmdZYF");
let id = assert_matches!(req.filter, Some(IncomingFilter::FilterId(id)) => id);
assert_eq!(id, "EOKFFmdZYF");
assert_eq!(req.since, None);
assert!(!req.full_state);
assert_eq!(req.set_presence, PresenceState::Online);

View File

@ -1,7 +1,7 @@
use assert_matches::assert_matches;
use assign::assign;
use ruma_client_api::{
error::{ErrorBody, ErrorKind},
error::ErrorKind,
uiaa::{
self, AuthData, AuthFlow, AuthType, IncomingAuthData, IncomingUserIdentifier, UiaaInfo,
UiaaResponse,
@ -15,15 +15,15 @@ use serde_json::{
#[test]
fn deserialize_user_identifier() {
assert_matches!(
let id = assert_matches!(
from_json_value(json!({
"type": "m.id.user",
"user": "cheeky_monkey"
}))
.unwrap(),
IncomingUserIdentifier::UserIdOrLocalpart(id)
if id == "cheeky_monkey"
IncomingUserIdentifier::UserIdOrLocalpart(id) => id
);
assert_eq!(id, "cheeky_monkey");
}
#[test]
@ -32,9 +32,9 @@ fn serialize_auth_data_registration_token() {
assign!(uiaa::RegistrationToken::new("mytoken"), { session: Some("session") }),
);
assert_matches!(
to_json_value(auth_data),
Ok(val) if val == json!({
assert_eq!(
to_json_value(auth_data).unwrap(),
json!({
"type": "m.login.registration_token",
"token": "mytoken",
"session": "session",
@ -50,13 +50,12 @@ fn deserialize_auth_data_registration_token() {
"session": "session",
});
assert_matches!(
let data = assert_matches!(
from_json_value(json),
Ok(IncomingAuthData::RegistrationToken(
uiaa::IncomingRegistrationToken { token, session: Some(session), .. },
))
if token == "mytoken" && session == "session"
Ok(IncomingAuthData::RegistrationToken(data)) => data
);
assert_eq!(data.token, "mytoken");
assert_eq!(data.session.as_deref(), Some("session"));
}
#[test]
@ -70,13 +69,11 @@ fn serialize_auth_data_fallback() {
fn deserialize_auth_data_fallback() {
let json = json!({ "session": "opaque_session_id" });
assert_matches!(
let data = assert_matches!(
from_json_value(json).unwrap(),
IncomingAuthData::FallbackAcknowledgement(
uiaa::IncomingFallbackAcknowledgement { session, .. },
)
if session == "opaque_session_id"
IncomingAuthData::FallbackAcknowledgement(data) => data
);
assert_eq!(data.session, "opaque_session_id");
}
#[test]
@ -126,32 +123,22 @@ fn deserialize_uiaa_info() {
"session": "xxxxxx"
});
assert_matches!(
from_json_value::<UiaaInfo>(json).unwrap(),
UiaaInfo {
auth_error: Some(ErrorBody {
kind: ErrorKind::Forbidden,
message: error_message,
}),
completed,
flows,
params,
session: Some(session),
..
} if error_message == "Invalid password"
&& completed == vec![AuthType::ReCaptcha]
&& matches!(
flows.as_slice(),
[f1, f2]
if f1.stages == vec![AuthType::Password]
&& f2.stages == vec![AuthType::EmailIdentity, AuthType::Msisdn]
)
&& from_json_str::<JsonValue>(params.get()).unwrap() == json!({
"example.type.baz": {
"example_key": "foobar"
}
})
&& session == "xxxxxx"
let info = from_json_value::<UiaaInfo>(json).unwrap();
assert_eq!(info.completed, vec![AuthType::ReCaptcha]);
assert_eq!(info.flows.len(), 2);
assert_eq!(info.flows[0].stages, vec![AuthType::Password]);
assert_eq!(info.flows[1].stages, vec![AuthType::EmailIdentity, AuthType::Msisdn]);
assert_eq!(info.session.as_deref(), Some("xxxxxx"));
let auth_error = info.auth_error.unwrap();
assert_eq!(auth_error.kind, ErrorKind::Forbidden);
assert_eq!(auth_error.message, "Invalid password");
assert_eq!(
from_json_str::<JsonValue>(info.params.get()).unwrap(),
json!({
"example.type.baz": {
"example_key": "foobar"
}
})
);
}
@ -170,24 +157,19 @@ fn try_uiaa_response_into_http_response() {
let uiaa_response =
UiaaResponse::AuthResponse(uiaa_info).try_into_http_response::<Vec<u8>>().unwrap();
assert_matches!(
from_json_slice::<UiaaInfo>(uiaa_response.body()).unwrap(),
UiaaInfo {
flows,
completed,
params,
session: None,
auth_error: None,
..
} if matches!(
flows.as_slice(),
[flow] if flow.stages == vec![AuthType::Password, AuthType::Dummy]
) && completed == vec![AuthType::ReCaptcha]
&& from_json_str::<JsonValue>(params.get()).unwrap() == json!({
"example.type.baz": {
"example_key": "foobar"
}
})
let info = from_json_slice::<UiaaInfo>(uiaa_response.body()).unwrap();
assert_eq!(info.flows.len(), 1);
assert_eq!(info.flows[0].stages, vec![AuthType::Password, AuthType::Dummy]);
assert_eq!(info.completed, vec![AuthType::ReCaptcha]);
assert_eq!(info.session, None);
assert_matches!(info.auth_error, None);
assert_eq!(
from_json_str::<JsonValue>(info.params.get()).unwrap(),
json!({
"example.type.baz": {
"example_key": "foobar"
}
})
);
assert_eq!(uiaa_response.status(), http::status::StatusCode::UNAUTHORIZED);
}
@ -220,36 +202,24 @@ fn try_uiaa_response_from_http_response() {
.body(json.as_bytes())
.unwrap();
let parsed_uiaa_info = match UiaaResponse::try_from_http_response(http_response).unwrap() {
UiaaResponse::AuthResponse(uiaa_info) => uiaa_info,
_ => panic!("Expected UiaaResponse::AuthResponse"),
};
assert_matches!(
parsed_uiaa_info,
UiaaInfo {
auth_error: Some(ErrorBody {
kind: ErrorKind::Forbidden,
message: error_message,
}),
completed,
flows,
params,
session: Some(session),
..
} if error_message == "Invalid password"
&& completed == vec![AuthType::ReCaptcha]
&& matches!(
flows.as_slice(),
[f1, f2]
if f1.stages == vec![AuthType::Password]
&& f2.stages == vec![AuthType::EmailIdentity, AuthType::Msisdn]
)
&& from_json_str::<JsonValue>(params.get()).unwrap() == json!({
"example.type.baz": {
"example_key": "foobar"
}
})
&& session == "xxxxxx"
let info = assert_matches!(
UiaaResponse::try_from_http_response(http_response),
Ok(UiaaResponse::AuthResponse(info)) => info
);
assert_eq!(info.completed, vec![AuthType::ReCaptcha]);
assert_eq!(info.flows.len(), 2);
assert_eq!(info.flows[0].stages, vec![AuthType::Password]);
assert_eq!(info.flows[1].stages, vec![AuthType::EmailIdentity, AuthType::Msisdn]);
assert_eq!(info.session.as_deref(), Some("xxxxxx"));
let auth_error = info.auth_error.unwrap();
assert_eq!(auth_error.kind, ErrorKind::Forbidden);
assert_eq!(auth_error.message, "Invalid password");
assert_eq!(
from_json_str::<JsonValue>(info.params.get()).unwrap(),
json!({
"example.type.baz": {
"example_key": "foobar"
}
})
);
}