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

在Databricks Notebook中执行pytest时遭遇ModuleNotFoundError:找不到'dummy_test'模块

在Databricks Notebook中执行pytest时遭遇ModuleNotFoundError:找不到'dummy_test'模块

看起来你遇到的问题核心是pytest无法定位到你的测试模块,同时Python也找不到需要导入的dummy模块,这通常和Databricks Notebook默认的工作目录以及Python模块搜索路径有关。咱们来一步步解决:

问题分析

从你给出的错误信息和目录结构来看:

  • 所有文件都在/Workspace/python_tests目录下,但pytest运行时的工作目录可能不是这个路径,导致它找不到dummy_test.py
  • 同时dummy_test.py里导入dummy模块时,Python的搜索路径也没包含/Workspace/python_tests,这也会引发导入问题(不过当前错误先出在找不到测试模块本身)

解决方案

你可以修改pyTestRunner笔记本的代码,通过设置正确的工作目录和添加模块搜索路径来解决:

%pip install pytest

import pytest
import sys
import os

# 定义你的测试目录路径
test_directory = "/Workspace/python_tests"

# 将测试目录添加到Python模块搜索路径,确保能导入dummy模块
sys.path.append(test_directory)
# 切换工作目录到测试目录,让pytest能找到测试文件
os.chdir(test_directory)

# Skip writing pyc files on a readonly filesystem.
sys.dont_write_bytecode = True

# 运行pytest,此时当前目录就是测试目录,直接用"."即可
retcode = pytest.main([".", "-v", "-p", "no:cacheprovider"])

# Fail the cell execution if there are any test failures.
assert retcode == 0, "The pytest invocation failed. See the log for details."

另一种简化方案(直接指定测试文件路径)

如果你不想切换工作目录,也可以直接把测试文件的绝对路径传给pytest:

%pip install pytest

import pytest
import sys

# Skip writing pyc files on a readonly filesystem.
sys.dont_write_bytecode = True

# 直接指定测试文件的完整路径
retcode = pytest.main(["/Workspace/python_tests/dummy_test.py", "-v", "-p", "no:cacheprovider"])

# Fail the cell execution if there are any test failures.
assert retcode == 0, "The pytest invocation failed. See the log for details."

额外注意点

  • 确保你的文件名和模块名符合Python规范(不能有空格、特殊字符,这里dummy.py和dummy_test.py都是合规的)
  • 如果后续还有导入dummy模块的问题,记得把/Workspace/python_tests添加到sys.path里,就像第一个方案那样

备注:内容来源于stack exchange,提问作者marcin2x4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 13:23:02