从同级目录导入模块以与 py.test 一起使用

Shi*_*a91 5 python python-import importerror pytest python-3.x

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

我有一个项目结构如下:

/ProjectName
|
|-- /Title
|    |-- file1.py
|    |-- file2.py
|    |-- file3.py
|    |-- __init__.py
|
|-- /test
|    |-- test_file1.py
Run Code Online (Sandbox Code Playgroud)

我无法在test_file1.py文件中使用 pytest 获得任何导入语句,因此目前我只是尝试使用声明的变量file_1.py并在test_file1.py运行时将其打印出来。

file1.py 包含:

file1_variable = "Hello"
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

但是,尝试py.test/ProjectName目录运行会给我一个错误提示ImportError: No module named 'file1'

有什么方法可以让我更好地构建事物,以便 pytest 成为可能?我需要在我的__init__.py文件中添加一些东西吗?

dni*_*t13 2

不,您不需要向 中添加任何内容__init__.py该文件告诉 Python 将父目录视为可以按照此处所述导入的模块。只需将其添加到您的 Title 目录并像这样导入

from ..Title.file import file1_variable
Run Code Online (Sandbox Code Playgroud)

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

注意..用于从测试目录访问标题包。如果您需要从ProjectName目录运行文件,则必须执行以下操作

from Title.file import file1_variable
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

4788 次

最近记录:

9 年,6 月 前