首页 > 解决方案 > 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)的工作目录相同。我哪里错了?

标签: pythonpython-3.xgithub-actions

解决方案


您的 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

最佳做法是直接将工作目录添加到您的路径中。


推荐阅读