如何为合约部署失败写断言?

解读

在国内真实面试中,面试官问“如何为合约部署失败写断言”并不是想听你背诵 assert 语法,而是想确认三件事:

  1. 你是否知道“部署失败”在 Python 世界里会表现为哪种异常或返回值;
  2. 你是否能用 Pytest 的断言机制精准捕获并表达“失败”这一负面场景;
  3. 你是否能把链上错误信息(回滚原因、revert message、gas 不足、字节码超限等)映射成 Python 可断言的对象,同时保证用例稳定、可维护、可 CI。

因此,回答必须围绕“异常类型选择 + 断言写法 + 失败信息提取”展开,并给出可直接落地的代码模板。

知识点

  1. 合约部署的两种主流 Python 通道

    • web3.py:直接 rpc 部署,失败时抛 ContractLogicError 或 TransactionFailed
    • brownie / ape / foundry-py 等框架:在 project.deploy 层面再封一层,失败时抛 VirtualMachineError 或自定义 DeployError
  2. Pytest 断言负面场景的两种范式

    • with pytest.raises(ExpectedException) as excinfo: 捕获指定异常
    • with pytest.raises(ExpectedException, match="必须包含的 revert 原因"): 同时校验错误信息
  3. 链上回滚消息的提取技巧

    • 0x08c379a0 开头:标准 revert(string)
    • 0x4e487b71 开头:Panic(uint256)
    • 无 revert 原因:节点返回 execution reverted 字样,需解析 output 字段
  4. 参数化与标记

    • @pytest.mark.parametrize("salt", [0, 1]) 可一次性测“成功创建 2 次”与“重复 salt 导致失败”
    • @pytest.mark.require_network("ganache") 保证只在本地链跑,避免主网误伤
  5. 清理与隔离

    • 使用 module 级 fixture 部署一次,函数级用例只读不写,避免“前一个用例把 gas 打光”导致后续误报失败

答案

下面给出 web3.py 与 brownie 两套可直接粘进国内公司代码库的断言模板,任选其一即可讲清思路。

方案 A:web3.py 裸 rpc 场景

# test_deploy_fail.py
import pytest
from web3 import Web3
from web3.exceptions import ContractLogicError

GANACHE_URL = "http://127.0.0.1:8545"
w3 = Web3(Web3.HTTPProvider(GANACHE_URL))

# 故意把字节码写错,制造部署失败
BAD_BYTECODE = "0x6080604052348015600f57600080fd5b50ff"  # 末尾 0x50ff 非法指令

def test_deploy_reverts_with_invalid_bytecode():
    """部署失败必须抛 ContractLogicError,且回滚信息包含 'invalid opcode'"""
    with pytest.raises(ContractLogicError, match="invalid opcode"):
        w3.eth.contract(bytecode=BAD_BYTECODE).constructor().transact()

方案 B:brownie 框架场景

# test_deploy_fail.py
import pytest
import brownie

@pytest.fixture(scope="module")
def owner(accounts):
    return accounts[0]

def test_deploy_fails_when_constructor_require_not_met(owner):
    """构造函数 require(msg.sender != 0) 会失败,应抛 VirtualMachineError"""
    with brownie.reverts("Ownable: new owner is the zero address"):
        # 故意把地址填 0,触发 require 失败
        brownie.compile_source("""
pragma solidity ^0.8.0;
contract Foo {
    constructor(address newOwner) {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
    }
}
        """).deploy("0x0000000000000000000000000000000000000000", {"from": owner})

要点讲解(面试时口述即可):

  1. 用 pytest.raises 精准圈定异常类型,避免“任何异常都算通过”的伪阳性;
  2. 用 match= 或 brownie 的 reverts() 二次校验 revert 原因,防止节点升级后异常文本漂移;
  3. 如果公司用私有链,务必在 pytest_configure 里加 chain_id 检查,防止误连主网烧真钱;
  4. 部署失败用例必须单独放 test_deploy_fail.py,与成功用例隔离,减少 gas 竞争导致的偶发失败。

拓展思考

  1. 如何断言“gas 不足”导致的部署失败?
    先 estimateGas 拿到基准值,再在 transact({"gas": baseline - 1}) 里故意给少,断言 ValueError 且 message == "intrinsic gas too low"。

  2. 如何断言“字节码 > 24 KB”导致的部署失败?
    用 solc --optimize 编译出超大合约,断言 ContractLogicError 的 data 字段包含 0x4e487b710000000000000000000000000000000000000000000000000000000000000022(Panic 0x22 代码)。

  3. 如何在 CI 里跑部署失败用例而不污染全局状态?
    在 conftest.py 里写 autouse=True 的 ganache fixture,用 --no-mining 启动即挖即停,每个失败用例后自动 evm_snapshot / evm_revert,保证链高度回滚到初始点。