从兄弟目录导入模块以用于 py.test

Importing modules from a sibling directory for use with py.test

我在将我打算 运行 和 py.test 的任何内容导入我的测试文件时遇到问题。

我的项目结构如下:

/ProjectName
|
|-- /Title
|    |-- file1.py
|    |-- file2.py
|    |-- file3.py
|    |-- __init__.py
|
|-- /test
|    |-- test_file1.py

我无法在 test_file1.py 文件中获得任何与 pytest 一起使用的导入语句,因此我目前只是尝试使用在 file_1.py 中声明的变量并在 test_file1.py 是 运行.

file1.py 包含:

file1_variable = "Hello"

test_file1.py 包含:

import sys
import os
sys.path.append(os.path.abspath('../Title'))
import file1

def test_something():
    assert file1.file1_variable == "Hello"

print(file1.file1_variable)

我的测试文件中的导入语句取自 ,它通过编辑 PYTHONPATH 变量来工作。这允许我 运行 test_file1.py 脚本并成功执行 print 语句。

但是,尝试从 /ProjectName 目录 运行 py.test 时出现错误 ImportError: No module named 'file1'

有没有什么方法可以让我更好地构建事物,以便 pytest 成为可能?我需要向我的 __init__.py 文件添加内容吗?

不,您不需要向 __init__.py 添加任何内容。该文件告诉 python 将 parent 目录视为可以作为 described here 导入的模块。 只需将它添加到您的 Title 目录并像

一样导入它
from ..Tiltle.file import file1_variable

这里我们在目录中向上移动 1 个层次结构,就像 cd ..

注意 .. 用于从 test 目录获取标题包。如果您需要从 ProjectName 目录 运行 您的文件,您将必须执行

from Tiltle.file import file1_variable