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

使用uvx pytest无法导入pyproject.toml中声明的模块问题

解决ntplib依赖无法被uvx pytest识别的问题

问题背景

项目的pyproject.toml依赖定义如下:

dependencies = [
    "numpy>=1.0.0,<2.0.0",
    "pandas~=2.2.2",
    "tqdm~=4.66.4",
    "scipy~=1.14.0",
    "tensorflow==2.15.0",
    "h5py==3.11.0",
    "ntplib>=0.4.0",
]

运行uvx pytest时出现以下错误:

from src.client.client import Client
  File "/xxx/src/client/client.py", line 5, in <module>
    import ntplib
ImportError: Error importing plugin "tests.fixtures.client_fixture": No module named 'ntplib'

解决步骤

1. 确认依赖是否完成安装

先检查当前环境中是否存在ntplib:

pip list | grep ntplib

如果无输出,说明依赖未安装,执行以下命令重新同步项目依赖:

uv sync

若使用pip管理虚拟环境:

pip install -e .

2. 确保uvx使用正确的虚拟环境

uvx不会自动激活虚拟环境,需先手动激活再执行命令:

# Linux/macOS
source .venv/bin/activate
uvx pytest

# Windows
.venv\Scripts\activate
uvx pytest

也可直接调用虚拟环境内的pytest,跳过uvx:

# Linux/macOS
.venv/bin/pytest

# Windows
.venv\Scripts\pytest.exe

3. 检查依赖分组是否正确

若pyproject.toml中存在可选依赖或测试依赖分组,确认ntplib未被错误归类。如果ntplib是测试场景专用,需将其放到测试依赖分组:

[project.optional-dependencies]
test = [
    "pytest",
    "ntplib>=0.4.0"
]

然后安装测试依赖:

uv sync --extra test

4. 重建虚拟环境

若环境存在损坏,删除后重新创建:

# Linux/macOS
rm -rf .venv
uv venv
uv sync
source .venv/bin/activate
uvx pytest

# Windows
rmdir /s .venv
uv venv
uv sync
.venv\Scripts\activate
uvx pytest

5. 排查测试插件的导入逻辑

错误提示来自测试插件导入,检查tests/fixtures/client_fixture.py的导入语句,确认是否存在路径错误,或是否在fixture中提前加载了依赖ntplib的模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:00:57