在實際工作中,經常需要skip過某個test case,比如現階段某個feature還沒有開發完畢,但是先把test cases寫到了pytest中,因此需要先把這個test case給skip掉。所以skip在pytest中有很大的用途,掌握這個skip功能會極大地提升工作效率。
這裏就列一下我所知道的skip掉test case的方法。
方法一:
使用@pytest.mark.skip(reason='')這個裝飾器。以下是pytest官網的一個例子:
@pytest.mark.skip(reason="no way of currently testing this")
def test_the_unknown():
...
但是這個功能需要pytest 2.9才能支持,之前的版本親測是不可用的。
另外一個是skipif裝飾器,很多時候,我並不想某個test case都被skip,我只想在特定的一些情況下skip,其他情況照常執行,skipif就是解決這個問題的。以下也是pytest官網的一個例子:
import sys
@pytest.mark.skipif(sys.version_info < (3,3),
reason="requires python3.3")
def test_function():
...
上面例子的含義是該test case的執行需要依賴於Python版本,如果Python版本低於3.3則會被skip,如果版本高於或等於3.3則會被執行。
方法二:
使用pytest.skip(reason=''),注意這個就不再是一個裝飾器了,而僅僅是一個函數了。此外需要注意的是,pytest.skip()放置位置對test case的執行至關重要。如果只放在一個test case中,則僅僅會skip掉這一個test case,比如:
import pytest
def test_123():
pytest.skip("Not implemented")
assert 1 == 0
def test_234():
assert 1 == 0
執行結果如下:
======================================== test session starts =========================================
platform linux2 -- Python 2.7.5 -- py-1.4.22 -- pytest-2.6.0
plugins: ordering
collected 2 items
test_123.py sF
============================================== FAILURES ==============================================
______________________________________________ test_234 ______________________________________________
def test_234():
> assert 1 == 0
E assert 1 == 0
test_123.py:8: AssertionError
================================ 1 failed, 1 skipped in 0.01 seconds =================================
因爲pytest.skip()放在了test_123()中,因此,僅僅會skip掉test_123,test_234()還是會執行的。如果把pytest_skip()放在了test_函數之外,則整個文件下的test cases都會被skip掉而不被執行。如下所示:
import pytest
pytest.skip("Not implemented")
def test_123():
assert 1 == 0
def test_234():
assert 1 == 0
執行結果如下:
py.test test_123.py -v
======================================== test session starts =========================================
platform linux2 -- Python 2.7.5 -- py-1.4.22 -- pytest-2.6.0 -- /usr/bin/python
plugins: ordering
collected 0 items / 1 skipped
===================================== 1 skipped in 0.01 seconds ======================================