
Standardize test image fixture loading for COCO images
快速结论:该问题发生在运行 Transformers 测试时,部分测试用例(如 test_image_processing_*.py, test_modeling_*.py)直接通过 httpx.get() 或 requests.get() 下载 COCO 测试图片,绕过了 utils/fetch_hub_objects_for_ci.py 中定义的 url_to_local_path() 逻辑和数据集预取机制。优先排查测试中是否存在直接调用 httpx.get(url, ...) 或 requests.get(url, ...) 加载 COCO 图片的代码,并将其替换为统一的 load_test_image() 测试辅助函数。
问题场景
用户在运行 Transformers 测试时,例如在本地执行 pytest tests/test_image_processing_common.py 或特定模型测试(如 tests/models/vitpose/test_image_processing_vitpose.py),测试中直接使用 httpx.get() 或 requests.get() 从 http://images.cocodataset.org/... 下载 COCO 图片,导致 CI 预取机制失效,本地或部分测试运行中仍然直接访问外部源。
报错原文
# 错误模式示例(非单一固定报错,而是代码风格问题):
# 直接 httpx.get() 用例(约9处):
# tests/test_image_processing_common.py:180
# tests/models/vitpose/test_image_processing_vitpose.py:238
# tests/models/flava/test_image_processing_flava.py:409
# ...
# 直接 requests.get() 用例(约28处):
# tests/models/aimv2/test_modeling_aimv2.py:482
# tests/models/video_llama_3/test_image_processing_video_llama_3.py:300
# tests/models/eomt/test_modeling_eomt.py:178
# ...
# 以上所有用例均应替换为统一 helper
# 典型的坏代码模式:
Image.open(io.BytesIO(httpx.get(url, follow_redirects=True).content))
Image.open(requests.get(url, stream=True).raw)
原因分析
项目中的测试代码普遍直接使用 httpx 或 requests 库从 COCO 原始 URL(images.cocodataset.org)下载测试图片,而非通过 utils/fetch_hub_objects_for_ci.py 提供的 url_to_local_path() 函数进行本地缓存或预取。这导致 CI 环境虽然可以成功预取数据,但本地或部分测试运行时仍然直接访问外部网络资源,造成依赖不稳定、网络超时或数据不可用问题。Issue 提出在 tests/test_processing_common.py 中新增一个 load_test_image() 辅助函数,统一调用 url_to_local_path() 和 load_image(),并将所有直接 HTTP 调用替换为使用该辅助函数。
环境排查
- 确认测试环境网络能够正常访问
https://huggingface.co/datasets/hf-internal-testing/fixtures-coco(建议使用的 Hub 镜像地址)。 - 检查
tests/test_processing_common.py中是否已导入或定义url_to_local_path和load_image。 - 确认
utils/fetch_hub_objects_for_ci.py中存在url_to_local_path()函数。 - 检查对应测试文件是否存在直接调用
httpx.get()或requests.get()的代码(参考 Issue 中列出的文件及行号)。
解决步骤
- 新增辅助函数:在
tests/test_processing_common.py文件中(建议放在url_to_local_path导入附近)添加load_test_image()函数:def load_test_image(url: str): return load_image(url_to_local_path(url))注意:
url_to_local_path需要从utils.fetch_hub_objects_for_ci导入。 - 替换直接 HTTP 调用:将所有使用
Image.open(io.BytesIO(httpx.get(url, follow_redirects=True).content))或Image.open(requests.get(url, stream=True).raw)的测试代码,统一替换为:image = load_test_image(url)需替换的完整文件列表请参考 Issue 正文中“Direct
httpx.get/requests.getCOCO call sites to update”部分(约9处 httpx 调用 + 约28处 requests 调用)。 - 更新 URL 源(可选但推荐):对于 COCO 测试图片,将 URL 指向
hf-internal-testing/fixtures-coco数据集下的镜像地址,而非images.cocodataset.org。 - 同步预取配置:确保
utils/fetch_hub_objects_for_ci.py中添加了与 tests 使用的 URL 匹配的条目,以保证 CI 预取一致性。
验证方法
运行被修改的测试文件,确认不再有直接 httpx.get() 或 requests.get() 调用 COCO 原始 URL,且图片加载正常通过 url_to_local_path() 机制。可执行以下命令(示例)验证测试是否通过:
pytest tests/models/vitpose/test_image_processing_vitpose.py -x -v
同时检查 utils/fetch_hub_objects_for_ci.py 中的预取日志,确认新 URL 已正确注册。



