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

pytest无显式根包或模块时如何调用被测试代码中的方法

是否需要在src目录下创建__init__.py

不需要强制创建也能完成导入,Python 3.3+版本支持隐式命名空间包,空的__init__.py不是必须项,不过为了兼容旧版本Python,建议新增该空文件。


报错原因分析

  1. ModuleNotFoundError: No module named 'scr'是拼写错误,你把包名src误写为scr
  2. ImportError: cannot import name 'my_func1' from 'src'有两个原因:
    • 导入路径写法错误,你写的from src.myfile import my_func1中文件名拼写错误,实际文件名为my_file1.py,缺少下划线
    • 项目根目录没有加入Python的模块搜索路径,Python无法找到src包

具体解决方案

  1. 在my_file1_test.py的开头加入以下代码,将项目根目录加入模块搜索路径:
import sys
import os
# 拿到当前文件所在的tests目录的上级目录(项目根目录),加入搜索路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# 正确导入目标函数
from src.my_file1 import my_func1
  1. 修正测试代码的语法错误:assert res = 222是赋值操作,判断相等需要用双等号,改为assert res == 222
  2. (可选)在src目录下新增空的__init__.py文件,兼容旧版本Python。

最终测试代码示例

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.my_file1 import my_func1

def my_test1():
    res = my_func1(123)
    assert res == 222

运行测试的正确姿势

在项目根目录(src和tests文件夹的同级目录)执行测试命令:

  • 用pytest测试:python -m pytest tests/my_file1_test.py
  • 用Python自带unittest测试:python -m unittest tests.my_file1_test

使用-m参数运行会自动将当前目录加入Python的模块搜索路径,不需要额外修改sys.path也能正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:39:02