【问题标题】:Python test file structure for GitHub actions [duplicate]GitHub操作的Python测试文件结构[重复]
【发布时间】:2021-06-22 12:24:00
【问题描述】:

我的目录结构如下:

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 在本地运行它,并且在 GH Actions 上以 python test/test_config.py 的身份运行?
  • 在本地,我使用 pycharm 并将配置选项 targetWorking Directory 设置为 main_dir。在 GH Actions 我有pipenv run pytest
  • @MisterMiyagi 成功了!添加__init__.py 有效,但我也认为它不应该存在。感谢您的回答和资源,肯定有一些阅读要做!

标签: python python-3.x github-actions


【解决方案1】:

您的 IDE 应该将您的项目添加到您的 python 路径中。

您可以使用以下 sn-p 将其添加到您的脚本中:

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 路径中存在什么,只需打印 sys.path

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

【讨论】:

    猜你喜欢
    • 2013-02-21
    • 1970-01-01
    • 2020-10-07
    • 2021-06-23
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    相关资源
    最近更新 更多