1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
56// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
1011// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
1516// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
1819//! Testing utils used by the RPC tests.
2021use std::{future::Future, sync::Arc};
2223use jsonrpsee::Extensions;
24use sc_rpc_api::DenyUnsafe;
2526/// A task executor that can be used for running RPC tests.
27///
28/// Warning: the tokio runtime must be initialized before calling this.
29#[derive(Clone)]
30pub struct TokioTestExecutor(tokio::runtime::Handle);
3132impl TokioTestExecutor {
33/// Create a new instance of `Self`.
34pub fn new() -> Self {
35Self(tokio::runtime::Handle::current())
36 }
37}
3839impl Default for TokioTestExecutor {
40fn default() -> Self {
41Self::new()
42 }
43}
4445impl sp_core::traits::SpawnNamed for TokioTestExecutor {
46fn spawn_blocking(
47&self,
48 _name: &'static str,
49 _group: Option<&'static str>,
50 future: futures::future::BoxFuture<'static, ()>,
51 ) {
52let handle = self.0.clone();
53self.0.spawn_blocking(move || {
54 handle.block_on(future);
55 });
56 }
57fn spawn(
58&self,
59 _name: &'static str,
60 _group: Option<&'static str>,
61 future: futures::future::BoxFuture<'static, ()>,
62 ) {
63self.0.spawn(future);
64 }
65}
6667/// Executor for testing.
68pub fn test_executor() -> Arc<TokioTestExecutor> {
69 Arc::new(TokioTestExecutor::default())
70}
7172/// Wrap a future in a timeout a little more concisely
73pub fn timeout_secs<I, F: Future<Output = I>>(s: u64, f: F) -> tokio::time::Timeout<F> {
74 tokio::time::timeout(std::time::Duration::from_secs(s), f)
75}
7677/// Helper to create an extension that denies unsafe calls.
78pub fn deny_unsafe() -> Extensions {
79let mut ext = Extensions::new();
80 ext.insert(DenyUnsafe::Yes);
81 ext
82}
8384/// Helper to create an extension that allows unsafe calls.
85pub fn allow_unsafe() -> Extensions {
86let mut ext = Extensions::new();
87 ext.insert(DenyUnsafe::No);
88 ext
89}