简体   繁体   English

用单元测试为Python项目导入模块/软件包的正确方法是什么?

[英]What is the correct way to import modules/packages for Python projects with unit tests?

I have the following directory structure: 我有以下目录结构:

|_ director_script.py
|_ app/
      |_ __init__.py
      |_ ParentClass.py
      |_ my_module/
                 |_ __init__.py
                 |_ MyClass.py
                 |_ MyClassTestCase.py

In my director_script.py I use MyClass and when I run python director_script.py the scripts run as expected without any error. 在我的director_script.py我使用MyClass ,当我运行python director_script.py ,脚本按预期运行,没有任何错误。 However, when I cd into my_module folder and run the unit tests using python -m unittest MyClassTestCase , I get the error: 但是,当我进入my_module文件夹并使用python -m unittest MyClassTestCase运行单元测试时,出现错误:

ModuleNotFoundError: No module named 'app'

This caused by the import statement in MyClass.py that is 这是由MyClass.py中的import语句引起的,即

from app.ParentClass import ParentClass

This import is fine when I run it from director_script.py and only happens with the unit test. 当我从director_script.py运行它时,这种导入很好,并且仅在单元测试中发生。

You should run from outside the app folder, any folder that has an __init__.py is a submodule in python. 您应该从app文件夹之外运行,任何具有__init__.py文件夹都是python中的子模块。 If you set the current working directory to my_module, it cannot see the app module, unless you have the folder path corresponding to the app folder set in the PYTHONPATH environment variable 如果将当前工作目录设置为my_module,则它将看不到应用程序模块,除非您具有与PYTHONPATH环境变量中设置的应用程序文件夹相对应的文件夹路径

在顶层文件夹中添加一个名为__init__.py的文件

A bit of a kludge, but this is how I usually do it: 有点纠结,但这是我通常的做法:

import sys
sys.path.append('../app')

Or under Windows: 或在Windows下:

sys.path.append('..\\app')

This needs to come before your module import, of course. 当然,这需要在模块导入之前进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在python库中导入模块的正确方法是什么? - What is the correct way to import modules in python library? 在 Python 的父目录中使用其他模块的模块(在子目录中)编写单元测试的正确方法是什么 - What is the proper way to write unit tests on modules (in subdirectories) which use other modules in the parent directory in Python Python:“导入”更喜欢什么-模块或软件包? - Python: what does “import” prefer - modules or packages? 在python包中包含本地化的正确方法是什么? - What is the correct way to include localisation in python packages? 当我在 python 中编写自己的模块时,导入模块的正确方法是什么? - What is the correct way to import modules when I'm writing my own module in python? 为使用`python -m zipapp`创建的独立应用程序导入模块的正确方法是什么? - What is the correct way to import modules for standalone app created using `python -m zipapp`? 在python中导入模块的最pythonic方法是什么 - What is the most pythonic way to import modules in python 如何知道需要在Python代码中导入哪些包/模块 - How to know what packages/modules you need to import in Python code Python 导入优先级:包还是模块? - Python import precedence: packages or modules? 单元测试如何导入他们测试的模块? - How do unit tests import the modules they test?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM