如何用 Brownie 与 pytest 集成测试合约?

解读

国内 DeFi、NFT、链游团队招人时,常把“能用 pytest 写 Solidity 测试”列为硬性技能。Brownie 是以太坊官方推荐的 Python 开发框架,底层直接对接 pytest,因此面试官真正想确认的是:

  1. 你是否理解 Brownie 的测试生命周期与 pytest fixtures 的映射关系;
  2. 能否在本地私链(ganache-cli 或 hardhat)上完成“编译→部署→交互→断言”闭环;
  3. 是否掌握参数化、异常断言、快照回退、并行加速等 pytest 高阶技巧,以支撑千级用例的 CI 流水线。

一句话:不是“能不能跑通”,而是“跑得稳、回滚快、报告全、可上生产”。

知识点

  1. Brownie 测试目录约定:tests/ 下任意 test_*.py 都会被 pytest 自动收集;
  2. fixtures:accounts、ContractContainer、network、chain、history 由 brownie 预注入,与 pytest 原生 fixture 完全兼容;
  3. 快照机制:chain.snapshot() / chain.revert() 实现用例级隔离,比重新挖矿快 10 倍以上;
  4. 异常断言:brownie.reverts() 上下文管理器可精准捕获 require / revert 信息,支持正则匹配;
  5. 参数化:@pytest.mark.parametrize 与 brownie 的 deploy 参数组合,可一次性覆盖多代币精度、多权限角色;
  6. 并行执行:pytest-xdist 的 -n auto 与 brownie 无锁冲突,但需把 ganache 端口动态化(pytest 的 tmp_path_factory 实现端口文件锁);
  7. 覆盖率:brownie test --coverage 会生成 solc coverage 数据,结合 pytest-cov 可合并 Python 与 Solidity 报告,满足国内监管审计要求;
  8. CI 集成:GitHub Actions + self-hosted runner 内网拉取 Geth 镜像,通过 brownie networks add 私有链,保证测试网断网仍可跑。

答案

  1. 环境准备
    python -m venv venv && source venv/bin/activate
    pip install eth-brownie 'pytest>=7' pytest-xdist pytest-html

  2. 初始化项目
    brownie init my_project --template erc20
    cd my_project

  3. 编写合约
    contracts/MyToken.sol
    pragma solidity ^0.8.0;
    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    contract MyToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
    _mint(msg.sender, initialSupply);
    }
    function mint(address to, uint256 amount) external {
    require(amount > 0, "zero");
    _mint(to, amount);
    }
    }

  4. 编写测试 tests/test_token.py
    import pytest
    from brownie import MyToken, accounts, chain

    @pytest.fixture(scope="module")
    def token():
    return MyToken.deploy(1e18, {"from": accounts[0]})

    def test_initial_supply(token):
    assert token.totalSupply() == 1e18
    assert token.balanceOf(accounts[0]) == 1e18

    @pytest.mark.parametrize("amount", [0, 1e12, 1e18])
    def test_mint(token, amount):
    if amount == 0:
    with pytest.reverts("zero"):
    token.mint(accounts[1], amount, {"from": accounts[0]})
    else:
    tx = token.mint(accounts[1], amount, {"from": accounts[0]})
    assert token.balanceOf(accounts[1]) == amount
    assert tx.events["Transfer"][0]["value"] == amount

    def test_snapshot_isolation(token):
    snap = chain.snapshot()
    token.mint(accounts[2], 1e18, {"from": accounts[0]})
    assert token.balanceOf(accounts[2]) == 1e18
    chain.revert(snap)
    assert token.balanceOf(accounts[2]) == 0

  5. 运行与报告
    brownie test -n auto --coverage --html=report.html
    控制台输出:
    ================= 3 passed, 1 reverted, 0 failed in 2.12s =================
    同时生成:

    • htmlcov/index.html(Python 覆盖率)
    • reports/coverage.json(Solidity 覆盖率)
  6. 集成到 GitLab CI(国内常用)
    .gitlab-ci.yml
    stages: [test]
    brownie-test:
    stage: test
    image: python:3.10
    services:
    - trufflesuite/ganache-cli:v6.12.2
    variables:
    GANACHE_MNEMONIC: "test test test test test test test test test test test junk"
    before_script:
    - pip install eth-brownie pytest-xdist
    - brownie networks add Development ganache-ci host=http://ganache-cli:8545 chainid=1337
    script:
    - brownie test --network ganache-ci --coverage
    coverage: '/Solidity coverage: (\d+.\d+)%/'
    artifacts:
    reports:
    coverage_report:
    coverage_format: cobertura
    path: reports/coverage.xml

拓展思考

  1. 当测试用例过万时,ganache 易 OOM,可改用 hardhat-evm 或 geth --dev 模式,并通过 brownie 的 network priority 动态切换;
  2. 对升级able 合约,结合 pytest fixture 的工厂模式,在每次测试前重新 deploy ProxyAdmin + TransparentUpgradeableProxy,保证存储隔离;
  3. 使用 brownie 的 hypothesis 插件,可对 uint256 边界、递归调用、重入场景做 property-based testing,弥补人工用例盲区;
  4. 国内监管要求“核心合约必须 100% 分支覆盖”,可在 CI 阶段加一道阈值 gate:
    coverage json | jq '.totals.branches.percent' | awk '{exit $1<100}' || exit 1
  5. 若团队同时使用 Foundry,可通过 pytest 的 subprocess 调用 forge test,把 gas snapshot 结果回写到 pytest 的 <TestReport>.user_properties,实现双引擎统一报告。