Skip to content

Commit

Permalink
feat: start refactor to integrate testing logic for models and entiti…
Browse files Browse the repository at this point in the history
…es (#1749)

* feat: start refactor to integrate testing logic for models and entities

* feat: set contract address of actions after migration

* feat: test store spawn

* fmt

* chore: imports

* fix: tests
  • Loading branch information
Larkooo authored Apr 3, 2024
1 parent 3e3b521 commit c2280fe
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 60 deletions.
4 changes: 2 additions & 2 deletions bin/sozo/src/commands/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,9 @@ where
}

let ui = ws.config().ui();
let strategy = prepare_migration(&target_dir, diff, name, world_address, &ui)?;
let mut strategy = prepare_migration(&target_dir, diff, name, world_address, &ui)?;

match migration::apply_diff(ws, account, None, &strategy).await {
match migration::apply_diff(ws, account, None, &mut strategy).await {
Ok(migration_output) => {
config.ui().print(format!(
"🎉 World at address {} updated!",
Expand Down
4 changes: 2 additions & 2 deletions bin/sozo/tests/register_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ async fn reregister_models() {

let base_dir = "../../examples/spawn-and-move";
let target_dir = format!("{}/target/dev", base_dir);
let migration = prepare_migration(base_dir.into(), target_dir.into()).unwrap();
let mut migration = prepare_migration(base_dir.into(), target_dir.into()).unwrap();

let sequencer =
TestSequencer::start(SequencerConfig::default(), get_default_test_starknet_config()).await;

let mut account = sequencer.account();
account.set_block_id(BlockId::Tag(BlockTag::Pending));

execute_strategy(&ws, &migration, &account, None).await.unwrap();
execute_strategy(&ws, &mut migration, &account, None).await.unwrap();
let world_address = &format!("0x{:x}", &migration.world_address().unwrap());
let account_address = &format!("0x{:x}", account.address());
let private_key = &format!("0x{:x}", sequencer.raw_account().private_key);
Expand Down
16 changes: 8 additions & 8 deletions crates/sozo/ops/src/migration/migration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ async fn migrate_with_auto_mine() {

let base_dir = "../../../examples/spawn-and-move";
let target_dir = format!("{}/target/dev", base_dir);
let migration = prepare_migration(base_dir.into(), target_dir.into()).unwrap();
let mut migration = prepare_migration(base_dir.into(), target_dir.into()).unwrap();

let sequencer =
TestSequencer::start(SequencerConfig::default(), get_default_test_starknet_config()).await;

let mut account = sequencer.account();
account.set_block_id(BlockId::Tag(BlockTag::Pending));

execute_strategy(&ws, &migration, &account, None).await.unwrap();
execute_strategy(&ws, &mut migration, &account, None).await.unwrap();

sequencer.stop().unwrap();
}
Expand All @@ -49,7 +49,7 @@ async fn migrate_with_block_time() {

let base = "../../../examples/spawn-and-move";
let target_dir = format!("{}/target/dev", base);
let migration = prepare_migration(base.into(), target_dir.into()).unwrap();
let mut migration = prepare_migration(base.into(), target_dir.into()).unwrap();

let sequencer = TestSequencer::start(
SequencerConfig { block_time: Some(1000), ..Default::default() },
Expand All @@ -60,7 +60,7 @@ async fn migrate_with_block_time() {
let mut account = sequencer.account();
account.set_block_id(BlockId::Tag(BlockTag::Pending));

execute_strategy(&ws, &migration, &account, None).await.unwrap();
execute_strategy(&ws, &mut migration, &account, None).await.unwrap();
sequencer.stop().unwrap();
}

Expand All @@ -72,7 +72,7 @@ async fn migrate_with_small_fee_multiplier_will_fail() {

let base = "../../../examples/spawn-and-move";
let target_dir = format!("{}/target/dev", base);
let migration = prepare_migration(base.into(), target_dir.into()).unwrap();
let mut migration = prepare_migration(base.into(), target_dir.into()).unwrap();

let sequencer = TestSequencer::start(
Default::default(),
Expand All @@ -93,7 +93,7 @@ async fn migrate_with_small_fee_multiplier_will_fail() {
assert!(
execute_strategy(
&ws,
&migration,
&mut migration,
&account,
Some(TxConfig { fee_estimate_multiplier: Some(0.2f64), wait: false, receipt: false }),
)
Expand Down Expand Up @@ -144,15 +144,15 @@ async fn migration_from_remote() {
.unwrap();
let world = WorldDiff::compute(manifest, None);

let migration = prepare_for_migration(
let mut migration = prepare_for_migration(
None,
Some(felt!("0x12345")),
&Utf8Path::new(&target_dir).to_path_buf(),
world,
)
.unwrap();

execute_strategy(&ws, &migration, &account, None).await.unwrap();
execute_strategy(&ws, &mut migration, &account, None).await.unwrap();

let local_manifest = BaseManifest::load_from_path(
&Utf8Path::new(base).to_path_buf().join(MANIFESTS_DIR).join(BASE_DIR),
Expand Down
14 changes: 8 additions & 6 deletions crates/sozo/ops/src/migration/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,14 @@ where
return Ok(());
}

let strategy = prepare_migration(&target_dir, diff, name.clone(), world_address, &ui)?;
let mut strategy = prepare_migration(&target_dir, diff, name.clone(), world_address, &ui)?;
let world_address = strategy.world_address().expect("world address must exist");

if dry_run {
print_strategy(&ui, account.provider(), &strategy).await;
} else {
// Migrate according to the diff.
match apply_diff(ws, account, None, &strategy).await {
match apply_diff(ws, account, None, &mut strategy).await {
Ok(migration_output) => {
update_manifests_and_abis(
ws,
Expand Down Expand Up @@ -237,7 +237,7 @@ pub async fn apply_diff<P, S>(
ws: &Workspace<'_>,
account: &SingleOwnerAccount<P, S>,
txn_config: Option<TxConfig>,
strategy: &MigrationStrategy,
strategy: &mut MigrationStrategy,
) -> Result<MigrationOutput>
where
P: Provider + Sync + Send + 'static,
Expand Down Expand Up @@ -372,7 +372,7 @@ pub fn prepare_migration(

pub async fn execute_strategy<P, S>(
ws: &Workspace<'_>,
strategy: &MigrationStrategy,
strategy: &mut MigrationStrategy,
migrator: &SingleOwnerAccount<P, S>,
txn_config: Option<TxConfig>,
) -> Result<MigrationOutput>
Expand Down Expand Up @@ -625,7 +625,7 @@ where
}

async fn deploy_contracts<P, S>(
strategy: &MigrationStrategy,
strategy: &mut MigrationStrategy,
migrator: &SingleOwnerAccount<P, S>,
ui: &Ui,
txn_config: Option<TxConfig>,
Expand All @@ -646,7 +646,8 @@ where

let world_address = strategy.world_address()?;

for contract in strategy.contracts.iter() {
let contracts = &mut strategy.contracts;
for contract in contracts {
let name = &contract.diff.name;
ui.print(italic_message(name).to_string());
match contract
Expand All @@ -666,6 +667,7 @@ where
));
}

contract.contract_address = output.contract_address;
ui.print_hidden_sub(format!("Deploy transaction: {:#x}", output.transaction_hash));
ui.print_sub(format!("Contract address: {:#x}", output.contract_address));
deploy_output.push(Some(output));
Expand Down
4 changes: 2 additions & 2 deletions crates/sozo/ops/src/tests/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ pub async fn setup(
let base_dir = "../../../examples/spawn-and-move";
let target_dir = format!("{}/target/dev", base_dir);

let migration = prepare_migration(base_dir.into(), target_dir.into())?;
let mut migration = prepare_migration(base_dir.into(), target_dir.into())?;

let mut account = sequencer.account();
account.set_block_id(BlockId::Tag(BlockTag::Pending));

let output = migration::execute_strategy(
&ws,
&migration,
&mut migration,
&account,
Some(TxConfig { wait: true, ..Default::default() }),
)
Expand Down
82 changes: 44 additions & 38 deletions crates/torii/core/src/sql_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,31 @@ use dojo_test_utils::sequencer::{
get_default_test_starknet_config, SequencerConfig, TestSequencer,
};
use dojo_world::contracts::world::WorldContractReader;
use dojo_world::migration::strategy::MigrationStrategy;
use dojo_world::utils::TransactionWaiter;
use scarb::ops;
use sozo_ops::migration::execute_strategy;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use starknet::core::types::{BlockId, BlockTag, Event, FieldElement};
use starknet::accounts::{Account, Call};
use starknet::core::types::{BlockId, BlockTag};
use starknet::core::utils::get_selector_from_name;
use starknet::providers::jsonrpc::HttpTransport;
use starknet::providers::{JsonRpcClient, Provider};
use starknet_crypto::poseidon_hash_many;
use tokio::sync::broadcast;

use crate::engine::{Engine, EngineConfig, Processors};
use crate::processors::register_model::RegisterModelProcessor;
use crate::processors::store_set_record::StoreSetRecordProcessor;
use crate::sql::Sql;
use crate::utils::utc_dt_string_from_timestamp;

pub async fn bootstrap_engine<P>(
world: WorldContractReader<P>,
db: Sql,
provider: P,
migration: MigrationStrategy,
sequencer: TestSequencer,
) -> Result<Engine<P>, Box<dyn std::error::Error>>
where
P: Provider + Send + Sync,
{
let mut account = sequencer.account();
account.set_block_id(BlockId::Tag(BlockTag::Pending));

let config = build_test_config("../../../examples/spawn-and-move/Scarb.toml").unwrap();
let ws = ops::read_workspace(config.manifest_path(), &config)
.unwrap_or_else(|op| panic!("Error building workspace: {op:?}"));
execute_strategy(&ws, &migration, &account, None).await.unwrap();

let (shutdown_tx, _) = broadcast::channel(1);
let mut engine = Engine::new(
world,
Expand Down Expand Up @@ -67,16 +58,37 @@ async fn test_load_from_remote() {
sqlx::migrate!("../migrations").run(&pool).await.unwrap();
let base_path = "../../../examples/spawn-and-move";
let target_path = format!("{}/target/dev", base_path);
let migration = prepare_migration(base_path.into(), target_path.into()).unwrap();
let mut migration = prepare_migration(base_path.into(), target_path.into()).unwrap();
let sequencer =
TestSequencer::start(SequencerConfig::default(), get_default_test_starknet_config()).await;
let provider = JsonRpcClient::new(HttpTransport::new(sequencer.url()));
let world = WorldContractReader::new(migration.world_address().unwrap(), &provider);

let mut account = sequencer.account();
account.set_block_id(BlockId::Tag(BlockTag::Pending));

let config = build_test_config("../../../examples/spawn-and-move/Scarb.toml").unwrap();
let ws = ops::read_workspace(config.manifest_path(), &config)
.unwrap_or_else(|op| panic!("Error building workspace: {op:?}"));
execute_strategy(&ws, &mut migration, &account, None).await.unwrap();

// spawn
let tx = account
.execute(vec![Call {
to: migration.contracts.first().unwrap().contract_address,
selector: get_selector_from_name("spawn").unwrap(),
calldata: vec![],
}])
.send()
.await
.unwrap();

TransactionWaiter::new(tx.transaction_hash, &provider).await.unwrap();

let mut db = Sql::new(pool.clone(), migration.world_address().unwrap()).await.unwrap();
let _ = bootstrap_engine(world, db.clone(), &provider, migration, sequencer).await;
let _ = bootstrap_engine(world, db.clone(), &provider).await;

let block_timestamp = 1710754478_u64;
let _block_timestamp = 1710754478_u64;
let models = sqlx::query("SELECT * FROM models").fetch_all(&pool).await.unwrap();
assert_eq!(models.len(), 3);

Expand Down Expand Up @@ -104,29 +116,23 @@ async fn test_load_from_remote() {
assert_eq!(packed_size, 1);
assert_eq!(unpacked_size, 2);

let event_id = format!("0x{:064x}:0x{:04x}:0x{:04x}", 0, 42, 69);
db.store_event(
&event_id,
&Event {
from_address: FieldElement::ONE,
keys: Vec::from([FieldElement::TWO]),
data: Vec::from([FieldElement::TWO, FieldElement::THREE]),
},
FieldElement::THREE,
block_timestamp,
);
// print all entities
let entities = sqlx::query("SELECT * FROM entities").fetch_all(&pool).await.unwrap();
assert_eq!(entities.len(), 1);

db.execute().await.unwrap();
let (id, keys): (String, String) = sqlx::query_as(
format!(
"SELECT id, keys FROM entities WHERE id = '{:#x}'",
poseidon_hash_many(&[account.address()])
)
.as_str(),
)
.fetch_one(&pool)
.await
.unwrap();

let query = format!(
"SELECT keys, data, transaction_hash, executed_at FROM events WHERE id = '{}'",
event_id
);
let (keys, data, tx_hash, executed_at): (String, String, String, String) =
sqlx::query_as(&query).fetch_one(&pool).await.unwrap();
assert_eq!(id, format!("{:#x}", poseidon_hash_many(&[account.address()])));
assert_eq!(keys, format!("{:#x}/", account.address()));

assert_eq!(keys, format!("{:#x}/", FieldElement::TWO));
assert_eq!(data, format!("{:#x}/{:#x}/", FieldElement::TWO, FieldElement::THREE));
assert_eq!(tx_hash, format!("{:#x}", FieldElement::THREE));
assert_eq!(executed_at, utc_dt_string_from_timestamp(block_timestamp));
db.execute().await.unwrap();
}
4 changes: 2 additions & 2 deletions crates/torii/graphql/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ pub async fn spinup_types_test() -> Result<SqlitePool> {

let base_path = "../types-test";
let target_path = format!("{}/target/dev", base_path);
let migration = prepare_migration(base_path.into(), target_path.into()).unwrap();
let mut migration = prepare_migration(base_path.into(), target_path.into()).unwrap();
let config = build_test_config("../types-test/Scarb.toml").unwrap();
let db = Sql::new(pool.clone(), migration.world_address().unwrap()).await.unwrap();

Expand All @@ -292,7 +292,7 @@ pub async fn spinup_types_test() -> Result<SqlitePool> {
let ws = ops::read_workspace(config.manifest_path(), &config)
.unwrap_or_else(|op| panic!("Error building workspace: {op:?}"));

execute_strategy(&ws, &migration, &account, None).await.unwrap();
execute_strategy(&ws, &mut migration, &account, None).await.unwrap();

let manifest =
DeploymentManifest::load_from_remote(&provider, migration.world_address().unwrap())
Expand Down

0 comments on commit c2280fe

Please sign in to comment.