Compiling Contracts
To compile contracts in Ape, place them in the `contracts/` directory of your project. Then run:
bash
ape compile
This will compile all the contracts in the directory. You can also specify the `--size` option to display the size of each contract after compilation:
bash
ape compile --size
Testing Contracts
Ape uses the `pytest` testing framework under the hood. To write tests, create a `tests/` directory in your project and add your test files there.
For example, create a file named `test_token.py` with the following contents:
python
from ape import accounts
def test_initial_supply(token_contract):
assert token_contract.totalSupply() == 1000
Here we define a test function that checks the initial total supply of a token contract.
To run the tests, use the `ape test` command:
bash
ape test
This will discover and run all the test cases in the `tests/` directory.
You can also specify pytest flags to filter which tests to run. For example:
bash
ape test -k test_initial_supply
This will only run the test cases that match the name "test_initial_supply".
Fixtures
Ape uses pytest fixtures to set up the testing environment. You can define fixtures in conftest.py files. For example:
python
@pytest.fixture
def token_contract(accounts):
return accounts[0].deploy(Token, 1000)
This fixture deploys a Token contract with an initial supply of 1000 tokens using the first account.
The fixture is then automatically injected into the test functions that request it as an argument.
Debugging Failed Tests
When a test fails, Ape will show you the specific line where the failure occurred and the reason for the failure.
You can use the `-i` flag to drop into an interactive debugger when a test fails:
bash
ape test -i
This will open an interactive console where you can inspect variables and step through the code to debug the issue.
In summary, Ape makes it easy to compile and test smart contracts using pytest. You can define fixtures to set up the testing environment and use pytest flags to filter and debug tests.
Citations:[1] https://github.com/Consensys/apeworx-ape
[2] https://github.com/ApeWorX/ape
[3] https://www.youtube.com/watch?v=LWFPMiXhlyI
[4] https://www.degencode.com/p/introduction-to-ape-framework
[5] https://dev.to/mosesmuwawu/how-to-compile-deploy-and-interact-with-smart-contracts-using-apeworxape-and-vs-code-4hie
[6] https://blog.chain.link/apeworx-python-vyper/
[7] https://apeworx.io/framework/
[8] https://docs.apeworx.io/ape/stable/userguides/contracts.html