Skip to content

Commit

Permalink
Merge branch 'main' into test/specversion
Browse files Browse the repository at this point in the history
  • Loading branch information
Trantorian1 committed Jan 12, 2024
2 parents 3159aee + 272a25b commit ebb89af
Show file tree
Hide file tree
Showing 14 changed files with 321 additions and 58 deletions.
22 changes: 20 additions & 2 deletions Cargo.lock

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

5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[workspace]
members = [ "macros",
"macros",
members = [
"macro_utils",
"macro",
"unit_tests",
]
default-members = ["unit_tests"]
Expand Down
3 changes: 2 additions & 1 deletion macros/Cargo.toml → macro/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "macros"
name = "macro"
version = "0.1.0"
edition = "2021"

Expand All @@ -9,3 +9,4 @@ proc-macro = true
[dependencies]
quote = "1.0.35"
syn = "2.0.48"
macro_utils = { path = "../macro_utils/" }
80 changes: 80 additions & 0 deletions macro/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use macro_utils::{extract_u64_from_expr, get_block_number};
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, parse_quote, ItemFn, MetaNameValue, Path, Token,
};

#[proc_macro_attribute]
pub fn logging(_: TokenStream, input: TokenStream) -> TokenStream {
let mut input = parse_macro_input!(input as ItemFn);

input.block.stmts.insert(
0,
syn::parse(
quote! {
env_logger::builder().is_test(true).try_init().err();
}
.into(),
)
.unwrap(),
);

input.into_token_stream().into()
}

struct ArgsRequire {
pub block_min: u64,
pub block_max: u64,
pub err: Result<(), Path>,
}

impl Parse for ArgsRequire {
fn parse(input: ParseStream) -> syn::Result<Self> {
let args = input.parse_terminated(MetaNameValue::parse, Token![,])?;

let mut parsed_params = Self {
block_min: 0,
block_max: 0,
err: Ok(()),
};

for arg in args {
match arg.path.get_ident() {
Some(ident) => match ident.to_string().as_str() {
"block_min" => {
parsed_params.block_min = extract_u64_from_expr(arg.value).unwrap_or(0);
}
"block_max" => {
parsed_params.block_max =
extract_u64_from_expr(arg.value).unwrap_or(u64::MAX);
}
_ => {
parsed_params.err = Err(arg.path);
}
},
None => todo!(),
}
}

Ok(parsed_params)
}
}

#[proc_macro_attribute]
pub fn require(args: TokenStream, item: TokenStream) -> TokenStream {
let bn = get_block_number();
let args_parsed = parse_macro_input!(args as ArgsRequire);

if bn >= args_parsed.block_min && bn <= args_parsed.block_max {
item
} else {
let mut func = parse_macro_input!(item as ItemFn);
func.attrs.push(
parse_quote!(#[ignore = "Deoxys node does not meet required specs to run this test"]),
);

quote!(#func).into()
}
}
18 changes: 18 additions & 0 deletions macro_utils/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "macro_utils"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.79"
serde = "1.0.195"
serde_json = "1.0.111"
starknet = { git = "https://github.com/xJonathanLEI/starknet-rs.git", rev = "64ebc36", default-features = false }
starknet-core = { git = "https://github.com/xJonathanLEI/starknet-rs.git", rev = "64ebc36", default-features = false }
starknet-providers = { git = "https://github.com/xJonathanLEI/starknet-rs.git", rev = "64ebc36", default-features = false }
url = "2.5.0"
syn = "2.0.48"
quote = "1.0.35"
tokio = { version = "1", features = ["full"] }
50 changes: 50 additions & 0 deletions macro_utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use serde::Deserialize;
use starknet_providers::{jsonrpc::HttpTransport, JsonRpcClient, Provider};
use std::{fs::File, io::Read};
use syn::{Expr, Lit};
use tokio::runtime;
use url::Url;

#[derive(PartialEq, Debug, Deserialize)]
pub struct TestConfig {
pub pathfinder: String,
pub deoxys: String,
}

impl TestConfig {
pub fn new(path: &str) -> anyhow::Result<Self> {
let mut file = File::open(path)?;
let mut content = String::new();

file.read_to_string(&mut content)?;

let config: TestConfig = serde_json::from_str(&content)
.expect("Could not deserialize test at {path} into Config");

Ok(config)
}
}

pub fn get_block_number() -> u64 {
let config =
TestConfig::new("./secret.json").expect("'./secret.json' must contain correct node urls");
let deoxys = JsonRpcClient::new(HttpTransport::new(
Url::parse(&config.deoxys).expect("Error parsing Deoxys node url"),
));

let rt = runtime::Runtime::new().unwrap();

rt.block_on(async { deoxys.block_number().await.unwrap() })
}

pub fn extract_u64_from_expr(expr: Expr) -> Result<u64, String> {
match expr {
Expr::Lit(expr_lit) => match expr_lit.lit {
Lit::Int(lit_int) => lit_int
.base10_parse::<u64>()
.map_err(|_| "Failed to parse integer".to_string()),
_ => Err("Not an integer literal".to_string()),
},
_ => Err("Not a literal expression".to_string()),
}
}
21 changes: 0 additions & 21 deletions macros/src/lib.rs

This file was deleted.

9 changes: 5 additions & 4 deletions unit_tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,19 @@ edition = "2021"
[dependencies]
anyhow = "1.0.79"
rstest = "0.18.2"
serde = "1.0.194"
serde_json = "1.0.110"
tokio = { version = "1", features = ["full"] }
url = "2.5.0"
starknet = { git = "https://github.com/xJonathanLEI/starknet-rs.git", rev = "64ebc36", default-features = false }
starknet-core = { git = "https://github.com/xJonathanLEI/starknet-rs.git", rev = "64ebc36", default-features = false }
starknet-providers = { git = "https://github.com/xJonathanLEI/starknet-rs.git", rev = "64ebc36", default-features = false }
env_logger = "0.10.1"
macro_utils = { path = "../macro_utils/" }
url = "2.5.0"

[dev-dependencies]
jsonrpsee = { version = "0.21.0", features = ["client"] }
tokio = { version = "1", features = ["full", "test-util"] }
flate2 = "1.0.28"
log = "0.4.20"
macros = { path = "../macros/" }
macro = { path = "../macro/" }
serde = "1.0.195"
serde_json = "1.0.111"
2 changes: 1 addition & 1 deletion unit_tests/src/fixtures.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::collections::HashMap;

use macro_utils::TestConfig;
use rstest::fixture;
use starknet_providers::{jsonrpc::HttpTransport, JsonRpcClient};
use url::Url;

use crate::constants::*;
use crate::map;
use crate::TestConfig;

#[fixture]
pub fn config() -> TestConfig {
Expand Down
22 changes: 0 additions & 22 deletions unit_tests/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
#![feature(assert_matches)]

use std::{fs::File, io::Read};

use constants::*;
use serde::Deserialize;
use starknet_core::{
types::{BroadcastedInvokeTransaction, BroadcastedTransaction, FieldElement},
utils::get_selector_from_name,
Expand All @@ -13,25 +10,6 @@ pub mod constants;
pub mod fixtures;
pub mod macros;

#[derive(PartialEq, Debug, Deserialize)]
pub struct TestConfig {
pub pathfinder: String,
pub deoxys: String,
}

impl TestConfig {
pub fn new(path: &str) -> anyhow::Result<Self> {
let mut file = File::open(path)?;
let mut content = String::new();

file.read_to_string(&mut content)?;

let config: TestConfig = serde_json::from_str(&content)
.expect("Could not deserialize test at {path} into Config");

Ok(config)
}
}
pub trait TransactionFactory {
fn build(nonce: Option<FieldElement>) -> BroadcastedTransaction;
}
Expand Down
2 changes: 1 addition & 1 deletion unit_tests/tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* Common imports used throughout all unit tests */

#[allow(unused_imports)]
pub use macros::*;
pub use r#macro::*;
#[allow(unused_imports)]
pub use rstest::*;
#[allow(unused_imports)]
Expand Down
9 changes: 5 additions & 4 deletions unit_tests/tests/test_get_class_at.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,13 @@ async fn work_contract_v0(
/// purpose: gets Cairo v1 contract and extracts it's data.
/// success case: should retrieve contract correctly.
///
#[require(block_min = 3000)]
#[rstest]
#[tokio::test]
async fn work_contract_v1(clients: HashMap<String, JsonRpcClient<HttpTransport>>) {
let deoxys = &clients[DEOXYS];
let pathfinder = &clients[PATHFINDER];

async fn work_contract_v1(
deoxys: JsonRpcClient<HttpTransport>,
pathfinder: JsonRpcClient<HttpTransport>,
) {
let response_deoxys = deoxys
.get_class_at(
BlockId::Tag(BlockTag::Latest),
Expand Down
4 changes: 4 additions & 0 deletions unit_tests/tests/test_get_nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ async fn fail_non_existing_contract(clients: HashMap<String, JsonRpcClient<HttpT
/// purpose: call getNonce on ERC721 contract.
/// success case: must return a nonce of 0.
///
#[require(block_min = 50000)]
#[rstest]
#[tokio::test]
async fn work_erc721_contract(clients: HashMap<String, JsonRpcClient<HttpTransport>>) {
Expand All @@ -113,6 +114,7 @@ async fn work_erc721_contract(clients: HashMap<String, JsonRpcClient<HttpTranspo
/// purpose: call getNonce on ERC20 contract.
/// success case: must return a nonce of 0.
///
#[require(block_min = 50000)]
#[rstest]
#[tokio::test]
async fn work_erc20_contract(clients: HashMap<String, JsonRpcClient<HttpTransport>>) {
Expand All @@ -135,6 +137,7 @@ async fn work_erc20_contract(clients: HashMap<String, JsonRpcClient<HttpTranspor
/// purpose: call getNonce on account contract.
/// success case: must return a non-zero nonce.
///
#[require(block_min = 50000)]
#[rstest]
#[tokio::test]
async fn work_account_contract(clients: HashMap<String, JsonRpcClient<HttpTransport>>) {
Expand Down Expand Up @@ -167,6 +170,7 @@ async fn work_account_contract(clients: HashMap<String, JsonRpcClient<HttpTransp
/// purpose: call getNonce on account proxy contract.
/// success case: must return a non-zero nonce.
///
#[require(block_min = 50000)]
#[rstest]
#[tokio::test]
async fn work_account_proxy_contract(clients: HashMap<String, JsonRpcClient<HttpTransport>>) {
Expand Down
Loading

0 comments on commit ebb89af

Please sign in to comment.