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

feat: add macros for testing #2337

Merged
merged 3 commits into from
Aug 23, 2024
Merged

feat: add macros for testing #2337

merged 3 commits into from
Aug 23, 2024

Conversation

glihm
Copy link
Collaborator

@glihm glihm commented Aug 23, 2024

This PR adds some useful macro to speed up testing setup.

A painful point in testing setup is spawning the test world with all the namespaces and models registered. This can quickly become hard to track when the number of models increases.

An important consideration to use the two macros below is that, sozo build must be run first. The compiler will remind it to the user if the project is not built first.

get_models_test_class_hashes

This macro gives the possibility to get the TEST_CLASS_HASH for all the models or only for the given namespaces.

// Only registers the models for the given namespaces.
let world = spawn_test_world(
    ["dojo_examples", "dojo_examples_weapons"].span(),
    get_models_test_class_hashes!(["dojo_examples", "dojo_examples_weapons"])
);

// Register all models in the project.
let world = spawn_test_world(
    ["dojo_examples", "dojo_examples_weapons"].span(),
    get_models_test_class_hashes!()
);

spawn_test_world

This macro has only namespaces as control, and registers all the namespaces and models inside the given namespaces (or everything). As the dojo world deployment and registration of models can take a long time, this macro also allow filtering by namespaces.

// Register all namespaces and models.
let world = spawn_test_world!();

// Register all models for the given namespace.
let world = spawn_test_world!(["ns1"]);

Summary by CodeRabbit

  • New Features

    • Introduced two new inline macro plugins: GetModelsTestClassHashes and SpawnTestWorldFull, enhancing macro capabilities in the Cairo programming language.
    • Added new public functions for managing manifests and namespaces, improving the handling of configuration settings.
    • Expanded testing capabilities with new test cases for the introduced macros to validate their functionalities.
  • Bug Fixes

    • Implemented error diagnostics for improper usage of new inline macros, enhancing user feedback.
  • Documentation

    • Updated documentation for new configurations and functionalities to provide clearer guidance for developers.

Copy link

coderabbitai bot commented Aug 23, 2024

Walkthrough

Ohayo, sensei! The recent changes involve the introduction of two new inline macro plugins, GetModelsTestClassHashes and SpawnTestWorldFull, into the Cairo programming language framework. Additionally, enhancements to utility functions for managing manifests and namespaces, as well as updates to testing files for validating functionalities, have been implemented. Configuration handling has also been improved, facilitating better access to dojo manifests.

Changes

Files Change Summary
crates/dojo-lang/src/inline_macros/... Added two new plugins for inline macros: GetModelsTestClassHashes and SpawnTestWorldFull. Introduced functions in utils.rs for loading manifests and retrieving manifest directories. New modules added in mod.rs.
crates/dojo-lang/src/plugin.rs Integrated the new inline macro plugins into the dojo_plugin_suite function, expanding its capabilities.
crates/dojo-lang/src/scarb_internal/... Enhanced configuration handling with a new key for the manifests directory, improving organization and access.
crates/dojo-lang/src/semantics/test_data/... Introduced test files for validating the new plugins, covering various scenarios for both get_models_test_class_hashes!() and spawn_test_world_full!().
crates/dojo-world/src/config/... Added DOJO_MANIFESTS_DIR_CFG_KEY to public exports, allowing external access to the manifests directory configuration. Added a new constant for the manifests directory key.
examples/spawn-and-move/src/actions.cairo Refactored test cases to utilize spawn_test_world_full!() and get_models_test_class_hashes!(), removing mutable arrays for models and streamlining the initialization process in tests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Plugin
    participant Utils
    participant Config

    User->>Plugin: Invoke get_models_test_class_hashes!
    Plugin->>Utils: Load manifest models and namespaces
    Utils-->>Plugin: Return models and namespaces
    Plugin-->>User: Return class hashes

    User->>Plugin: Invoke spawn_test_world_full!
    Plugin->>Utils: Load models and namespaces
    Utils-->>Plugin: Return models and namespaces
    Plugin-->>User: Spawn test world
Loading

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 51a678b and 7cf3649.

Files ignored due to path filters (2)
  • spawn-and-move-db.tar.gz is excluded by !**/*.gz
  • types-test-db.tar.gz is excluded by !**/*.gz
Files selected for processing (12)
  • crates/dojo-lang/src/inline_macros/get_models_test_class_hashes.rs (1 hunks)
  • crates/dojo-lang/src/inline_macros/mod.rs (1 hunks)
  • crates/dojo-lang/src/inline_macros/spawn_test_world_full.rs (1 hunks)
  • crates/dojo-lang/src/inline_macros/utils.rs (2 hunks)
  • crates/dojo-lang/src/plugin.rs (2 hunks)
  • crates/dojo-lang/src/scarb_internal/mod.rs (4 hunks)
  • crates/dojo-lang/src/semantics/test_data/get_models_test_class_hashes (1 hunks)
  • crates/dojo-lang/src/semantics/test_data/spawn_test_world_full (1 hunks)
  • crates/dojo-lang/src/semantics/tests.rs (1 hunks)
  • crates/dojo-world/src/config/mod.rs (1 hunks)
  • crates/dojo-world/src/config/namespace_config.rs (1 hunks)
  • examples/spawn-and-move/src/actions.cairo (2 hunks)
Files skipped from review due to trivial changes (1)
  • crates/dojo-world/src/config/namespace_config.rs
Additional comments not posted (14)
crates/dojo-world/src/config/mod.rs (1)

9-11: Ohayo, sensei! The export addition looks good.

The addition of DOJO_MANIFESTS_DIR_CFG_KEY to the exports aligns with the existing export pattern and enhances the module's interface.

crates/dojo-lang/src/semantics/test_data/spawn_test_world_full (1)

1-43: Ohayo, sensei! The test cases are well-structured.

The test scenarios for missing configurations and invalid parameters are comprehensive and the error messages are clear. This will help ensure robustness in the macro's usage.

crates/dojo-lang/src/semantics/tests.rs (1)

21-24: Ohayo, sensei! The macro additions are seamless.

The integration of get_models_test_class_hashes and spawn_test_world_full into the test_file_test! macro is consistent and enhances the testing framework.

crates/dojo-lang/src/semantics/test_data/get_models_test_class_hashes (4)

1-21: Ohayo, sensei! Ensure the test setup is complete.

The test case checks for a missing dojo_manifests_dir, which is expected to fail. Make sure the test environment is correctly set up to simulate this condition.


24-44: Ohayo, sensei! Validate parameter handling.

The test case for bad parameters is well-structured. Ensure that the macro correctly handles parameter validation and provides clear error messages.


47-67: Ohayo, sensei! Verify argument validation.

The test case for too many parameters is clear. Confirm that the macro's error handling for argument validation is robust and user-friendly.


70-89: Ohayo, sensei! Confirm directory dependencies.

This test case checks for missing directories again. Ensure that the test environment is set up to reflect this scenario accurately.

crates/dojo-lang/src/inline_macros/spawn_test_world_full.rs (1)

19-43: Ohayo, sensei! Validate argument checks.

The generate_code function checks for empty arguments. Ensure that the error message is clear and guides the user on correct usage.

crates/dojo-lang/src/inline_macros/mod.rs (1)

10-13: Modules added successfully!

The new modules get_models_test_class_hashes and spawn_test_world_full are integrated smoothly, expanding the module's capabilities without affecting existing functionality. Well done!

crates/dojo-lang/src/scarb_internal/mod.rs (1)

Line range hint 18-243: Configuration handling enhanced successfully!

The addition of DOJO_MANIFESTS_DIR_CFG_KEY and the modifications to cfg_set_from_component improve manifest organization and access. The logic is clear and well-implemented.

Verify the directory path setup.

Ensure that the dojo_manifests_dir is correctly set up and accessible. This is crucial for the new configuration to function as intended.

Run the following script to verify the directory path setup:

Verification successful

Ohayo, sensei! The directory path setup is verified successfully! 🌟

The dojo_manifests_dir is correctly set up and accessible in the expected locations. The configuration changes enhance manifest organization and access as intended.

  • The manifests directories are present in multiple locations, confirming the setup.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the directory path setup for `dojo_manifests_dir`.

# Test: Check if the directory is correctly set. Expect: Directory path should exist.
fd --type d "manifests" --exec echo "Directory exists: {}"

Length of output: 252

examples/spawn-and-move/src/actions.cairo (2)

204-204: LGTM! Simplified test world setup.

The use of spawn_test_world_full!() effectively streamlines the test setup process. This change enhances maintainability and reduces potential errors.


239-240: LGTM! Enhanced flexibility with get_models_test_class_hashes!().

Using get_models_test_class_hashes!() allows for dynamic retrieval of model hashes, improving flexibility and reducing maintenance overhead.

crates/dojo-lang/src/plugin.rs (2)

161-161: LGTM! Successful integration of GetModelsTestClassHashes.

The addition of GetModelsTestClassHashes to the plugin suite enhances the functionality without disrupting existing operations.


162-162: LGTM! Successful integration of SpawnTestWorldFull.

The addition of SpawnTestWorldFull to the plugin suite enhances the functionality without disrupting existing operations.


Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@glihm
Copy link
Collaborator Author

glihm commented Aug 23, 2024

Wondering if two macros is necessary...
We may have only spawn_test_world! macro actually, and we can provide a list of namespaces. Then the macro does the rest.

// Registers everything.
let world = spawn_test_world!();

// Registers only the given namespace and it's models.
let world = spawn_test_world!(["dojo_examples"]);

But not sure if having access to TEST_CLASS_HASH in a array can somehow be relevant for testing.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (2)
crates/dojo-lang/src/inline_macros/spawn_test_world_full.rs (1)

62-84: Ohayo, sensei! Review code generation logic.

The code generation logic for spawning the test world is well-implemented. Consider adding comments to explain the purpose of each step for future maintainability.

crates/dojo-lang/src/inline_macros/get_models_test_class_hashes.rs (1)

1-139: Great implementation with robust error handling!

The GetModelsTestClassHashes macro plugin is well-implemented with efficient use of PatchBuilder for code generation. Error handling and diagnostics are thorough.

Consider improving error messages for clarity.

Some error messages could be more descriptive to aid debugging. For example, specifying which argument caused the error could be helpful.

Comment on lines +33 to +62
/// Reads all the models and namespaces from base manifests files.
pub fn load_manifest_models_and_namespaces(
cfg_set: &CfgSet,
whitelisted_namespaces: &[String],
) -> anyhow::Result<(Vec<String>, Vec<String>)> {
let dojo_manifests_dir = get_dojo_manifests_dir(cfg_set.clone())?;

let base_dir = dojo_manifests_dir.join("base");
let base_abstract_manifest = BaseManifest::load_from_path(&base_dir)?;

let mut models = HashSet::new();
let mut namespaces = HashSet::new();

for model in base_abstract_manifest.models {
let qualified_path = model.inner.qualified_path;
let namespace = naming::split_tag(&model.inner.tag)?.0;

if !whitelisted_namespaces.is_empty() && !whitelisted_namespaces.contains(&namespace) {
continue;
}

models.insert(qualified_path);
namespaces.insert(namespace);
}

let models_vec: Vec<String> = models.into_iter().collect();
let namespaces_vec: Vec<String> = namespaces.into_iter().collect();

Ok((namespaces_vec, models_vec))
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohayo, sensei! Improve error messaging.

The load_manifest_models_and_namespaces function handles manifest loading and filtering. Consider enhancing error messages to provide more context on failures, such as which file or namespace caused the issue.

Comment on lines +64 to +73
/// Gets the dojo_manifests_dir from the cfg_set.
pub fn get_dojo_manifests_dir(cfg_set: CfgSet) -> anyhow::Result<Utf8PathBuf> {
for cfg in cfg_set.into_iter() {
if cfg.key == DOJO_MANIFESTS_DIR_CFG_KEY {
return Ok(Utf8PathBuf::from(cfg.value.unwrap().as_str().to_string()));
}
}

Err(anyhow::anyhow!("dojo_manifests_dir not found"))
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohayo, sensei! Ensure robust error handling.

The get_dojo_manifests_dir function retrieves the directory path. Ensure that the error message when the key is not found is informative enough for debugging purposes.

Comment on lines 45 to 60
let (namespaces, models) = match load_manifest_models_and_namespaces(metadata.cfg_set, &[])
{
Ok((namespaces, models)) => (namespaces, models),
Err(_e) => {
return InlinePluginResult {
code: None,
diagnostics: vec![PluginDiagnostic {
stable_ptr: syntax.stable_ptr().untyped(),
message: "Failed to load models and namespaces, ensure you have run `sozo \
build` first."
.to_string(),
severity: Severity::Error,
}],
};
}
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohayo, sensei! Enhance error feedback.

When loading models and namespaces fails, consider providing more detailed error feedback, possibly including the specific reason for the failure.

Copy link

codecov bot commented Aug 23, 2024

Codecov Report

Attention: Patch coverage is 60.76555% with 82 lines in your changes missing coverage. Please review.

Project coverage is 67.19%. Comparing base (3e3c33e) to head (91887d0).
Report is 6 commits behind head on main.

Files Patch % Lines
...es/dojo-lang/src/inline_macros/spawn_test_world.rs 57.35% 29 Missing ⚠️
.../src/inline_macros/get_models_test_class_hashes.rs 60.00% 28 Missing ⚠️
crates/dojo-lang/src/inline_macros/utils.rs 54.54% 25 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2337      +/-   ##
==========================================
+ Coverage   66.13%   67.19%   +1.05%     
==========================================
  Files         354      357       +3     
  Lines       46585    46622      +37     
==========================================
+ Hits        30808    31326     +518     
+ Misses      15777    15296     -481     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@glihm glihm merged commit a3ddf39 into dojoengine:main Aug 23, 2024
14 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant