如何用 pytest 启动 Ganache 并自动挖矿?

解读

国内区块链项目普遍使用以太坊本地链做集成测试,Ganache 因一键启停、秒级出块成为首选。面试官问“pytest 启动 Ganache 并自动挖矿”,本质考察三件事:

  1. 能否在测试生命周期里拉起/关闭 Ganache 进程,端口不冲突;
  2. 能否让 Ganache 持续自动产块(--miner.blockTime 0 或 --miner.blockTime 1),而不是手动 evm_mine;
  3. 能否把链信息(RPC 端口、链 ID、助记词)注入到测试用例,做到“测试即服务”。

答不到“生命周期管理”和“fixture 依赖注入”两点,基本会被判“只能写单元测试,不会写集成测试”。

知识点

  1. pytest fixture 作用域:session 级只启停一次 Ganache,module/class/function 级按需隔离。
  2. subprocess.Popen + psutil 确保跨平台杀进程,避免僵尸端口占用。
  3. Ganache CLI 参数:
    --server.port 动态选端口(pytest-xdist 并行时必做);
    --miner.blockTime 0 或 1 实现自动挖矿;
    --chain.chainId 1337 固定链 ID;
    --wallet.mnemonic 固定助记词,方便测试账号复现。
  4. web3.py 连接检测:轮询 eth_blockNumber 直到返回最新块高,确保链就绪再 yield。
  5. 清理策略:atexit 与 request.addfinalizer 双保险,CI 异常退出也能杀进程。
  6. 并发安全:使用 filelock 对端口文件加锁,防止 pytest-xdist 多 worker 重复占用。

答案

给出一个可直接落地的 conftest.py 片段,满足“一键启停 + 自动挖矿 + 端口隔离 + 并行安全”。

# conftest.py
import os, subprocess, time, socket, signal, psutil, json, tempfile, filelock
import pytest
from web3 import Web3

def _pick_free_port():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('', 0))
        return s.getsockname()[1]

@pytest.fixture(scope="session")
def ganache():
    # 1. 选端口并加文件锁,防止 xdist 冲突
    lock_path = os.path.join(tempfile.gettempdir(), "ganache_port.lock")
    with filelock.FileLock(lock_path):
        port = _pick_free_port()
        rpc_url = f"http://127.0.0.1:{port}"

    # 2. 启动 Ganache
    cmd = [
        "ganache",
        "--server.port", str(port),
        "--chain.chainId", "1337",
        "--chain.networkId", "1337",
        "--wallet.mnemonic", "myth like bonus scare over problem client lizard pioneer submit female collect",
        "--miner.blockTime", "1",          # 自动挖矿,每 1 秒一块
        "--miner.defaultGasPrice", "0x4A817C800",  # 20 gwei
        "--wallet.totalAccounts", "10",
        "--logging.verbose", "false"
    ]
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # 3. 等待链就绪
    w3 = Web3(Web3.HTTPProvider(rpc_url))
    for _ in range(30):
        try:
            if w3.is_connected() and w3.eth.block_number > 0:
                break
        except Exception:
            pass
        time.sleep(0.5)
    else:
        _kill_proc(proc)
        raise RuntimeError("Ganache 启动超时")

    # 4. 构造上下文
    ganache_info = {"rpc": rpc_url, "chain_id": 1337, "proc": proc}

    yield ganache_info

    # 5. 清理
    _kill_proc(proc)

def _kill_proc(proc):
    parent = psutil.Process(proc.pid)
    for child in parent.children(recursive=True):
        child.kill()
    parent.kill()
    parent.wait(timeout=5)

测试用例侧零感知,直接注入即可:

def test_deployment(ganache):
    w3 = Web3(Web3.HTTPProvider(ganache["rpc"]))
    assert w3.eth.block_number >= 1

运行 pytest -n auto 可并行,端口互不冲突,Ganache 全程自动挖矿。

拓展思考

  1. 速度优化:把 scope="session" 改成 scope="module",每模块重启,可隔离脏数据,但耗时翻倍;用 ganache --database.dbPath 做快照还原,兼顾速度与隔离。
  2. 账号预充值:在 fixture 里提前部署 WETH、USDC 等 ERC20 合约,把地址写进 ganache_info,测试用例直接 w3.eth.send_transaction 无需重复部署。
  3. 异常场景:用 pytest-raises 结合 ganache-cli --fork 做主网分叉测试,模拟“余额不足”、“gas 超限”等链上异常。
  4. CI 集成:GitHub Actions / GitLab CI 中预装 node 与 ganache 全局包,缓存 ~/.npm;若用 Docker,可官方镜像 trufflesuite/ganache:latest,把端口映射到 8545,pytest 侧通过环境变量 GANACHE_RPC 接入,实现“本地与 CI 同一套代码”。