不会——但极大概率会卡在 ImportError: cannot import name 'Iterable' from 'collections',因 Python 3.13 移除旧别名,而 pytest 插件或依赖库(如 pluggy、packaging)尚未适配。

直接运行 pytest 会报 ImportError 吗?
不会——但极大概率会卡在 ImportError: cannot import name 'Iterable' from 'collections' 或类似错误。Python 3.13 彻底移除了 collections.Iterable、collections.Mapping 等旧别名,而很多 pytest 插件(如 pytest-cov、pytest-xdist)或旧版 pytest 自身仍依赖它们。
根本原因不是 pytest 本身,而是它间接依赖的库(比如 pluggy、packaging、attrs)尚未适配 3.13 的 collections 重构。你看到的报错位置可能在 pluggy 的 hook 注册逻辑里,实际源头却是 Python 标准库变更。
- 确认当前 pytest 版本:
pip show pytest—— 若低于8.2.0,基本无法启动 - 强制升级到最新稳定版:
pip install --upgrade pytest>=8.2.0 - 同时升级关键依赖:
pip install --upgrade pluggy>=1.5.0 packaging>=24.0 attrs>=23.2.0
为什么 pytest -v 仍提示 SyntaxWarning 或 DeprecationWarning?
因为 Python 3.13 默认启用更严格的语法检查,且部分警告已升级为错误(尤其在 -Werror 模式下)。常见触发点包括:
-
asyncio.async()别名调用(已被彻底移除,需改用asyncio.create_task()) - 使用
yield但未标注生成器返回类型(如def f() -> Iterator[int]: yield 1缺少from typing import Iterator) - 测试中硬编码字符串格式化用
%或.format(),而项目启用了pylint或mypy的严格模式
建议在运行时显式抑制非致命警告(仅限调试阶段):python -W ignore::DeprecationWarning -m pytest -v。但生产迁移必须修复,不能靠屏蔽。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;
CI 中跑 pytest 总是失败:如何复现并定位真实问题?
本地能过、CI 失败,大概率是环境差异导致的隐式依赖问题。Python 3.13 预览版对 importlib 行为做了微调,某些动态导入路径(尤其涉及 __pycache__ 或命名空间包)会失效。
- 在 CI 脚本中加一行诊断命令:
python -c "import pytest; print(pytest.__version__)"; python -c "import importlib.util; print(importlib.util.spec_from_file_location.__code__.co_filename)" - 检查是否误用了
sys.path.insert(0, ...)干扰了模块解析顺序 —— 3.13 对重复路径去重更激进 - 禁用 pytest 缓存:
pytest --cache-clear -v,避免旧缓存污染新解释器行为 - 若用
pytest-xdist并行执行,先降级为单进程:pytest -n 0排除 fork 行为变更影响
测试通过但结果不准:asyncio 和 time 相关断言为何失效?
Python 3.13 的自适应解释器(Adaptive Interpreter)改变了事件循环调度粒度和 wall-clock 时间精度,尤其影响 asyncio.sleep(0)、time.time() 微秒级比较、以及 mock 时间相关的测试。
- 避免直接断言
time.time()差值,改用freezegun或pytest-freezegun固定时间上下文 - 异步测试中慎用
asyncio.sleep(0)做“让出控制权”——改用await asyncio.yield_()(3.12+ 引入,3.13 全面支持) - 检查是否依赖
loop.time()返回值做逻辑分支,该值在 3.13 中可能因调度优化出现微小偏移
最易被忽略的是:pytest 的 timeout 插件在 3.13 下默认超时判定逻辑已变更,若测试中用了 @pytest.mark.timeout,必须确认插件版本 ≥ 2.3.0 并重测临界超时场景。

















