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

如何解决独立tests目录下单元测试的mypy报错问题?

解决mypy无法识别src模块的问题

项目结构

rolutte
├── doc
├── README.rst
├── src
│   ├── outcome.py
│   └── __pycache__
├── tests
│   ├── context.py
│   ├── __init__.py
│   ├── __pycache__
│   └── test_outcome.py
└── tox.ini

相关代码片段

src/outcome.py

from dataclasses import dataclass, field

@dataclass(frozen=True)
class Outcome:
    ...

tests/context.py

import os
import sys

# Adding the project root directory to sys.path
sys.path.insert(0, os.path.abspath(
    os.path.join(os.path.dirname(__file__), '..')))

import src

tests/test_outcome.py

from .context import src
from src.outcome import Outcome

def test_outcome():
    ...

def test_outcome_win_amount():
    ...

mypy报错信息

对tests/context.py的报错:

tests/context.py:9: error: Cannot find implementation or library stub for module named "src"
tests/context.py:9: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 1 error in 1 file (checked 1 source file)

对tests/test_outcome.py的报错:

tests/context.py:9: error: Cannot find implementation or library stub for module named "src"
tests/test_outcome.py:6: error: Cannot find implementation or library stub for module named "src.outcome"
tests/test_outcome.py:6: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 2 errors in 2 files (checked 1 source file)

解决方法

以下几种方法都不需要将src安装为站点包,可按需选择:

1. 给src目录添加__init__.py文件

在src目录下创建空的__init__.py文件,让src成为合法的Python包:

src/
├── __init__.py
├── outcome.py
└── __pycache__

mypy会自动识别这个包,无需修改现有导入逻辑即可消除报错。

2. 配置mypy的Python路径

在项目根目录创建mypy.ini(或pyproject.toml),指定项目根目录为mypy的Python路径:

用mypy.ini:

[mypy]
pythonpath = .

用pyproject.toml:

[tool.mypy]
pythonpath = ["."]

配置后mypy会从项目根目录开始查找模块,即使src没有__init__.py也能识别(但推荐还是加__init__.py保持包结构规范)。

3. 简化测试文件的导入逻辑

可以去掉tests/context.py,直接在测试文件中调整路径并导入:
修改tests/test_outcome.py:

import sys
from pathlib import Path

# 将项目根目录加入sys.path
sys.path.append(str(Path(__file__).parent.parent))

from src.outcome import Outcome

def test_outcome():
    ...

def test_outcome_win_amount():
    ...

这种方式更直接,同时配合方法1添加src的__init__.py效果更好。

内容的提问来源于stack exchange,提问作者AK-CHP

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:45:43