unittest,在本地工作,但不在远程服务器上,没有名为 x.__main__ 的模块; 'x'是一个包,不能直接执行

2024-03-05

我正在为我的 Python 包开发 Jenkins CI/CD 管道。我的项目文件层次结构如下:

project/
- package_name
  - file1.py
  - file2.py
  - etc...
- tests
  - unit
    - __main__.py
    - __init__.py
    - test1.py
    - test2.py

所有单元测试(我正在使用unittest)使用单个命令运行

python -m tests.unit

通过添加__init__.py包含以下内容:

contents

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

and __main__.py看起来像这样

contents

import unittest
import sys

sys.path.append('../..')

loader = unittest.TestLoader()
start_dir = '.'
suite = loader.discover(start_dir)
runner = unittest.TextTestRunner(verbosity=2).run(suite)

首先将路径改为./tests/unit。之后,将顶级目录添加到导入路径中,以便在测试中导入该包。这按预期工作(即,所有休息都通过运行来执行python -m test.unit在我的个人笔记本电脑(Python 3.6.4)上的项目目录顶部)。

但是,当我在远程 Jenkins 服务器(以及 Python 3.6.4)上使用相同的技巧时,我收到以下错误:

no module named test.unit.__main__; 'test.unit' is a package and cannot be directly executed

我已经研究了这个问题,但所提出的解决方案似乎都不适用于我的情况。

如何修改我的代码以创建测试套件unittest本地和远程运行不会有任何问题吗?

EDIT我尝试修改PYTHONPATH变量,但没有成功


1. 为什么不起作用?

1.1.关于python -m and __main__.py

当你跑步时python -m tests.unit,Python解释器将运行什么代码,按这个顺序

tests.__init__.py
tests.unit.__init__.py
tests.unit.__main__.py

1.2.重现错误

现在,如果您删除__main__.py,您将收到以下错误:

No module named tests.unit.__main__; 'tests.unit' is a package and cannot be directly executed

这与您收到的消息几乎相同。如果您有sys.path包含名为的文件夹的文件夹test具有这样的结构(注:test-文件夹不在prular中,并且没有__main__.py!)

test
├── __init__.py
└── unit
    └── __init__.py

并运行命令

python -m test.unit

python 解释器尝试运行的顺序是

test.__init__.py
test.unit.__init__.py
test.unit.__main__.py <-- missing!

Since test.unit.__main__.py缺失,您将收到错误消息

No module named test.unit.__main__; 'test.unit' is a package and cannot be directly executed

这是您收到的错误消息。因此,您的错误消息的原因很可能是您的某个地方sys.path目录 一个名为的目录test具有上面所示的结构,并且您正在尝试调用python -m test.unit代替python -m tests.unit.

2.如何让它发挥作用?

  • 删除你的os.chdir and sys.path.append你正在使用的黑客__init__.py and __main__.py。至少,python unittest 工作不需要它们。
  • 使用中所示的模式创建单元测试文档 https://docs.python.org/3/library/unittest.html(通过子类化unittest.TestCase)
  • 通过以下方式运行您的单元测试
python -m unittest
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

unittest,在本地工作,但不在远程服务器上,没有名为 x.__main__ 的模块; 'x'是一个包,不能直接执行 的相关文章

随机推荐