【问题标题】:How to properly import between src and test modules如何在 src 和测试模块之间正确导入
【发布时间】:2021-08-14 08:42:07
【问题描述】:

我有一个项目要运行 root_dir> python ./src/main_file.py。当我想测试它时,我使用root_dir> python -m pytest,它会搜索test*.py*test.py格式的任何文件。

我有一个类似于以下的文件结构:

root_dir
├── src
│   ├── __init__.py
│   ├── main_file.py
│   ├── file1.py
│   ├── file2.py 
└── tests
    ├── __init__.py
    └── file1_test.py

我想要做的是创建一个测试文件来测试file1.py,但我得到了一个ModuleNotFoundError,因为我认为是以下原因,我不完全确定正确的方法是什么地址是。

在file1_test.py中:

./file1_test.py/
import src.file1 as file1

def test_file1():
  <do stuff>

问题发生在file1.py内部,其中:

./file1.py/
import file2.py

<blah blah blah>

pytest 以 ModuleNotFoundError: No module named 'file2' 失败。如果我将 file1.py 更改为:

./file1.py/ (EDITED)
import src.file2.py

<blah blah blah>

那么 pytest 就会成功运行。但是,如果我的 main_file.py 从同一个模块 (src) 中导入 file1.py,

./main_file.py/
import file1

<blah blah blah>

然后python ./src/main_file.py 将因该更改而失败并显示ModuleNotFoundError: No module named 'src.file2'。将file1改回原始文件将适用于main_file.py,但不适用于pytest,而且我陷入了一个循环。

我不知道我应该做些什么不同的事情来让 main_file.py 和 pytest 的正常导入结构配合。我应该更改目录吗? main_file.py 应该在 src 之外吗?我想我会遇到类似的问题,如果 file1 正在导入 file2,则 src 之外的文件所期望的导入路径和 src 内部的文件所期望的导入路径总是会发生冲突。

【问题讨论】:

  • import src.file2.py 这是错字吗?另外,您在PYTHONPATH 中设置了什么?
  • 你需要配置你的 sys.path,或者使用 import src.file1 如果你将 src 重命名为 my_module 这样会更有意义。
  • @tchar 是对的。在您的 file1_test.py 中,它无法知道 file1 在哪里或 src 在哪里。 src 目录需要添加到 python 路径然后你应该使用import src.file1

标签: python


【解决方案1】:

有三种方法可以做你想做的事。

  1. 首选方式
root_dir
├── my_module
│   ├── __init__.py
│   ├── main_file.py
│   ├── file1.py
│   ├── file2.py 
└── tests
    ├── __init__.py
    └── file1_test.py

my_module 中的所有文件都应该像这样导入

from my_module.file1 import some_function

那么你不需要做任何黑客攻击

  1. 保持src 并假设语句类似
from src.file1 import some_function

不是你想要的,你需要修改你的测试

import os
import sys
sys.path.insert(0, os.path.abspath('src')
  1. 不修改 src,不修改测试:用
  2. 运行测试
PYTHONPATH=path/to/src pytest

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 2012-05-04
    • 2018-10-04
    • 2011-06-13
    • 2018-06-10
    • 1970-01-01
    • 2020-06-05
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多