执行pytest --collect-only时触发TypeError:'NoneType'对象不可调用
问题:
pytest --collect-only 执行后抛出gevent相关TypeError 执行pytest --collect-only命令时,PyTest可正常收集测试用例,但会终止并抛出以下报错:
Traceback (most recent call last): File "/data/anaconda/envs/env/lib/python3.9/logging/__init__.py", line 831, in _removeHandlerRef File "/data/anaconda/envs/env/lib/python3.9/logging/__init__.py", line 225, in _acquireLock File "/data/anaconda/envs/env/lib/python3.9/threading.py", line 156, in acquire File "/data/anaconda/envs/env/lib/python3.9/site-packages/gevent/thread.py", line 74, in get_ident TypeError: 'NoneType' object is not callable
已尝试升级相关依赖、移除部分测试用例,但报错仍未解决。
解决方案
这个错误是gevent的monkey patch与Python标准库logging模块在线程锁处理上的冲突导致的——gevent.thread.get_ident被意外置为None,进而触发TypeError。可以尝试以下几种解决方式:
- 修复gevent的get_ident指向:在项目的
conftest.py中添加以下代码,强制将gevent的get_ident绑定到Python原生的threading.get_ident:
import gevent.thread import threading gevent.thread.get_ident = threading.get_ident
调整gevent monkey patch时机:如果测试代码中有手动执行
gevent.monkey.patch_all()的操作,确保该操作在pytest初始化完成后再执行,或者避免patch threading模块(改为gevent.monkey.patch_all(thread=False))。使用pytest-gevent插件协调:安装
pytest-gevent插件自动处理兼容性问题,执行命令安装:
pip install pytest-gevent
之后运行pytest时添加--gevent参数:
pytest --collect-only --gevent
- 降级gevent到兼容版本:Python 3.9与部分新版本gevent存在兼容性问题,尝试降级到稳定兼容版本:
pip install gevent==21.12.0
内容的提问来源于stack exchange,提问作者corey
相关产品推荐
相关产品推荐

