what’s Foundry
Foundry 是用 Rust 编写的用于以太坊应用程序开发的快速、可移植和模块化工具包。
来自官网的介绍
Foundry consists of:
Forge: Build, test, fuzz, debug and deploy Solidity contracts, like Hardhat, Brownie, Ape.
Cast: A Swiss Army knife for interacting with EVM smart contracts, sending transactions and getting chain data.
Anvil: Fast local Ethereum development node, akin to Hardhat Network, Tenderly.
Chisel: Fast, utilitarian, and verbose Solidity REPL.
反正就是对英语 dapp 测试基本上就用这个了,性能,功能,非常的灵活和强大。
开始 1
安装下
curl -L https://foundry.paradigm.xyz | bash
,提示网络错误,可以添加环境变量即可。
export https_proxy=http://127.0.0.1:7897 http_proxy=http://127.0.0.1:7897 all_proxy=socks5://127.0.0.1:7897
执行下 source, 就可以找到foundryup ,然后执行foundryup
就可以安装了。
安装完成。
Forge 用法
Forge 是里面的一个工具之一。
Forge:构建、测试、模糊、调试和部署 Solidity 合约,如 Hardhat、Brownie 和 Ape。
forge init
即可。
在当前目录可以看到一个文件, 里面的 foundry.toml 是 Forge 项目中的配置文件。在 foundry.toml 中使用 solc 配置编译器版本和优化次数:
[profile.default]
src = 'src'
out = 'out'
libs = ['lib']
solc = "0.8.x"
optimizer = true
optimizer_runs = 200
然后编译,forge build
.
执行所有的测试。forge test
和 gtest 和 ctest 有点类似,支持过滤条件来执行 test cases.
how to write a case
https://book.getfoundry.sh/forge/writing-tests
for example .
pragma solidity 0.8.10;
import {Test} from "forge-std/Test.sol";
contract ContractBTest is Test {
uint256 testNumber;
function setUp() public {
testNumber = 42;
}
function test_NumberIs42() public {
assertEq(testNumber, 42);
}
/// forge-config: default.allow_internal_expect_revert = true
function testRevert_Subtract43() public {
vm.expectRevert();
testNumber -= 43;
}
}
这个 setup 是每个 case 之前都是需要执行的, 这个和其他测试框架类似
test case 的名字必须用 test 开头,比如这里的test_NumberIs42
, 和 pytest 框架类似。
这里主要顶部有一个 import ,这个就是将使用 Forge Std 的 Test 合约中的函数。该合约本身就是 DSTest 的超集。DSTest 提供基本的日志和断言功能。所以需要导入这个基础的测试集。
assertEq 这个很好理解, 和其他断言超不多。
第二个 test case,有点专业知识了理解。
testRevert_Subtract43
这个就是很少的一个名字,就是需要:测试用例期望合约操作会回滚。
vm.expectRevert(); vm 是 Foundry 提供的特殊对象,用于模拟以太坊虚拟机(EVM)的行为. expectRevert() 是一个断言,表示接下来的操作应该会导致回滚. 测试的结果:如果接下来的操作没有回滚,这个测试将会失败。
这里为什么会失败? 由于在 setUp() 函数中 testNumber 被初始化为 42,减去 43 会导致下溢(underflow),这在 Solidity 0.8.x 版本中会触发回滚。
典型的边界条件测试之一。
read more
https://github.com/foundry-rs/foundry https://book.getfoundry.sh/