【问题标题】:From a test sub-directory, import module that inherits from a base abstract class从测试子目录中,导入从基本抽象类继承的模块
【发布时间】:2021-09-24 22:58:06
【问题描述】:

上下文

我正在尝试使用 pytest 运行单元测试,但是,测试文件无法找到模块,因为它们继承自抽象类。

更具体地说,我有以下目录结构:

project
|- __init__.py
|- project.py
|- JsonParser.py
|- Parser.py
|- tests
   |__init__.py
   |-test_JsonParser.py

JsonParser 具有以下导入:

from Parser import Parser

test_JsonParser.py 有以下导入:

from project.JsonParser import JsonParser

目标是从位于“项目”父目录中的 JsonParser 导入 JsonParser 类。当我尝试这个时,pytest 提出以下投诉:

ModuleNotFoundError: No module named 'Parser'

相关修复尝试

由于下面的线程,我选择了相应的目录结构。当没有抽象基类的继承时,Itt 工作得很好。我怀疑问题在于 JsonParser 如何导入 Parser。存在嵌套导入,pytest 无法协调这一点,即使从父目录运行也是如此

What is the best project structure for a Python application?

下面的主题是我最接近答案的主题,但它变成了先有鸡还是先有蛋的问题。如果我将路径设为相对路径,我将无法执行“project.py”,因为它将无法定位 Parser 的相对路径。

Python, import package module when class inherit abstract class

编辑:我应该提到我使用以下内容运行测试:

pytest tests/test_JsonParser.py

【问题讨论】:

    标签: python python-import


    【解决方案1】:

    看起来诀窍是按以下方式执行:

    Python -m pytest project/tests
    

    这样做会将根目录添加到搜索路径。仅使用 pytest 运行不包括 Python 文件搜索路径中的根目录。例如,当使用 'pytest' 执行测试时,Parser 将无法导入 JsonParser,因为解释器将仅在 Parser 目录中搜索 Parser.Parser。请注意 Parser.Parser 是相对于根目录的。如果根目录不在搜索路径中,解释器将不会找到同目录下其他文件导入的文件。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多