Skip to content
This repository has been archived by the owner on Jun 20, 2024. It is now read-only.

Commit

Permalink
📝 edit foundry forge
Browse files Browse the repository at this point in the history
  • Loading branch information
omarespejel committed Oct 19, 2023
1 parent 952798b commit 5f81c62
Showing 1 changed file with 89 additions and 120 deletions.
209 changes: 89 additions & 120 deletions src/ch02-11-foundry-forge.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,77 +13,98 @@ Merely deploying contracts is not the end game. Many tools have offered this cap

To utilize Forge, define test functions and label them with test attributes. Users can either test standalone Cairo functions or integrate contracts, dispatchers, and test contract interactions on-chain.

## `snForge` Command-Line Usage

## Using `snForge` command-line
This section guides you through the Starknet Foundry `snforge` command-line tool. Learn how to set up a new project, compile the code, and execute tests.

This section provides an introduction to the Starknet Foundry `snforge` command-line tool. We will walk you through the process of creating a new project, compiling your code, and running tests.
To start a new project with Starknet Foundry, use the `--init` command and replace `project_name` with your project's name.

## Creating a New Project
```shell
snforge --init project_name
```

To initiate a new project using Starknet Foundry, you can use the `--init` command. Replace `project_name` with the desired name for your project.
Once you've set up the project, inspect its layout:

```shell
snforge --init project_name
cd project_name
tree . -L 1
```
After creating the project, you can explore its structure as follows:

The project structure is as follows:

```shell
$ cd project_name
$ tree . -L 1
.
├── README.md
├── Scarb.toml
├── src
└── tests
```
- src/ contains the source code for all your contracts.
- tests/ is where your test files are located.
- Scarb.toml contains the project and `snforge` configuration.
Make sure that the casm code generation is enabled in the Scarb.toml file:

- `src/` holds your contract source code.
- `tests/` is the location of your test files.
- `Scarb.toml` is for project and **`snforge`** configurations.

Ensure the casm code generation is active in the `Scarb.toml` file:

```shell
# ...
[[target.starknet-contract]]
casm = true
# ...
```
Now, you can run tests with `snforge`:

To run tests using `snforge`:

```shell
$ snforge
snforge

Collected 2 test(s) from the `test_name` package
Running 0 test(s) from `src/`
Running 2 test(s) from `tests/`
[PASS] tests::test_contract::test_increase_balance
[PASS] tests::test_contract::test_cannot_increase_balance_with_zero_value
Tests: 2 passed, 0 failed, 0 skipped
```
## Using snforge with Existing Scarb Projects
If you have an existing Scarb project and want to use `snforge`, ensure that you have declared the `snforge_std package` as a dependency in your project. Add the following line under the [dependencies] section in your Scarb.toml file:

## Integrating `snforge` with Existing Scarb Projects

For those with an established Scarb project who wish to incorporate `snforge`, ensure the `snforge_std package` is declared as a dependency. Insert the line below in the [dependencies] section of your `Scarb.toml`:

```shell
# ...
[dependencies]
snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry.git", tag = "v0.7.1" }
snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry.git", tag = "[VERSION]" }
```
Make sure that the version in the tag matches the version of snforge. You can check the installed snforge version with the following command:
```shell
$ snforge --version
forge 0.7.1
Ensure the tag version corresponds with your `snforge` version. To verify your `snforge` version:
```sh
snforge --version
```
Alternatively, you can add this dependency using the `scarb` command:
Or, add this dependency using the `scarb` command:
```shell
$ scarb add snforge_std --git https://github.com/foundry-rs/starknet-foundry.git --tag v0.7.1
scarb add snforge_std --git https://github.com/foundry-rs/starknet-foundry.git --tag VERSION
```
Now, you are ready to use `snforge` with your existing Scarb project.
With these steps, your existing Scarb project is now **`snforge`**-ready.
## Testing with `snforge`
Utilize Starknet Foundry's `snforge` command to efficiently run tests.
### Executing Tests
## Running Tests with snforge
To run tests using the Starknet Foundry `snforge` command, follow these instructions. We will cover `test execution`, `test filtering`, `running specific tests`, and `handling test execution failures`.
Navigate to the package directory and issue this command to run tests:
### Running Tests
To execute tests, navigate to the package directory and run the following command:
```shell
$ snforge
snforge
```
This command collects and runs tests within the specified package. Here's an example output:
Sample output might resemble:
```shell
Collected 3 test(s) from `package_name` package
Running 3 test(s) from `src/`
Expand All @@ -92,51 +113,36 @@ Running 3 test(s) from `src/`
[PASS] package_name::calling_another
Tests: 3 passed, 0 failed, 0 skipped
```
### Filtering Tests
You can filter the tests to run by passing a filter string after the `snforge` command. By default, tests with an absolute module tree path matching the filter will be executed:
### Filter Tests
Run specific tests using a filter string after the `snforge` command. Tests matching the filter based on their absolute module tree path will be executed:
```shell
$ snforge calling
Collected 2 test(s) from `package_name` package
Running 2 test(s) from `src/`
[PASS] package_name::calling
[PASS] package_name::calling_another
Tests: 2 passed, 0 failed, 0 skipped
```
### Running a Specific Test
To run a specific test, you can use the `--exact` flag along with the filter string. Ensure that you use a fully qualified test name, including the module name:
```shell
$ snforge package_name::calling --exact
Collected 1 test(s) from `package_name` package
Running 1 test(s) from `src/`
[PASS] package_name::calling
Tests: 1 passed, 0 failed, 0 skipped
```
### Stopping Test Execution After First Failed Test
To halt test execution after the first failed test, include the `--exit-first` flag with the `snforge` command:
```shell
$ snforge --exit-first
Collected 6 test(s) from package_name package
Running 6 test(s) from src/
[PASS] package_name::executing
[PASS] package_name::calling
[PASS] package_name::calling_another
[FAIL] package_name::failing
### Run a Specific Test
Failure data:
original value: [8111420071579136082810415440747], converted to a string: [failing check]
[SKIP] package_name::other_test
[SKIP] package_name::yet_another_test
Tests: 3 passed, 1 failed, 2 skipped
Use the `--exact` flag and a fully qualified test name to run a particular test:
Failures:
package_name::failing
```shell
snforge package_name::calling --exact
```
## Testing Starknet contract with `snforge` (Example)
In this example we'll be using the below starknet contract:
### Stop After First Test Failure
To stop after the first test failure, add the `--exit-first` flag to the `snforge` command:
```shell
snforge --exit-first
```
## Basic Example
The example provided below demonstrates how to test a Starknet contract using `snforge`.
```rust
#[starknet::interface]
trait IHelloStarknet<TContractState> {
fn increase_balance(ref self: TContractState, amount: felt252);
Expand All @@ -152,92 +158,55 @@ mod HelloStarknet {
#[external(v0)]
impl HelloStarknetImpl of super::IHelloStarknet<ContractState> {
// Increases the balance by the given amount.
// Increases the balance by the specified amount.
fn increase_balance(ref self: ContractState, amount: felt252) {
self.balance.write(self.balance.read() + amount);
}
// Gets the balance.
// Returns the balance.
fn get_balance(self: @ContractState) -> felt252 {
self.balance.read()
}
}
}
```
It should be noted that the name written after `mod` is the contract name which would be referenced later on; in this case, it is `HelloStarknet`.
```
## Writing the test
let's write the test cases for `HelloStarknet` contract. In this test, we'll deploy `Hellostarknet` and interact with some functions:
Remember, the identifier following `mod` signifies the contract name. Here, the contract name is `HelloStarknet`.
```shell
### Craft the Test
Below is a test for the **`HelloStarknet`** contract. This test deploys **`HelloStarknet`** and interacts with its functions:
```rust
use snforge_std::{ declare, ContractClassTrait };
#[test]
fn call_and_invoke() {
// First declare and deploy a contract
// Declare and deploy the contract
let contract = declare('HelloStarknet');
let contract_address = contract.deploy(@ArrayTrait::new()).unwrap();
// Create a Dispatcher object that will allow interacting with the deployed contract
// Instantiate a Dispatcher object for contract interactions
let dispatcher = IHelloStarknetDispatcher { contract_address };
// Call a view function of the contract
// Invoke a contract's view function
let balance = dispatcher.get_balance();
assert(balance == 0, 'balance == 0');
// Call a function of the contract
// Here we mutate the state of the storage
// Invoke another function to modify the storage state
dispatcher.increase_balance(100);
// Check that transaction took effect
// Validate the transaction's effect
let balance = dispatcher.get_balance();
assert(balance == 100, 'balance == 100');
}
```
Now we are ready to run `snforge`. once you run the `snforge` command, you should get the below output
To run the test, execute the `snforge` command. The expected output is:
```shell
$ snforge
Collected 1 test(s) from using_dispatchers package
Running 1 test(s) from src/
[PASS] using_dispatchers::call_and_invoke
Tests: 1 passed, 0 failed, 0 skipped
```
Now you have successfully created and tested your starknet contract using `snforge`.
## snforge Commands
- Running `snforge` in the Current Directory
To run the snforge command in the current directory, simply execute the following command:
### Test Filter Options
- `-e, --exact`: Use the `-e` or `--exact` option to run a test with a name that exactly matches the provided test filter. The test filter should be a fully qualified test name, including the package name. For example, instead of specifying just `my_test`, use `package_name::my_test` as the test filter.
- `--init` <NAME>: The `--init` <NAME> option allows you to create a new directory and forge project with the specified name <NAME>.
- `-x`, `--exit-first`: By using the` -x` or `--exit-first` option, you can stop the execution of tests after the first test failure is encountered.
### Package Selection
- `-p`, `--package`: The `-p` or `--package` option is used to specify the packages on which to run the `snforge` command. You can either provide a concrete package name (e.g., foobar) or use a prefix glob (e.g., foo*) to match multiple packages.
- `-w`, `--workspace`: Use the `-w` or `--workspace` option to run tests for all packages in the workspace.
### Fuzzer Configuration
- `-r`, `--fuzzer-runs` <FUZZER_RUNS>: Specify the number of fuzzer runs using the `-r` or `--fuzzer-runs` option, followed by the desired number of runs <FUZZER_RUNS>.
- `-s`, `--fuzzer-seed` <FUZZER_SEED>: Set the seed for the fuzzer by using the `-s` or `--fuzzer-seed` option, followed by the desired seed value <FUZZER_SEED>.
### Cache Management
- `-c`, `--clean-cache`: To clean the `snforge` cache directory, simply use the `-c` or `--clean-cache` option.
### Help and Version Information
- `-h`,` --help`: Use the `-h` or `--help` option to print the help information, providing guidance on how to use `snforge`.
- `-V`, `--version`: To display the current version of `snforge`, use the `-V` or `--version` option.
Note: Replace <NAME>, <FUZZER_RUNS>, and <FUZZER_SEED> with your specific values when using the `snforge` command.

0 comments on commit 5f81c62

Please sign in to comment.