Add cargo fmt to ci using nightly

master
Devin Ragotzy 2021-05-12 13:20:52 -04:00
parent 2ef0c2959c
commit 5f09d091cb
22 changed files with 139 additions and 105 deletions

View File

@ -20,7 +20,7 @@ jobs:
- name: Install rust - name: Install rust
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
toolchain: stable toolchain: nightly
components: rustfmt components: rustfmt
profile: minimal profile: minimal
override: true override: true

View File

@ -73,18 +73,19 @@ async fn login_and_sync(
println!("logged in as {}", username); println!("logged in as {}", username);
// An initial sync to set up state and so our bot doesn't respond to old messages. // An initial sync to set up state and so our bot doesn't respond to old
// If the `StateStore` finds saved state in the location given the initial sync will // messages. If the `StateStore` finds saved state in the location given the
// be skipped in favor of loading state from the store // initial sync will be skipped in favor of loading state from the store
client.sync_once(SyncSettings::default()).await.unwrap(); client.sync_once(SyncSettings::default()).await.unwrap();
// add our CommandBot to be notified of incoming messages, we do this after the initial // add our CommandBot to be notified of incoming messages, we do this after the
// sync to avoid responding to messages before the bot was running. // initial sync to avoid responding to messages before the bot was running.
client.set_event_handler(Box::new(CommandBot::new())).await; client.set_event_handler(Box::new(CommandBot::new())).await;
// since we called `sync_once` before we entered our sync loop we must pass // since we called `sync_once` before we entered our sync loop we must pass
// that sync token to `sync` // that sync token to `sync`
let settings = SyncSettings::default().token(client.sync_token().await.unwrap()); let settings = SyncSettings::default().token(client.sync_token().await.unwrap());
// this keeps state from the server streaming in to CommandBot via the EventHandler trait // this keeps state from the server streaming in to CommandBot via the
// EventHandler trait
client.sync(settings).await; client.sync(settings).await;
Ok(()) Ok(())

View File

@ -40,7 +40,8 @@ impl Deref for Device {
impl Device { impl Device {
/// Start a interactive verification with this `Device` /// Start a interactive verification with this `Device`
/// ///
/// Returns a `Sas` object that represents the interactive verification flow. /// Returns a `Sas` object that represents the interactive verification
/// flow.
/// ///
/// # Example /// # Example
/// ///

View File

@ -76,12 +76,7 @@ impl Handler {
} }
pub(crate) async fn handle_sync(&self, response: &SyncResponse) { pub(crate) async fn handle_sync(&self, response: &SyncResponse) {
for event in response for event in response.account_data.events.iter().filter_map(|e| e.deserialize().ok()) {
.account_data
.events
.iter()
.filter_map(|e| e.deserialize().ok())
{
self.handle_account_data_event(&event).await; self.handle_account_data_event(&event).await;
} }
@ -95,8 +90,7 @@ impl Handler {
for event in for event in
room_info.account_data.events.iter().filter_map(|e| e.deserialize().ok()) room_info.account_data.events.iter().filter_map(|e| e.deserialize().ok())
{ {
self.handle_room_account_data_event(room.clone(), &event) self.handle_room_account_data_event(room.clone(), &event).await;
.await;
} }
for event in room_info.state.events.iter().filter_map(|e| e.deserialize().ok()) { for event in room_info.state.events.iter().filter_map(|e| e.deserialize().ok()) {
@ -116,8 +110,7 @@ impl Handler {
for event in for event in
room_info.account_data.events.iter().filter_map(|e| e.deserialize().ok()) room_info.account_data.events.iter().filter_map(|e| e.deserialize().ok())
{ {
self.handle_room_account_data_event(room.clone(), &event) self.handle_room_account_data_event(room.clone(), &event).await;
.await;
} }
for event in room_info.state.events.iter().filter_map(|e| e.deserialize().ok()) { for event in room_info.state.events.iter().filter_map(|e| e.deserialize().ok()) {

View File

@ -38,13 +38,16 @@ use crate::{
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait HttpSend: AsyncTraitDeps { pub trait HttpSend: AsyncTraitDeps {
/// The method abstracting sending request types and receiving response types. /// The method abstracting sending request types and receiving response
/// types.
/// ///
/// This is called by the client every time it wants to send anything to a homeserver. /// This is called by the client every time it wants to send anything to a
/// homeserver.
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `request` - The http request that has been converted from a ruma `Request`. /// * `request` - The http request that has been converted from a ruma
/// `Request`.
/// ///
/// * `request_config` - The config used for this request. /// * `request_config` - The config used for this request.
/// ///

View File

@ -17,19 +17,21 @@
//! //!
//! # Enabling logging //! # Enabling logging
//! //!
//! Users of the matrix-sdk crate can enable log output by depending on the `tracing-subscriber` //! Users of the matrix-sdk crate can enable log output by depending on the
//! crate and including the following line in their application (e.g. at the start of `main`): //! `tracing-subscriber` crate and including the following line in their
//! application (e.g. at the start of `main`):
//! //!
//! ```rust //! ```rust
//! tracing_subscriber::fmt::init(); //! tracing_subscriber::fmt::init();
//! ``` //! ```
//! //!
//! The log output is controlled via the `RUST_LOG` environment variable by setting it to one of //! The log output is controlled via the `RUST_LOG` environment variable by
//! the `error`, `warn`, `info`, `debug` or `trace` levels. The output is printed to stdout. //! setting it to one of the `error`, `warn`, `info`, `debug` or `trace` levels.
//! The output is printed to stdout.
//! //!
//! The `RUST_LOG` variable also supports a more advanced syntax for filtering log output more //! The `RUST_LOG` variable also supports a more advanced syntax for filtering
//! precisely, for instance with crate-level granularity. For more information on this, check out //! log output more precisely, for instance with crate-level granularity. For
//! the [tracing_subscriber //! more information on this, check out the [tracing_subscriber
//! documentation](https://tracing.rs/tracing_subscriber/filter/struct.envfilter). //! documentation](https://tracing.rs/tracing_subscriber/filter/struct.envfilter).
//! //!
//! # Crate Feature Flags //! # Crate Feature Flags
@ -44,10 +46,13 @@
//! * `markdown`: Support for sending markdown formatted messages. //! * `markdown`: Support for sending markdown formatted messages.
//! * `socks`: Enables SOCKS support in reqwest, the default HTTP client. //! * `socks`: Enables SOCKS support in reqwest, the default HTTP client.
//! * `sso_login`: Enables SSO login with a local http server. //! * `sso_login`: Enables SSO login with a local http server.
//! * `require_auth_for_profile_requests`: Whether to send the access token in the authentication //! * `require_auth_for_profile_requests`: Whether to send the access token in
//! header when calling endpoints that retrieve profile data. This matches the synapse //! the authentication
//! configuration `require_auth_for_profile_requests`. Enabled by default. //! header when calling endpoints that retrieve profile data. This matches the
//! * `appservice`: Enables low-level appservice functionality. For an high-level API there's the //! synapse configuration `require_auth_for_profile_requests`. Enabled by
//! default.
//! * `appservice`: Enables low-level appservice functionality. For an
//! high-level API there's the
//! `matrix-sdk-appservice` crate //! `matrix-sdk-appservice` crate
#![deny( #![deny(

View File

@ -12,7 +12,8 @@ use matrix_sdk_common::{
use crate::{BaseRoom, Client, Result, RoomMember}; use crate::{BaseRoom, Client, Result, RoomMember};
/// A struct containing methodes that are common for Joined, Invited and Left Rooms /// A struct containing methodes that are common for Joined, Invited and Left
/// Rooms
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Common { pub struct Common {
inner: BaseRoom, inner: BaseRoom,
@ -108,9 +109,9 @@ impl Common {
} }
} }
/// Sends a request to `/_matrix/client/r0/rooms/{room_id}/messages` and returns /// Sends a request to `/_matrix/client/r0/rooms/{room_id}/messages` and
/// a `get_message_events::Response` that contains a chunk of room and state events /// returns a `get_message_events::Response` that contains a chunk of
/// (`AnyRoomEvent` and `AnyStateEvent`). /// room and state events (`AnyRoomEvent` and `AnyStateEvent`).
/// ///
/// # Arguments /// # Arguments
/// ///
@ -235,9 +236,9 @@ impl Common {
/// Get all the joined members of this room. /// Get all the joined members of this room.
/// ///
/// *Note*: This method will not fetch the members from the homeserver if the /// *Note*: This method will not fetch the members from the homeserver if
/// member list isn't synchronized due to member lazy loading. Thus, members /// the member list isn't synchronized due to member lazy loading. Thus,
/// could be missing from the list. /// members could be missing from the list.
/// ///
/// Use [joined_members()](#method.joined_members) if you want to ensure to /// Use [joined_members()](#method.joined_members) if you want to ensure to
/// always get the full member list. /// always get the full member list.
@ -271,9 +272,9 @@ impl Common {
/// Get a specific member of this room. /// Get a specific member of this room.
/// ///
/// *Note*: This method will not fetch the members from the homeserver if the /// *Note*: This method will not fetch the members from the homeserver if
/// member list isn't synchronized due to member lazy loading. Thus, members /// the member list isn't synchronized due to member lazy loading. Thus,
/// could be missing. /// members could be missing.
/// ///
/// Use [get_member()](#method.get_member) if you want to ensure to always /// Use [get_member()](#method.get_member) if you want to ensure to always
/// have the full member list to chose from. /// have the full member list to chose from.
@ -290,7 +291,8 @@ impl Common {
.map(|member| RoomMember::new(self.client.clone(), member))) .map(|member| RoomMember::new(self.client.clone(), member)))
} }
/// Get all members for this room, includes invited, joined and left members. /// Get all members for this room, includes invited, joined and left
/// members.
/// ///
/// *Note*: This method will fetch the members from the homeserver if the /// *Note*: This method will fetch the members from the homeserver if the
/// member list isn't synchronized due to member lazy loading. Because of /// member list isn't synchronized due to member lazy loading. Because of
@ -303,11 +305,12 @@ impl Common {
self.members_no_sync().await self.members_no_sync().await
} }
/// Get all members for this room, includes invited, joined and left members. /// Get all members for this room, includes invited, joined and left
/// members.
/// ///
/// *Note*: This method will not fetch the members from the homeserver if the /// *Note*: This method will not fetch the members from the homeserver if
/// member list isn't synchronized due to member lazy loading. Thus, members /// the member list isn't synchronized due to member lazy loading. Thus,
/// could be missing. /// members could be missing.
/// ///
/// Use [members()](#method.members) if you want to ensure to always get /// Use [members()](#method.members) if you want to ensure to always get
/// the full member list. /// the full member list.

View File

@ -4,15 +4,17 @@ use crate::{room::Common, BaseRoom, Client, Result, RoomType};
/// A room in the invited state. /// A room in the invited state.
/// ///
/// This struct contains all methodes specific to a `Room` with type `RoomType::Invited`. /// This struct contains all methodes specific to a `Room` with type
/// Operations may fail once the underlaying `Room` changes `RoomType`. /// `RoomType::Invited`. Operations may fail once the underlaying `Room` changes
/// `RoomType`.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Invited { pub struct Invited {
pub(crate) inner: Common, pub(crate) inner: Common,
} }
impl Invited { impl Invited {
/// Create a new `room::Invited` if the underlaying `Room` has type `RoomType::Invited`. /// Create a new `room::Invited` if the underlaying `Room` has type
/// `RoomType::Invited`.
/// ///
/// # Arguments /// # Arguments
/// * `client` - The client used to make requests. /// * `client` - The client used to make requests.

View File

@ -6,15 +6,17 @@ use crate::{room::Common, BaseRoom, Client, Result, RoomType};
/// A room in the left state. /// A room in the left state.
/// ///
/// This struct contains all methodes specific to a `Room` with type `RoomType::Left`. /// This struct contains all methodes specific to a `Room` with type
/// Operations may fail once the underlaying `Room` changes `RoomType`. /// `RoomType::Left`. Operations may fail once the underlaying `Room` changes
/// `RoomType`.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Left { pub struct Left {
pub(crate) inner: Common, pub(crate) inner: Common,
} }
impl Left { impl Left {
/// Create a new `room::Left` if the underlaying `Room` has type `RoomType::Left`. /// Create a new `room::Left` if the underlaying `Room` has type
/// `RoomType::Left`.
/// ///
/// # Arguments /// # Arguments
/// * `client` - The client used to make requests. /// * `client` - The client used to make requests.

View File

@ -14,12 +14,14 @@
//! Matrix [Application Service] library //! Matrix [Application Service] library
//! //!
//! The appservice crate aims to provide a batteries-included experience. That means that we //! The appservice crate aims to provide a batteries-included experience. That
//! * ship with functionality to configure your webserver crate or simply run the webserver for you //! means that we
//! * ship with functionality to configure your webserver crate or simply run
//! the webserver for you
//! * receive and validate requests from the homeserver correctly //! * receive and validate requests from the homeserver correctly
//! * allow calling the homeserver with proper virtual user identity assertion //! * allow calling the homeserver with proper virtual user identity assertion
//! * have the goal to have a consistent room state available by leveraging the stores that the //! * have the goal to have a consistent room state available by leveraging the
//! matrix-sdk provides //! stores that the matrix-sdk provides
//! //!
//! # Quickstart //! # Quickstart
//! //!
@ -173,8 +175,10 @@ impl Appservice {
/// # Arguments /// # Arguments
/// ///
/// * `homeserver_url` - The homeserver that the client should connect to. /// * `homeserver_url` - The homeserver that the client should connect to.
/// * `server_name` - The server name to use when constructing user ids from the localpart. /// * `server_name` - The server name to use when constructing user ids from
/// * `registration` - The [Appservice Registration] to use when interacting with the homserver. /// the localpart.
/// * `registration` - The [Appservice Registration] to use when interacting
/// with the homserver.
/// ///
/// [Appservice Registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration /// [Appservice Registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration
pub async fn new( pub async fn new(
@ -205,8 +209,9 @@ impl Appservice {
/// Get `Client` for the given `localpart` /// Get `Client` for the given `localpart`
/// ///
/// If the `localpart` is covered by the `namespaces` in the [registration] all requests to the /// If the `localpart` is covered by the `namespaces` in the [registration]
/// homeserver will [assert the identity] to the according virtual user. /// all requests to the homeserver will [assert the identity] to the
/// according virtual user.
/// ///
/// [registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration /// [registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration
/// [assert the identity]: /// [assert the identity]:
@ -287,7 +292,8 @@ impl Appservice {
/// Get the host and port from the registration URL /// Get the host and port from the registration URL
/// ///
/// If no port is found it falls back to scheme defaults: 80 for http and 443 for https /// If no port is found it falls back to scheme defaults: 80 for http and
/// 443 for https
pub fn get_host_and_port_from_registration(&self) -> Result<(Host, Port)> { pub fn get_host_and_port_from_registration(&self) -> Result<(Host, Port)> {
let uri = Uri::try_from(&self.registration.url)?; let uri = Uri::try_from(&self.registration.url)?;
@ -311,9 +317,11 @@ impl Appservice {
actix::get_scope().data(self.clone()) actix::get_scope().data(self.clone())
} }
/// Convenience method that runs an http server depending on the selected server feature /// Convenience method that runs an http server depending on the selected
/// server feature
/// ///
/// This is a blocking call that tries to listen on the provided host and port /// This is a blocking call that tries to listen on the provided host and
/// port
pub async fn run(&self, host: impl AsRef<str>, port: impl Into<u16>) -> Result<()> { pub async fn run(&self, host: impl AsRef<str>, port: impl Into<u16>) -> Result<()> {
#[cfg(feature = "actix")] #[cfg(feature = "actix")]
{ {

View File

@ -107,8 +107,8 @@ mod actix {
let resp = test::call_service(&app, req).await; let resp = test::call_service(&app, req).await;
// TODO: this should actually return a 401 but is 500 because something in the extractor // TODO: this should actually return a 401 but is 500 because something in the
// fails // extractor fails
assert_eq!(resp.status(), 500); assert_eq!(resp.status(), 500);
} }
} }

View File

@ -75,9 +75,11 @@ pub struct EncryptedEvent {
#[derive(Debug, Serialize, Deserialize, PartialEq)] #[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum KdfInfo { pub enum KdfInfo {
Pbkdf2ToChaCha20Poly1305 { Pbkdf2ToChaCha20Poly1305 {
/// The number of PBKDF rounds that were used when deriving the store key. /// The number of PBKDF rounds that were used when deriving the store
/// key.
rounds: u32, rounds: u32,
/// The salt that was used when the passphrase was expanded into a store key. /// The salt that was used when the passphrase was expanded into a store
/// key.
kdf_salt: Vec<u8>, kdf_salt: Vec<u8>,
}, },
} }

View File

@ -6,8 +6,9 @@ use std::{fs::File, os::raw::c_int, path::Path};
use criterion::profiler::Profiler; use criterion::profiler::Profiler;
use pprof::ProfilerGuard; use pprof::ProfilerGuard;
/// Small custom profiler that can be used with Criterion to create a flamegraph for benchmarks. /// Small custom profiler that can be used with Criterion to create a flamegraph
/// Also see [the Criterion documentation on this][custom-profiler]. /// for benchmarks. Also see [the Criterion documentation on
/// this][custom-profiler].
/// ///
/// ## Example on how to enable the custom profiler: /// ## Example on how to enable the custom profiler:
/// ///
@ -30,12 +31,12 @@ use pprof::ProfilerGuard;
/// } /// }
/// ``` /// ```
/// ///
/// The neat thing about this is that it will sample _only_ the benchmark, and not other stuff like /// The neat thing about this is that it will sample _only_ the benchmark, and
/// the setup process. /// not other stuff like the setup process.
/// ///
/// Further, it will only kick in if `--profile-time <time>` is passed to the benchmark binary. /// Further, it will only kick in if `--profile-time <time>` is passed to the
/// A flamegraph will be created for each individual benchmark in its report directory under /// benchmark binary. A flamegraph will be created for each individual benchmark
/// `profile/flamegraph.svg`. /// in its report directory under `profile/flamegraph.svg`.
/// ///
/// [custom-profiler]: https://bheisler.github.io/criterion.rs/book/user_guide/profiling.html#implementing-in-process-profiling-hooks /// [custom-profiler]: https://bheisler.github.io/criterion.rs/book/user_guide/profiling.html#implementing-in-process-profiling-hooks
pub struct FlamegraphProfiler<'a> { pub struct FlamegraphProfiler<'a> {

View File

@ -29,10 +29,10 @@
//! //!
//! ## User //! ## User
//! //!
//! Cross-signing capable devices will upload 3 additional (master, self-signing, //! Cross-signing capable devices will upload 3 additional (master,
//! user-signing) public keys which represent the user identity owning all the //! self-signing, user-signing) public keys which represent the user identity
//! devices. This is represented in two ways, as a `UserIdentity` for other //! owning all the devices. This is represented in two ways, as a `UserIdentity`
//! users and as `OwnUserIdentity` for our own user. //! for other users and as `OwnUserIdentity` for our own user.
//! //!
//! This is done because the server will only give us access to 2 of the 3 //! This is done because the server will only give us access to 2 of the 3
//! additional public keys for other users, while it will give us access to all //! additional public keys for other users, while it will give us access to all

View File

@ -382,7 +382,8 @@ pub struct PickledInboundGroupSession {
pub history_visibility: Option<HistoryVisibility>, pub history_visibility: Option<HistoryVisibility>,
} }
/// The typed representation of a base64 encoded string of the GroupSession pickle. /// The typed representation of a base64 encoded string of the GroupSession
/// pickle.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboundGroupSessionPickle(String); pub struct InboundGroupSessionPickle(String);

View File

@ -102,8 +102,9 @@ impl Session {
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `recipient_device` - The device for which this message is going to be encrypted, this /// * `recipient_device` - The device for which this message is going to be
/// needs to be the device that was used to create this session with. /// encrypted, this needs to be the device that was used to create this
/// session with.
/// ///
/// * `event_type` - The type of the event. /// * `event_type` - The type of the event.
/// ///
@ -258,7 +259,8 @@ pub struct PickledSession {
pub last_use_time: Instant, pub last_use_time: Instant,
} }
/// The typed representation of a base64 encoded string of the Olm Session pickle. /// The typed representation of a base64 encoded string of the Olm Session
/// pickle.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionPickle(String); pub struct SessionPickle(String);

View File

@ -46,7 +46,8 @@ impl Utility {
/// ///
/// * `key_id` - The id of the key that signed the JSON object. /// * `key_id` - The id of the key that signed the JSON object.
/// ///
/// * `signing_key` - The public ed25519 key which was used to sign the JSON object. /// * `signing_key` - The public ed25519 key which was used to sign the JSON
/// object.
/// ///
/// * `json` - The JSON object that should be verified. /// * `json` - The JSON object that should be verified.
pub(crate) fn verify_json( pub(crate) fn verify_json(

View File

@ -38,14 +38,16 @@ use matrix_sdk_common::{
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
/// Customized version of `ruma_client_api::r0::to_device::send_event_to_device::Request`, using a /// Customized version of
/// `ruma_client_api::r0::to_device::send_event_to_device::Request`, using a
/// UUID for the transaction ID. /// UUID for the transaction ID.
#[derive(Clone, Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ToDeviceRequest { pub struct ToDeviceRequest {
/// Type of event being sent to each device. /// Type of event being sent to each device.
pub event_type: EventType, pub event_type: EventType,
/// A request identifier unique to the access token used to send the request. /// A request identifier unique to the access token used to send the
/// request.
pub txn_id: Uuid, pub txn_id: Uuid,
/// A map of users to devices to a content for a message event to be /// A map of users to devices to a content for a message event to be
@ -79,15 +81,18 @@ impl ToDeviceRequest {
pub struct UploadSigningKeysRequest { pub struct UploadSigningKeysRequest {
/// The user's master key. /// The user's master key.
pub master_key: Option<CrossSigningKey>, pub master_key: Option<CrossSigningKey>,
/// The user's self-signing key. Must be signed with the accompanied master, or by the /// The user's self-signing key. Must be signed with the accompanied master,
/// user's most recently uploaded master key if no master key is included in the request. /// or by the user's most recently uploaded master key if no master key
/// is included in the request.
pub self_signing_key: Option<CrossSigningKey>, pub self_signing_key: Option<CrossSigningKey>,
/// The user's user-signing key. Must be signed with the accompanied master, or by the /// The user's user-signing key. Must be signed with the accompanied master,
/// user's most recently uploaded master key if no master key is included in the request. /// or by the user's most recently uploaded master key if no master key
/// is included in the request.
pub user_signing_key: Option<CrossSigningKey>, pub user_signing_key: Option<CrossSigningKey>,
} }
/// Customized version of `ruma_client_api::r0::keys::get_keys::Request`, without any references. /// Customized version of `ruma_client_api::r0::keys::get_keys::Request`,
/// without any references.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct KeysQueryRequest { pub struct KeysQueryRequest {
/// The time (in milliseconds) to wait when downloading keys from remote /// The time (in milliseconds) to wait when downloading keys from remote

View File

@ -42,16 +42,17 @@ pub enum EventsJson {
Typing, Typing,
} }
/// The `EventBuilder` struct can be used to easily generate valid sync responses for testing. /// The `EventBuilder` struct can be used to easily generate valid sync
/// These can be then fed into either `Client` or `Room`. /// responses for testing. These can be then fed into either `Client` or `Room`.
/// ///
/// It supports generated a number of canned events, such as a member entering a room, his power /// It supports generated a number of canned events, such as a member entering a
/// level and display name changing and similar. It also supports insertion of custom events in the /// room, his power level and display name changing and similar. It also
/// form of `EventsJson` values. /// supports insertion of custom events in the form of `EventsJson` values.
/// ///
/// **Important** You *must* use the *same* builder when sending multiple sync responses to /// **Important** You *must* use the *same* builder when sending multiple sync
/// a single client. Otherwise, the subsequent responses will be *ignored* by the client because /// responses to a single client. Otherwise, the subsequent responses will be
/// the `next_batch` sync token will not be rotated properly. /// *ignored* by the client because the `next_batch` sync token will not be
/// rotated properly.
/// ///
/// # Example usage /// # Example usage
/// ///
@ -92,7 +93,8 @@ pub struct EventBuilder {
ephemeral: Vec<AnySyncEphemeralRoomEvent>, ephemeral: Vec<AnySyncEphemeralRoomEvent>,
/// The account data events that determine the state of a `Room`. /// The account data events that determine the state of a `Room`.
account_data: Vec<AnyGlobalAccountDataEvent>, account_data: Vec<AnyGlobalAccountDataEvent>,
/// Internal counter to enable the `prev_batch` and `next_batch` of each sync response to vary. /// Internal counter to enable the `prev_batch` and `next_batch` of each
/// sync response to vary.
batch_counter: i64, batch_counter: i64,
} }
@ -216,7 +218,8 @@ impl EventBuilder {
pub fn build_json_sync_response(&mut self) -> JsonValue { pub fn build_json_sync_response(&mut self) -> JsonValue {
let main_room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost"); let main_room_id = room_id!("!SVkFJHzfwvuaIEawgC:localhost");
// First time building a sync response, so initialize the `prev_batch` to a default one. // First time building a sync response, so initialize the `prev_batch` to a
// default one.
let prev_batch = self.generate_sync_token(); let prev_batch = self.generate_sync_token();
self.batch_counter += 1; self.batch_counter += 1;
let next_batch = self.generate_sync_token(); let next_batch = self.generate_sync_token();

View File

@ -1,8 +1,8 @@
//! Test data for the matrix-sdk crates. //! Test data for the matrix-sdk crates.
//! //!
//! Exporting each const allows all the test data to have a single source of truth. //! Exporting each const allows all the test data to have a single source of
//! When running `cargo publish` no external folders are allowed so all the //! truth. When running `cargo publish` no external folders are allowed so all
//! test data needs to be contained within this crate. //! the test data needs to be contained within this crate.
use lazy_static::lazy_static; use lazy_static::lazy_static;
use serde_json::{json, Value as JsonValue}; use serde_json::{json, Value as JsonValue};

View File

@ -1,6 +1,7 @@
use proc_macro::TokenStream; use proc_macro::TokenStream;
/// Attribute to use `wasm_bindgen_test` for wasm32 targets and `tokio::test` for everything else /// Attribute to use `wasm_bindgen_test` for wasm32 targets and `tokio::test`
/// for everything else
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn async_test(_attr: TokenStream, item: TokenStream) -> TokenStream { pub fn async_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
let attrs = r#" let attrs = r#"