#![allow(dead_code)]
use clap::Parser;
use mega_evme::common::RpcArgs;
use wiremock::{matchers, Mock, MockServer, ResponseTemplate};
pub(crate) struct MockRpcServer {
server: MockServer,
}
impl MockRpcServer {
pub(crate) async fn start() -> Self {
Self { server: MockServer::start().await }
}
pub(crate) fn uri(&self) -> String {
self.server.uri()
}
pub(crate) async fn respond_status_n_times(&self, status: u16, n: u64, priority: u8) {
Mock::given(matchers::method("POST"))
.respond_with(ResponseTemplate::new(status))
.up_to_n_times(n)
.with_priority(priority)
.mount(&self.server)
.await;
}
pub(crate) async fn respond_status_always(&self, status: u16) {
Mock::given(matchers::method("POST"))
.respond_with(ResponseTemplate::new(status))
.mount(&self.server)
.await;
}
pub(crate) async fn respond_jsonrpc_result(&self, hex_result: &str, priority: u8) {
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 0,
"result": hex_result,
});
Mock::given(matchers::method("POST"))
.respond_with(ResponseTemplate::new(200).set_body_json(body))
.with_priority(priority)
.mount(&self.server)
.await;
}
pub(crate) async fn respond_jsonrpc_error(&self, code: i32, message: &str, priority: u8) {
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 0,
"error": { "code": code, "message": message },
});
Mock::given(matchers::method("POST"))
.respond_with(ResponseTemplate::new(200).set_body_json(body))
.with_priority(priority)
.mount(&self.server)
.await;
}
pub(crate) async fn respond_eth_chain_id(&self, chain_id: u64, priority: u8) {
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 0,
"result": format!("0x{:x}", chain_id),
});
Mock::given(matchers::method("POST"))
.and(matchers::body_partial_json(serde_json::json!({
"method": "eth_chainId"
})))
.respond_with(ResponseTemplate::new(200).set_body_json(body))
.with_priority(priority)
.mount(&self.server)
.await;
}
pub(crate) async fn received_request_count(&self) -> usize {
self.server.received_requests().await.expect("received_requests").len()
}
}
pub(crate) fn test_rpc_args(url: &str, max_retries: Option<u32>) -> RpcArgs {
let mut argv: Vec<String> = vec![
"mega-evme".into(),
"--rpc".into(),
url.into(),
"--rpc.cache-size".into(),
"0".into(),
"--rpc.backoff-ms".into(),
"1".into(),
"--rpc.rate-limit".into(),
"660".into(),
];
if let Some(n) = max_retries {
argv.push("--rpc.max-retries".into());
argv.push(n.to_string());
}
RpcArgs::parse_from(argv)
}
pub(crate) fn test_rpc_args_cached(
url: &str,
cache_dir: &std::path::Path,
max_retries: Option<u32>,
) -> RpcArgs {
let mut argv: Vec<String> = vec![
"mega-evme".into(),
"--rpc".into(),
url.into(),
"--rpc.cache-size".into(),
"256".into(),
"--rpc.cache-dir".into(),
cache_dir.to_str().expect("cache_dir utf-8").to_string(),
"--rpc.backoff-ms".into(),
"1".into(),
"--rpc.rate-limit".into(),
"660".into(),
];
if let Some(n) = max_retries {
argv.push("--rpc.max-retries".into());
argv.push(n.to_string());
}
RpcArgs::parse_from(argv)
}