简体   繁体   中英

How can I run pytest (and doctests) on Python files without .py extension?

In some cases, for system scripts I like to keep the extension out and use a shebang. Unfortunately pytest seems to ignore these files and doctest fails because it cannot import these files. Example:

#!/usr/bin/python3

# filename: "my-nagios-plugin"

import sys

def runcheck(value):
    """
    Example check

    >>> runcheck(3)
    0
    >>> runcheck(10)
    1
    """
    return 1 if value > 5 else 0

if __name__ == "__main__":
    sys.exit(runcheck(int(sys.argv[1])))

Doctest output:

› python3 -m doctest my-nagios-plugin                                 ✗: 130
**********************************************************************
File "my-nagios-plugin", line 13, in my-nagios-plugin
Failed example:
    runcheck(3)
Exception raised:
    Traceback (most recent call last):
      File "/usr/lib/python3.6/doctest.py", line 1330, in __run
        compileflags, 1), test.globs)
      File "<doctest my-nagios-plugin[0]>", line 1, in <module>
        runcheck(3)
    NameError: name 'runcheck' is not defined
**********************************************************************
File "my-nagios-plugin", line 15, in my-nagios-plugin
Failed example:
    runcheck(10)
Exception raised:
    Traceback (most recent call last):
      File "/usr/lib/python3.6/doctest.py", line 1330, in __run
        compileflags, 1), test.globs)
      File "<doctest my-nagios-plugin[1]>", line 1, in <module>
        runcheck(10)
    NameError: name 'runcheck' is not defined
**********************************************************************
1 items had failures:
   2 of   2 in my-nagios-plugin
***Test Failed*** 2 failures.

pytest output:

› pytest -m doctest-modules my-nagios-plugin my-nagios-plugin           ✗: 1
========================================= test session starts ==========================================
platform linux -- Python 3.6.9, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
rootdir: /home/users/malbert/work/monitoring-plugins
plugins: testinfra-3.4.0
collected 0 items

======================================== no tests ran in 0.21s =========================================
ERROR: not found: /home/users/malbert/work/monitoring-plugins/my-nagios-plugin
(no name '/home/users/malbert/work/monitoring-plugins/my-nagios-plugin' in any of [])

ERROR: not found: /home/users/malbert/work/monitoring-plugins/my-nagios-plugin
(no name '/home/users/malbert/work/monitoring-plugins/my-nagios-plugin' in any of [])

You could just leave the.py extension and then symlink to them from your system script directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM