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

发布于 2024-08-21 01:04:10 字数 191 浏览 6 评论 0原文

我仍在思考 import 语句。如果我有2个同级文件夹:

  1. src
  2. test

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

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

  1. src
  2. test

How to make the py files in test import the modules in src?
Is there a better solution (like put a folder inside another?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

与君绝 2024-08-28 01:04:10

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

from src import module_name 

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

您的目录结构是我使用的,但模型名称而不是 src。我从 J Calderone 的博客 获得了这个结构

The code you want is for using 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

Your directory structure is what I use but with the model name instead from src. I got this structure from J Calderone's blog and

尤怨 2024-08-28 01:04:10

试试这个:

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

经过编辑以支持任何平台

Try this out:

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

edited to support any platform

清秋悲枫 2024-08-28 01:04:10

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

  • 项目文件夹
    1. 来源
    2. 测试

所有模块,无论是在 src、test 或它们的子文件夹中,总是使用 Mark 在他的回答中显示的 import 形式:

from src import module_name

我所做的是编写一个位于以下位置的模块在项目文件夹中,并递归地发现测试文件夹中的所有测试模块,并让unittest运行所有这些测试。由于 python 在项目文件夹中运行,因此模块是相对于工作目录的。

这意味着测试就像任何其他想要从 src 获取模块的客户端一样。

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

  • Project Folder
    1. src
    2. test

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

from src import module_name

What I have done is write a module that sits in Project Folder and 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.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文