如果它们在姐妹文件夹中,如何让我的 Python 单元测试导入已测试的模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2262546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:12:17  来源:igfitidea点击:

How to make my Python unit tests to import the tested modules if they are in sister folders?

pythonimportdirectorycode-organizationpython-unittest

提问by Jader Dias

I am still getting my head around the importstatement. If I have 2 folders in the same level:

我仍然在理解这个import声明。如果我在同一级别有 2 个文件夹:

  1. src
  2. test
  1. 源文件
  2. 测试

How to make the pyfiles in testimport the modules in src? Is there a better solution (like put a folder inside another?)

如何使py文件中的test导入模块src?有没有更好的解决方案(比如将文件夹放在另一个文件夹中?)

采纳答案by user151019

The code you want is for using src/module_name.py

您想要的代码用于使用 src/module_name.py

from src import module_name 

and the root directory is on your PYTHONPATH e.g. you run from the root directory

并且根目录在您的 PYTHONPATH 上,例如您从根目录运行

Your directory structure is what I use but woth the model name instead from src. I got this structure from J Calderone's blogand similar to A google blog

您的目录结构是我使用的,但模型名称来自 src。我从J Calderone 的博客中得到了这个结构,类似于A google blog

回答by Vadikus

Try this out:

试试这个:

import sys
import os
sys.path.append(os.path.join('..', 'src'))
import module_in_src_folder

edited to support any platform

编辑以支持任何平台

回答by quamrana

I have exactly the same situation as the OP with all the python projects I write:

对于我编写的所有 python 项目,我的情况与 OP 完全相同:

  • Project Folder
    1. src
    2. test
  • 项目文件夹
    1. 源文件
    2. 测试

All modules, whether in src, or test, or subfolders of these always use the form of importthat Mark shows in his answer:

所有模块,无论是在 src、test 还是它们的子文件夹中,都始终使用importMark 在他的回答中显示的形式:

from src import module_name

What I have done is write a module that sits in Project Folderand recursively discovers all the test modules within the test folder and gets unittest to run all those tests. As python is running in Project Folder, then modules are relative to the working directory.

我所做的是编写一个模块,该模块位于Project Folder并递归地发现 test 文件夹中的所有测试模块,并让 unittest 运行所有这些测试。当 python 在 中运行时Project Folder,模块是相对于工作目录的。

This means that the tests are just like any other client that wants to modules from src.

这意味着测试就像任何其他想要从src.