【问题标题】:Python unittest with test/ and src/ not finding src modules带有 test/ 和 src/ 的 Python unittest 没有找到 src 模块
【发布时间】:2025-12-30 08:05:04
【问题描述】:

我有一个简单的目录结构:

proj/
    src/
        __init__.py
        foo.py
        bar.py
    test/
        __init__.py
        test_foo.py

test_foo.py

import unittest

import sys
sys.path.append('../src')

from src import foo

class TestFoo(unittest.TestCase):

  def test_foo(self):
    foo.start()


if __name__ == '__main__':
    unittest.main()

foo.py

import bar

def start():
  bar.do_stuff()

在运行我的测试时(我正在使用 vscode),我收到以下错误:

Failed to import test module: test_foo
Traceback (most recent call last):
  File "~/.pyenv/versions/3.8.6/lib/python3.8/unittest/loader.py", line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File "~/.pyenv/versions/3.8.6/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "~/proj/test/test_foo.py", line 6, in <module>
    from src import foo
  File "~/proj/src/foo.py", line 1, in <module>
    import bar
ModuleNotFoundError: No module named 'bar'

不知道为什么在导入 src/foo 时测试找不到 src/bar

【问题讨论】:

  • 从 test_foo.py 你使用“from src import foo”然后从 foo.py 你只使用“import bar”。我会怀疑你的 proj/src/__init__.py。
  • __init__.py 只是空文件

标签: python visual-studio-code python-unittest


【解决方案1】:

您的bar.py 文件中有什么内容?只是do_stuff() 函数?还是do_stuff()函数是对象bar的方法?

根据上述问题的答案,尝试在您的 foo.py 文件中执行以下操作:

from proj.src.bar import [name of function you're testing here]

在您的具体情况下,如果do_stuff() 是一个独立函数,则如下所示:

from proj.src.bar import do_stuff

然后您的foo.py 文件将是:

from proj.src.bar import do_stuff

def stuff():
  do_stuff()

但是,如果do_stuff()bar 对象的一个​​方法,它可能是这样的,虽然不知道bar.py 文件的内容很难判断:

from proj.src.bar import bar

然后您的 foo.py 文件将与您现在的方式相似:

from proj.src.bar import bar

def stuff():
  bar.do_stuff()

我最近在尝试将一个相邻文件导入另一个文件时遇到了类似的问题。这个link 也帮助了我。

【讨论】:

    【解决方案2】:

    试试from src import bar,而不是import bar

    from src import bar
    
    
    def start():
        bar.do_stuff()
    
    

    通知

    请记住,您只是在测试中调整了路径。您不希望测试工作,但应用程序失败,因为您忘记在某些时候调整应用程序中的路径。

    【讨论】:

      【解决方案3】:

      两个变化:

      1. from src import barfoo.py

      2. test_foo.py 中导入模块之前,添加

         import sys  
         sys.path.append("./")
        

      那么你应该可以成功运行代码了。

      【讨论】: