Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Improve tests coverage #825

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ gloo-timers = { version = "0.3.0", features = ["futures"] }
[dev-dependencies]
anyhow = "1.0.89"
alloy-primitives = { version = "0.8.5", default-features = false }
blockifier = { git = "https://github.com/sergey-melnychuk/sequencer.git", tag = "beerus-wasm-2024-09-22", version = "=0.8.0-rc.2", features = ["testing"] }
chrono = "0.4.38"
katana-core = { git = "https://github.com/dojoengine/dojo", tag = "v1.0.0-alpha.9" }
katana-executor = { git = "https://github.com/dojoengine/dojo", tag = "v1.0.0-alpha.9" }
Expand All @@ -79,6 +80,7 @@ katana-rpc-api = { git = "https://github.com/dojoengine/dojo", tag = "v1.0.0-alp
scarb = { git = "https://github.com/software-mansion/scarb/", tag = "v2.8.3" }
semver = { version = "1", features = ["serde"] }
wiremock = "0.6.2"
tempfile = "3.13.0"

[patch.crates-io]
starknet-core = { git = "https://github.com/kariy/starknet-rs", branch = "dojo-patch" }
Expand Down
153 changes: 153 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use wiremock::{
matchers::body_partial_json, Mock, MockServer, ResponseTemplate,
};
Expand Down Expand Up @@ -335,6 +336,41 @@
result.unwrap_err().to_string(),
"rpc error: computer says no"
);

drop(server);

let server = mock(&[
(
serde_json::json!({
"method": "eth_chainId"
}),
serde_json::json!({
"id": 0,
"jsonrpc": "2.0",
"result": "0xcafebabe"
}),
),
(
serde_json::json!({
"method": "starknet_chainId"
}),
serde_json::json!({
"id": 0,
"jsonrpc": "2.0",
"error": serde_json::json!({
"object": "error"
})
}),
),
])
.await;

let rpc = format!("http://{}/", server.address());
let result = check_chain_id(&rpc, &rpc).await;
assert_eq!(
result.unwrap_err().to_string(),
"rpc error: {\"object\":\"error\"}"
);
}

#[tokio::test]
Expand All @@ -353,4 +389,121 @@
assert!(response.is_err());
assert!(response.unwrap_err().to_string().contains("poll_secs"));
}

#[tokio::test]
async fn test_default_poll_seconds_returns_default_value() {
assert_eq!(default_poll_secs(), DEFAULT_POLL_SECS);
}

#[tokio::test]
async fn test_default_rpc_addr() {
assert_eq!(
default_rpc_addr().to_string(),
String::from("0.0.0.0:3030")
);
}

#[tokio::test]
async fn test_default_data_dir() {
assert_eq!(default_data_dir(), String::from("tmp"));
}

#[tokio::test]
async fn test_server_config_from_env() {
// lets make a clean state for our test
std::env::remove_var("POLL_SECS");
std::env::remove_var("RPC_ADDR");
std::env::remove_var("ETHEREUM_RPC");
std::env::remove_var("STARKNET_RPC");
std::env::remove_var("DATA_DIR");

let config = ServerConfig::from_env();
assert!(config.is_err());
assert!(config.unwrap_err().to_string().contains("ETHEREUM_RPC env var missing"));

std::env::set_var("ETHEREUM_RPC", "ethereum_rpc");

let config = ServerConfig::from_env();
assert!(config.is_err());
assert!(config.unwrap_err().to_string().contains("STARKNET_RPC env var missing"));

std::env::set_var("STARKNET_RPC", "starknet_rpc");

let config = ServerConfig::from_env().unwrap();
assert_eq!(config.client.ethereum_rpc, "ethereum_rpc");
assert_eq!(config.client.starknet_rpc, "starknet_rpc");

// test default values
assert_eq!(config.client.data_dir, default_data_dir());
assert_eq!(config.poll_secs, DEFAULT_POLL_SECS);
assert_eq!(config.rpc_addr, default_rpc_addr());


std::env::set_var("DATA_DIR", "data_dir");
let config = ServerConfig::from_env().unwrap();
assert_eq!(config.client.data_dir, "data_dir");


std::env::set_var("POLL_SECS", "invalid_data");
assert!(ServerConfig::from_env().is_err());

std::env::set_var("POLL_SECS", "10");
let config = ServerConfig::from_env().unwrap();
assert_eq!(config.poll_secs, 10);


std::env::set_var("RPC_ADDR", "invalid_data");
assert!(ServerConfig::from_env().is_err());

std::env::set_var("RPC_ADDR", "0.0.0.0:3000");
let config = ServerConfig::from_env().unwrap();
assert_eq!(config.rpc_addr, "0.0.0.0:3000".parse().unwrap());
}


#[tokio::test]
async fn test_server_config_from_file_returns_error_for_non_exisiting_path() {

Check warning on line 465 in src/config.rs

View workflow job for this annotation

GitHub Actions / typos

"exisiting" should be "existing".
assert!(!std::path::Path::new("/beerus/does_not_exists").exists());
assert!(ServerConfig::from_file("/beerus/does_not_exists").is_err());
}

#[tokio::test]
async fn test_server_config_from_file() {
let mut ntmpfile = tempfile::NamedTempFile::new().unwrap();
write!(ntmpfile,r#"
ethereum_rpc = "ethereum_rpc"
starknet_rpc = "starknet_rpc"
data_dir = "tmp"
poll_secs = 5
rpc_addr = "127.0.0.1:3030"
"#).unwrap();

let config = ServerConfig::from_file(ntmpfile.path().to_str().unwrap()).unwrap();
assert_eq!(config.client.ethereum_rpc, "ethereum_rpc");
assert_eq!(config.client.starknet_rpc, "starknet_rpc");
assert_eq!(config.client.data_dir, "tmp");
assert_eq!(config.poll_secs, 5);
assert_eq!(config.rpc_addr, SocketAddr::from(([127, 0, 0, 1], 3030)));
}

#[tokio::test]
async fn test_check_data_dir() {
assert!(check_data_dir(&"does_not_exists").is_err());

let tmp_dir = tempfile::tempdir().unwrap();
let tmp_path = tmp_dir.path().to_owned();
let mut perms = tmp_path.metadata().unwrap().permissions();
perms.set_readonly(true);
std::fs::set_permissions(&tmp_path, perms).unwrap();

let check = check_data_dir(&tmp_path);
assert!(check.is_err());
assert!(check.unwrap_err().to_string().contains("path is readonly"));

let mut perms = tmp_path.metadata().unwrap().permissions();
perms.set_readonly(false);
std::fs::set_permissions(&tmp_path, perms).unwrap();
let check = check_data_dir(&tmp_path);
assert!(check.is_ok());
}
}
31 changes: 31 additions & 0 deletions src/exe/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,34 @@ impl From<Error> for iamgroot::jsonrpc::Error {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_conversion_to_iamgroot_jsonrpc_error() {
let error = Error::Custom("test");
let iamgroot_jsonrpc_error: iamgroot::jsonrpc::Error = error.into();
assert_eq!(iamgroot_jsonrpc_error, iamgroot::jsonrpc::Error {code: 500, message: "test".to_string()});


let error = Error::IamGroot(iamgroot::jsonrpc::Error {code: 500, message: "test".to_string()});
let iamgroot_jsonrpc_error: iamgroot::jsonrpc::Error = error.into();

assert_eq!(
iamgroot::jsonrpc::Error {code: 500, message: "test".to_string()},
iamgroot_jsonrpc_error,
);
}
#[test]
fn test_conversion_to_blockifier_state_errors_state_error() {
let error = Error::Custom("test");
let blockifier_error: blockifier::state::errors::StateError = error.into();

assert_eq!(
blockifier_error.to_string(),
blockifier::state::errors::StateError::StateReadError("Custom(\"test\")".into()).to_string()
);
}
}
102 changes: 102 additions & 0 deletions src/exe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,3 +318,105 @@ impl<T: gen::client::blocking::HttpClient> BlockifierState for StateProxy<T> {
tracing::info!(?class_hash, pcs.len = pcs.len(), "add_visited_pcs");
}
}

#[cfg(test)]
mod tests {

use blockifier::execution::contract_class::ContractClassV1;
use starknet_api::core::PatriciaKey;

use super::*;
struct MockHttpClient {
response: std::result::Result<iamgroot::jsonrpc::Response, iamgroot::jsonrpc::Error>,
}

impl MockHttpClient {
fn new(response: std::result::Result<iamgroot::jsonrpc::Response, iamgroot::jsonrpc::Error>) -> Self {
Self {
response,
}
}
}

impl Default for MockHttpClient {
fn default() -> Self {
Self::new(Ok(iamgroot::jsonrpc::Response::result(serde_json::Value::default())))
}
}

impl gen::client::blocking::HttpClient for MockHttpClient {
fn post(
&self,
_url: &str,
_request: &iamgroot::jsonrpc::Request,
) -> std::result::Result<iamgroot::jsonrpc::Response, iamgroot::jsonrpc::Error> {
self.response.clone()
}
}

fn state_proxy_with_response (
response: std::result::Result<iamgroot::jsonrpc::Response, iamgroot::jsonrpc::Error>,
proxy: Option<StateProxy<MockHttpClient>>
) -> StateProxy<MockHttpClient> {
let state = if let Some(test) = proxy {
test.state.clone()
} else {
State {
block_number: 0,
block_hash: gen::Felt::try_new("0x0").unwrap(),
root: gen::Felt::try_new("0x0").unwrap(),
}
};
StateProxy {
state,
client: gen::client::blocking::Client::new("test", MockHttpClient::new(response)),
}
}

#[test]
fn test_exe() {
let p = StateProxy {
client: gen::client::blocking::Client::new("test", MockHttpClient::default()),
state: State {
block_number: 0,
block_hash: gen::Felt::try_new("0x0").unwrap(),
root: gen::Felt::try_new("0x0").unwrap(),
}
};

let mut proxy = state_proxy_with_response(
Ok(iamgroot::jsonrpc::Response::result(serde_json::Value::String("0x0".into()))),
Some(p)
);

let response = proxy.get_storage_at(
ContractAddress(PatriciaKey::try_from(starknet_crypto::Felt::ZERO).unwrap()),
StarknetStorageKey(PatriciaKey::try_from(starknet_crypto::Felt::ZERO).unwrap()),
);

let nonce = proxy.get_nonce_at(
ContractAddress(PatriciaKey::try_from(starknet_crypto::Felt::ZERO).unwrap()),
).unwrap();

assert_eq!(nonce.0,
starknet_crypto::Felt::from_hex("0x0").unwrap(),
);

proxy.set_storage_at(
ContractAddress(PatriciaKey::try_from(starknet_crypto::Felt::ZERO).unwrap()),
StarknetStorageKey(PatriciaKey::try_from(starknet_crypto::Felt::ZERO).unwrap()),
starknet_crypto::Felt::ZERO,
).unwrap();
proxy.increment_nonce(
ContractAddress(PatriciaKey::try_from(starknet_crypto::Felt::ZERO).unwrap()),
).unwrap();
proxy.set_class_hash_at(
ContractAddress(PatriciaKey::try_from(starknet_crypto::Felt::ZERO).unwrap()),
ClassHash(starknet_crypto::Felt::ZERO),
).unwrap();
proxy.set_contract_class(ClassHash(starknet_crypto::Felt::ZERO), ContractClass::V1(ContractClassV1::empty_for_testing())).unwrap();
proxy.set_compiled_class_hash(ClassHash(starknet_crypto::Felt::ZERO), CompiledClassHash(starknet_crypto::Felt::ZERO)).unwrap();
proxy.add_visited_pcs(ClassHash(starknet_crypto::Felt::ZERO), &HashSet::new());

}
}
Loading
Loading