referrerpolicy=no-referrer-when-downgrade

sc_rpc/
testing.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// 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.
10
11// 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.
15
16// 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/>.
18
19//! Testing utils used by the RPC tests.
20
21use std::{future::Future, sync::Arc};
22
23use jsonrpsee::Extensions;
24use sc_rpc_api::DenyUnsafe;
25
26/// 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);
31
32impl TokioTestExecutor {
33	/// Create a new instance of `Self`.
34	pub fn new() -> Self {
35		Self(tokio::runtime::Handle::current())
36	}
37}
38
39impl Default for TokioTestExecutor {
40	fn default() -> Self {
41		Self::new()
42	}
43}
44
45impl sp_core::traits::SpawnNamed for TokioTestExecutor {
46	fn spawn_blocking(
47		&self,
48		_name: &'static str,
49		_group: Option<&'static str>,
50		future: futures::future::BoxFuture<'static, ()>,
51	) {
52		let handle = self.0.clone();
53		self.0.spawn_blocking(move || {
54			handle.block_on(future);
55		});
56	}
57	fn spawn(
58		&self,
59		_name: &'static str,
60		_group: Option<&'static str>,
61		future: futures::future::BoxFuture<'static, ()>,
62	) {
63		self.0.spawn(future);
64	}
65}
66
67/// Executor for testing.
68pub fn test_executor() -> Arc<TokioTestExecutor> {
69	Arc::new(TokioTestExecutor::default())
70}
71
72/// 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}
76
77/// Helper to create an extension that denies unsafe calls.
78pub fn deny_unsafe() -> Extensions {
79	let mut ext = Extensions::new();
80	ext.insert(DenyUnsafe::Yes);
81	ext
82}
83
84/// Helper to create an extension that allows unsafe calls.
85pub fn allow_unsafe() -> Extensions {
86	let mut ext = Extensions::new();
87	ext.insert(DenyUnsafe::No);
88	ext
89}