You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在tox中创建两个依赖库版本不同的测试环境

解决tox同一Python版本下测试不同依赖版本的问题

你的问题出在配置的语法细节和依赖顺序上,导致typeguard的版本约束没有生效。以下是修正后的配置方案和关键调整说明:

方案一:独立环境配置(直观不易错)

直接定义两个独立的测试环境,分别对应typeguard v2和v3:

[tox]
requires = tox>=4
env_list = py{37,38,39,310,311}, typeguard-v2, typeguard-v3

[testenv]
description = 运行单元测试
deps = -rrequirements.txt
commands = pytest {posargs:tests}

[testenv:typeguard-v2]
description = 使用typeguard v2.x运行测试
base_python = python3.10
deps =
    typeguard<3.0.0
    -rrequirements.txt
commands = pytest {posargs:tests}

[testenv:typeguard-v3]
description = 使用typeguard v3.x运行测试
base_python = python3.10
deps =
    typeguard>=3.0.0
    -rrequirements.txt
commands = pytest {posargs:tests}

方案二:参数化环境配置(简洁高效)

利用tox的参数化特性,用一套配置生成两个环境:

[tox]
requires = tox>=4
env_list = py{37,38,39,310,311}, typeguard-{2,3}

[testenv]
description = 运行单元测试
deps = -rrequirements.txt
commands = pytest {posargs:tests}

[testenv:typeguard-]
description = 使用typeguard v{env:VERSION}运行测试
base_python = python3.10
deps =
    {env:VERSION:2}: typeguard<3.0.0
    {env:VERSION:3}: typeguard>=3.0.0
    -rrequirements.txt
commands = pytest {posargs:tests}
parametrize =
    VERSION; 2,3

关键调整点

  1. 明确环境标识:避免原配置中typeguard_{v2,v3}的模糊写法,改用清晰的环境命名或参数化定义,确保tox能正确生成两个独立环境。
  2. 固定Python版本:给typeguard测试环境直接指定base_python = python3.10,确保两个环境使用同一Python版本。
  3. 依赖顺序优化:将typeguard的版本约束写在-rrequirements.txt之前,这样即使requirements.txt未指定typeguard版本,也会优先应用明确的版本约束;如果反过来写,pip会自动将typeguard调整到符合约束的版本,两种顺序都可行,但前者更直观。

验证方法

  • 运行tox -av查看所有生成的测试环境,确认typeguard-v2和typeguard-v3存在。
  • 运行tox -e typeguard-v2 -- pip freeze | grep typeguard,检查输出的版本是否符合<3.0.0的要求,同理验证v3环境。

内容的提问来源于stack exchange,提问作者Ilya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:03:36