0
我想編寫一個測試,但只有在安裝了nlopt
模塊後,此測試纔會通過。由於這個模塊是可選,我想知道是否有辦法編寫一個測試,如果該模塊不存在,將不會阻止py.test完全失敗。在這一點上,py.test停止,因爲找不到nlopt
模塊:py.test由於缺少模塊而失敗
$ 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
我試過了,但代碼仍然失敗,我提供了測試的庫內,因爲庫內部還有一個'import nlopt',如果找不到模塊就會引發異常。 – aaragon
你可以在實際使用它的函數內部移動這個'import',而不是使它成爲頂層。 – tzaman
你的意思是在庫側還是在測試側? – aaragon