Python3.10.9下tox的coverage环境为何因mypy命令触发失败?
问题:tox coverage环境执行完测试后错误执行mypy命令导致失败
项目结构
hello |_hello | |___init__.py | |_add.py |_tests | |___init__.py | |_test_add.py |_pyproject.toml
pyproject.toml中的tox配置片段
[tool.tox] legacy_tox_ini = """ [tox] env_list = py310, coverage, mypy, flake8 [testenv] description = run tests with pytest deps = pytest commands = pytest -v {posargs} [testenv:coverage] deps = pytest-cov commands = pytest --cov --cov-report term-missing --cov-report html --cov-append --cov-context=test --cov-fail-under=100 {posargs} [testenv:mypy] deps = mypy commands = mypy hello [testenv:flake8] deps = flake8 commands = flake8 hello """
报错现象
coverage环境完成测试且覆盖率达100%后,错误执行[testenv:mypy]命令,返回退出码2:
platform linux -- Python 3.10.9, pytest-7.2.1, pluggy-1.0.0 cachedir: .tox/coverage/.pytest_cache rootdir: /home/jonwebb/Code_Dev/Python/hello, configfile: pyproject.toml, testpaths: tests plugins: cov-4.0.0 collected 2 items tests/test_add.py .. [100%] ---------- coverage: platform linux, python 3.10.9-final-0 ----------- Name Stmts Miss Cover Missing ------------------------------------------------- conftest.py 0 0 100% hello/__init__.py 0 0 100% hello/add.py 4 0 100% tests/__init__.py 0 0 100% tests/test_add.py 12 0 100% ------------------------------------------------- TOTAL 16 0 100% Coverage HTML written to dir htmlcov Required test coverage of 100% reached. Total coverage: 100.00% ============================== 2 passed in 0.03s =============================== coverage: commands[1]>'[testenv:mypy]' coverage: exit 2 (0.00 seconds) /home/jonwebb/Code_Dev/Python/hello>'[testenv:mypy]' coverage: FAIL ✖ in 1.39 seconds
触发原因
问题出在legacy_tox_ini的多行字符串缩进处理上:[testenv:coverage]的commands块结束后,下一行的[testenv:mypy]因缩进与commands内的命令行一致,被tox误识别为coverage环境的第二条命令,而非独立的新环境定义。当tox尝试执行[testenv:mypy]这个不存在的命令时,自然返回退出码2导致失败。
修复方法
调整legacy_tox_ini中的缩进,确保每个环境定义([testenv:*])的层级与[tox]、[testenv]保持一致,避免被解析为前一个环境的命令:
修改后的tox配置:
[tool.tox] legacy_tox_ini = """ [tox] env_list = py310, coverage, mypy, flake8 [testenv] description = run tests with pytest deps = pytest commands = pytest -v {posargs} [testenv:coverage] deps = pytest-cov commands = pytest --cov --cov-report term-missing --cov-report html --cov-append --cov-context=test --cov-fail-under=100 {posargs} [testenv:mypy] deps = mypy commands = mypy hello [testenv:flake8] deps = flake8 commands = flake8 hello """
内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

