jsonrpsee_test_utils/lib.rs
1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! Shared test helpers for JSONRPC v2.
28//!
29//! Vendored from [jsonrpsee](https://github.com/paritytech/jsonrpsee), Copyright (c) 2019-2021
30//! Parity Technologies (UK) Ltd., licensed under the MIT License (see
31//! `crates/rpc/jsonrpsee/LICENSE`).
32
33#![recursion_limit = "256"]
34
35use std::{future::Future, time::Duration};
36
37use tokio::time::{timeout, Timeout};
38
39pub mod helpers;
40pub mod mocks;
41
42/// Helper extension trait which allows to limit execution time for the futures.
43/// It is helpful in tests to ensure that no future will ever get stuck forever.
44pub trait TimeoutFutureExt<T>: Future<Output = T> + Sized {
45 /// Returns a reasonable value that can be used as a future timeout with a certain
46 /// degree of confidence that timeout won't be triggered by the test specifics.
47 fn default_timeout() -> Duration {
48 // If some future wasn't done in 60 seconds, it's either a poorly written test
49 // or (most likely) a bug related to some future never actually being completed.
50 const TIMEOUT_SECONDS: u64 = 60;
51 Duration::from_secs(TIMEOUT_SECONDS)
52 }
53
54 /// Adds a fixed timeout to the future.
55 fn with_default_timeout(self) -> Timeout<Self> {
56 self.with_timeout(Self::default_timeout())
57 }
58
59 /// Adds a custom timeout to the future.
60 fn with_timeout(self, timeout_value: Duration) -> Timeout<Self> {
61 timeout(timeout_value, self)
62 }
63}
64
65impl<T, U> TimeoutFutureExt<T> for U where U: Future<Output = T> + Sized {}