由于缺少模块,py.test失败

时间:2015-05-06 20:08:25

标签: python pytest

我想编写测试,但只有安装了nlopt模块才会通过此测试。由于这个模块是可选,我想知道是否有办法编写一个测试,如果模块不存在则不会阻止py.test完全失败。此时,py.test停止,因为它找不到nlopt模块:

$ make test
py.test --exitfirst tests/
============================================================= test session starts =============================================================
platform darwin -- Python 3.4.2 -- py-1.4.26 -- pytest-2.6.4
collecting 0 items / 1 errors
=================================================================== ERRORS ====================================================================
_____________________________________________ ERROR collecting tests/unit/fem/test_simulation.py ______________________________________________
tests/unit/fem/test_simulation.py:5: in <module>
    from hybrida.fem import Simulation, Step, Eigenvalue
src/hybrida/__init__.py:4: in <module>
    from . import geometry
src/hybrida/geometry/__init__.py:3: in <module>
    from . import distance
src/hybrida/geometry/distance.py:9: in <module>
    import nlopt
E   ImportError: No module named 'nlopt'
--------------------------------------------------------------- Captured stdout ---------------------------------------------------------------
 nlopt does not seem to be installed. 
=========================================================== short test summary info ===========================================================
ERROR tests/unit/fem/test_simulation.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
=========================================================== 1 error in 0.67 seconds ===========================================================
make: *** [test] Error 2

我尝试在测试文件的开头添加try-except块,但这没有帮助:

try:
    import nlopt
    import numpy as np

except ImportError:
    print("""nlopt does not seem to be installed""")

我正在编写测试的库中使用nlopt模块。目前,如果找不到模块,库会引发异常。在使用该模块的文件的顶层:

try:
    import nlopt

except ImportError:
    print("""\033[91m nlopt does not seem to be installed. Please install it by downloading nlopt, and installing it using
        $ ./configure --enable-shared
        $ make
        $ make install
        and adding /usr/local/lib/Python3.4/site-packages to the PYTHONPATH
        (or wherever nlopt has been installed):
        export PYTHONPATH=$PYTHONPATH:/usr/local/lib/Python3.4/site-packages

        Note: although Homebrew provides nlopt, it does not install the Python interface.\033[0m""")
    raise

1 个答案:

答案 0 :(得分:2)

使用conditional import machinery pytest提供:

nlopt = pytest.importorskip('nlopt')

将该行放在使用nlopt的特定测试函数中(或在一组函数的setup方法中),并且只有当它无法导入时才会跳过这些。