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

运行pytest时导入src文件夹触发ModuleNotFoundError的原因

问题:运行pytest时出现ModuleNotFoundError找不到src模块

项目结构

unit_testing/
├── src/
│   └── my_functions.py
└── tests/
    └── test_my_functions.py

src/my_functions.py 代码

def adding_pos(a, b, c):
    if a < 0 or b < 0 or c < 0:
        output = f'function needs positive numbers'
    else:
        output = a + b + c
    return output

tests/test_my_functions.py 代码

# import libs
import pytest
from src.my_functions import adding_pos


# %% test
class TestAddingPos(object):
    def test_adding(self):
        assert adding_pos(2, 5, 6) == 13

    def test_adding_neg(self):
        assert adding_pos(-1, 2, 3) == 'function needs positive numbers'

问题详情

进入tests文件夹后运行pytest,持续出现ModuleNotFoundError,提示找不到src模块。但导入语句原本是有效的,想知道原因及解决方法。

原因及解决方法

原因

Python的模块查找路径(sys.path)默认包含当前工作目录。当你进入tests文件夹运行pytest时,当前工作目录变成了unit_testing/tests/,而src文件夹在它的上级目录unit_testing/,所以Python找不到src模块。

之前导入语句有效,大概率是因为你当时的工作目录是unit_testing/,此时src在当前目录下,所以能被正常识别。

解决方法

有几种简单可行的处理方式:

  1. 在项目根目录运行pytest
    直接回到unit_testing/文件夹,执行命令pytest tests/,这样Python能在当前目录找到src模块。

  2. 修改测试文件的模块查找路径
    在test_my_functions.py的开头添加以下代码,将项目根目录加入Python的模块查找路径:

    import sys
    from pathlib import Path
    sys.path.append(str(Path(__file__).parent.parent))
    

    这样不管从哪个目录运行测试,都能正确找到src模块。

  3. 设置PYTHONPATH环境变量
    在运行pytest前,把项目根目录添加到PYTHONPATH:

    • Linux/macOS:
      export PYTHONPATH=/path/to/unit_testing:$PYTHONPATH
      pytest
      
    • Windows(命令提示符):
      set PYTHONPATH=C:\path\to\unit_testing;%PYTHONPATH%
      pytest
      
    • Windows(PowerShell):
      $env:PYTHONPATH = "C:\path\to\unit_testing;$env:PYTHONPATH"
      pytest
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:27:13