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

如何解决Pytest测试本地未安装模块时的导入冲突问题?

我试过pytest.ini、test目录下的__init__.py、conftest.py等方案,都没解决问题。项目结构如下:

.
├── module
│   ├── bar.py
│   ├── foo.py
│   ├── __init__.py
│   └── __main__.py
└── tests
    ├── __init__.py
    └── test_module.py

模块可运行,测试失败

各文件内容如下:

module/bar.py:

def bar():
    return "bar"

module/foo.py:我怀疑导入方式有误...后续详述

from bar import bar

def foo():
    value = bar()
    print(value)
    return value

module/__init__.py:空文件

module/__main__.py:

from foo import foo

foo()

执行python module能正常输出bar,但运行pytest .或python -m pytest时,测试文件tests/test_module.py报错:

_________________________________________________________________________________________________________________________________ ERROR collecting tests/test_module.py __________________________________________________________________________________________________________________________________
ImportError while importing test module '/home/susensio/Projects/sandbox/pytest/tests/test_module.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.11/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_module.py:1: in <module>
    from module import foo
E   ModuleNotFoundError: No module named 'module'

此时模块可运行,但测试失败。


模块运行失败,测试正常

修改foo.py为相对导入:

from .bar import bar

def foo():
    value = bar()
    print(value)
    return value

修改后测试能正常运行,但执行python module时报错:

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/home/susensio/Projects/sandbox/pytest/module/__main__.py", line 1, in <module>
    from foo import foo
  File "/home/susensio/Projects/sandbox/pytest/module/foo.py", line 1, in <module>
    from .bar import bar
ImportError: attempted relative import with no known parent package

其他相关问题的解决方案都没能解决这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:23:19