首页 > 解决方案 > 从父目录导入python

问题描述

我正在尝试使用以下目录结构对 filea.py 运行 pytest 测试

test_filea.py

from filea import *

def test_one_p_one():
    r = one_p_one()
    assert r == 2

文件.py

def one_p_one():
    return 1 + 1

当我必须遵循目录结构时,一切正常。

├── filea.py
├── test_filea.py

但是当我将我的测试移动到这样的子目录中时

├── filea.py
└── tests
    └── test_filea.py

我得到错误:

test_filea.py:1: in <module>
    from filea import *
E   ModuleNotFoundError: No module named 'filea'

我的编辑器似乎表明子目录中的文件中的导入是可以的..(没有读取波浪线)

但是当我使用“pytest”运行它时

我收到上面指出的错误。

标签: pytest

解决方案


根据有关测试发现的 pytest 文档,尝试如下:

  • 在目录中添加一个空__init__.py文件tests
  • 确保在运行时和pytest .的父目录是当前工作目录。filea.pytests

推荐阅读