|
| 1 | +//! Utilities for recording and replaying RPC responses in tests. |
| 2 | +//! |
| 3 | +//! This module provides infrastructure for running integration tests offline |
| 4 | +//! by recording JSON-RPC interactions with real nodes and replaying them |
| 5 | +//! through a mock HTTP server. |
| 6 | +//! |
| 7 | +//! ## Modes |
| 8 | +//! |
| 9 | +//! - **Recording mode** (`RECORD_RPC_RECORDS=1`): Tests run against a real RPC node through a |
| 10 | +//! recording proxy that saves all request/response pairs to JSON files. |
| 11 | +//! |
| 12 | +//! - **Replay mode** (record files present): Tests start a mock HTTP server that serves |
| 13 | +//! pre-recorded responses, enabling fully offline execution (used in CI). |
| 14 | +//! |
| 15 | +//! - **Live mode** (default): Tests use a real RPC node directly (existing behavior). |
| 16 | +
|
| 17 | +use std::fs; |
| 18 | +use std::path::{Path, PathBuf}; |
| 19 | + |
| 20 | +use apollo_infra_utils::compile_time_cargo_manifest_dir; |
| 21 | +use serde::{Deserialize, Serialize}; |
| 22 | + |
| 23 | +/// A recorded JSON-RPC request-response pair. |
| 24 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 25 | +pub struct RpcInteraction { |
| 26 | + /// The JSON-RPC method name (e.g., "starknet_getStorageAt"). |
| 27 | + pub method: String, |
| 28 | + /// The JSON-RPC parameters. |
| 29 | + pub params: serde_json::Value, |
| 30 | + /// The full JSON-RPC response body. |
| 31 | + pub response: serde_json::Value, |
| 32 | +} |
| 33 | + |
| 34 | +/// Collection of recorded RPC interactions for a test. |
| 35 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 36 | +pub struct RpcRecords { |
| 37 | + /// All recorded interactions, in order. |
| 38 | + pub interactions: Vec<RpcInteraction>, |
| 39 | +} |
| 40 | + |
| 41 | +impl RpcRecords { |
| 42 | + /// Loads recorded RPC interactions from a JSON file. |
| 43 | + pub fn load(path: &Path) -> Self { |
| 44 | + let content = fs::read_to_string(path) |
| 45 | + .unwrap_or_else(|e| panic!("Failed to read records from {path:?}: {e}")); |
| 46 | + serde_json::from_str(&content) |
| 47 | + .unwrap_or_else(|e| panic!("Failed to parse records from {path:?}: {e}")) |
| 48 | + } |
| 49 | + |
| 50 | + /// Saves recorded RPC interactions to a JSON file. |
| 51 | + pub fn save(&self, path: &Path) { |
| 52 | + let dir = path.parent().expect("Invalid record path"); |
| 53 | + fs::create_dir_all(dir) |
| 54 | + .unwrap_or_else(|e| panic!("Failed to create directory {dir:?}: {e}")); |
| 55 | + let content = |
| 56 | + serde_json::to_string_pretty(self).expect("Failed to serialize RPC records"); |
| 57 | + fs::write(path, content) |
| 58 | + .unwrap_or_else(|e| panic!("Failed to write records to {path:?}: {e}")); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/// Creates a mockito server pre-configured with all recorded RPC interactions. |
| 63 | +/// |
| 64 | +/// The server matches JSON-RPC requests by their `method` and `params` fields, |
| 65 | +/// returning the recorded response for each matching request. |
| 66 | +/// The `id` and `jsonrpc` version fields are ignored during matching so that |
| 67 | +/// the mock works with both `RpcStateReader` and `JsonRpcClient` regardless |
| 68 | +/// of their internal request formatting. |
| 69 | +pub async fn setup_mock_rpc_server(records: &RpcRecords) -> mockito::ServerGuard { |
| 70 | + let mut server = mockito::Server::new_async().await; |
| 71 | + for interaction in &records.interactions { |
| 72 | + let request_matcher = serde_json::json!({ |
| 73 | + "method": interaction.method, |
| 74 | + "params": interaction.params, |
| 75 | + }); |
| 76 | + server |
| 77 | + .mock("POST", "/") |
| 78 | + .match_body(mockito::Matcher::PartialJson(request_matcher)) |
| 79 | + .with_status(200) |
| 80 | + .with_header("content-type", "application/json") |
| 81 | + .with_body(serde_json::to_string(&interaction.response).unwrap()) |
| 82 | + .create_async() |
| 83 | + .await; |
| 84 | + } |
| 85 | + server |
| 86 | +} |
| 87 | + |
| 88 | +// ================================================================================================ |
| 89 | +// Path helpers |
| 90 | +// ================================================================================================ |
| 91 | + |
| 92 | +/// Returns the path to the RPC records directory for the starknet_os_runner crate. |
| 93 | +pub fn records_dir() -> PathBuf { |
| 94 | + PathBuf::from(compile_time_cargo_manifest_dir!()).join("resources").join("fixtures") |
| 95 | +} |
| 96 | + |
| 97 | +/// Returns the path to a specific test's record file. |
| 98 | +pub fn record_path(test_name: &str) -> PathBuf { |
| 99 | + records_dir().join(format!("{test_name}.json")) |
| 100 | +} |
| 101 | + |
| 102 | +/// Returns true if a record file exists for the given test. |
| 103 | +pub fn records_exist(test_name: &str) -> bool { |
| 104 | + record_path(test_name).exists() |
| 105 | +} |
0 commit comments