如何在没有 .py 扩展名的 Python 文件上运行 pytest(和 doctests)?

exh*_*uma 6 python unit-testing pytest

在某些情况下,对于系统脚本,我喜欢保留扩展名并使用 shebang。不幸的是 pytest 似乎忽略了这些文件并且 doctest 失败了,因为它无法导入这些文件。例子:

\n
#!/usr/bin/python3\n\n# filename: "my-nagios-plugin"\n\nimport sys\n\ndef runcheck(value):\n    """\n    Example check\n\n    >>> runcheck(3)\n    0\n    >>> runcheck(10)\n    1\n    """\n    return 1 if value > 5 else 0\n\nif __name__ == "__main__":\n    sys.exit(runcheck(int(sys.argv[1])))\n
Run Code Online (Sandbox Code Playgroud)\n

文档测试输出:

\n
\xe2\x80\xba python3 -m doctest my-nagios-plugin                                 \xe2\x9c\x97: 130\n**********************************************************************\nFile "my-nagios-plugin", line 13, in my-nagios-plugin\nFailed example:\n    runcheck(3)\nException raised:\n    Traceback (most recent call last):\n      File "/usr/lib/python3.6/doctest.py", line 1330, in __run\n        compileflags, 1), test.globs)\n      File "<doctest my-nagios-plugin[0]>", line 1, in <module>\n        runcheck(3)\n    NameError: name 'runcheck' is not defined\n**********************************************************************\nFile "my-nagios-plugin", line 15, in my-nagios-plugin\nFailed example:\n    runcheck(10)\nException raised:\n    Traceback (most recent call last):\n      File "/usr/lib/python3.6/doctest.py", line 1330, in __run\n        compileflags, 1), test.globs)\n      File "<doctest my-nagios-plugin[1]>", line 1, in <module>\n        runcheck(10)\n    NameError: name 'runcheck' is not defined\n**********************************************************************\n1 items had failures:\n   2 of   2 in my-nagios-plugin\n***Test Failed*** 2 failures.\n
Run Code Online (Sandbox Code Playgroud)\n

py测试输出:

\n
\xe2\x80\xba pytest -m doctest-modules my-nagios-plugin my-nagios-plugin           \xe2\x9c\x97: 1\n========================================= test session starts ==========================================\nplatform linux -- Python 3.6.9, pytest-6.0.1, py-1.9.0, pluggy-0.13.1\nrootdir: /home/users/malbert/work/monitoring-plugins\nplugins: testinfra-3.4.0\ncollected 0 items\n\n======================================== no tests ran in 0.21s =========================================\nERROR: not found: /home/users/malbert/work/monitoring-plugins/my-nagios-plugin\n(no name '/home/users/malbert/work/monitoring-plugins/my-nagios-plugin' in any of [])\n\nERROR: not found: /home/users/malbert/work/monitoring-plugins/my-nagios-plugin\n(no name '/home/users/malbert/work/monitoring-plugins/my-nagios-plugin' in any of [])\n
Run Code Online (Sandbox Code Playgroud)\n

Hol*_*son -1

您可以只保留 .py 扩展名,然后从系统脚本目录符号链接到它们。