python - GitHub 操作的 Python 测试文件结构
问题描述
我有以下目录结构:
main_dir/
|--.git/
|--.github/
|--workflows/
|--main.yml
|--package/
|--__init__.py
|--config.py
|--tests/
|--pytest.ini
|--test_config.py
在test/test_config.py
第一行从 config.py 文件中导入一个类:
from package.config import Config
这些测试在本地运行时有效,但在 GitHub Actions 上出现错误ModuleNotFoundError: No module named 'package'
。两者(main_dir)的工作目录相同。我哪里错了?
解决方案
您的 IDE 应该将您的项目添加到您的 python 路径中。
您可以使用以下代码段将其添加到您的脚本中:
import os
current_dir = os.path.dirname(os.path.realpath(__file__)))
working_dir = os.path.join(current_dir , "..")
import sys
sys.path.append(working_dir)
您现在可以在 python 路径中使用您的工作目录
from package.config import Config
要知道你的 python 路径中存在什么,只需 print sys.path
。
最佳做法是直接将工作目录添加到您的路径中。
推荐阅读
- reactjs - 禁用对 ag-grid-react 中特定列的排序
- javascript - jQuery 内部错误:未捕获的 TypeError:无法读取未定义的属性“toLowerCase”
- java - 使用 MapStruct 将新的子实体添加到托管实体
- c++ - 对象初始化中是否允许指向 this 成员的指针?
- assembly - 在arm汇编语言中,“sub r3, r2, 5”会修改存储在r2中的值吗?
- python - Python Pydantic - 如何有一个“可选”字段,但如果存在则需要符合非无值?
- node.js - Node js流文件而不保存到内存
- python - Django:从查询集中查找所有 one_to_one 关系
- plsql - 在通过数据库链接物化时使用 Oracle ON COMMIT 选项
- angular - 如何对订阅 ActivatedRoute 数据时调用的函数的调用进行单元测试?