1. 程式人生 > 實用技巧 >pytest(六)--fixture之yield實現teardown

pytest(六)--fixture之yield實現teardown

前言

  上一篇講到fixture通過scope引數控制setup級別,既然有setup作為用例之前的操作,用例執行完之後那肯定也有teardown操作。

  這裡用到fixture的teardown操作並不是獨立的函式,用yield關鍵字呼喚teardown操作。

scope="module"

1.fixture引數scope="module",module作用是整個.py檔案都會生效,用例呼叫時,引數寫上函式名稱就行。

# coding:utf-8
#test_fix1.py
import pytest
@pytest.fixture(scope="module")
def open():
    print("開啟瀏覽器,並且開啟百度")
def test_1(open):
    print("test_1:搜尋fix1")
def test_2(open):
    print("test_2:搜尋fix2")
def test_3(open):
    print("test_3:搜尋fix3")
if __name__=="__main__":
    pytest.main(["-s","test_fix1.py"])

 

執行結果:

從結果看出,雖然test_1,test_2,test_3三個地方都呼叫了open函式,但是它只會在第一個用例前執行一次。

2.如果test_1不呼叫,test_2(呼叫open),test_3不呼叫,執行順序會是怎樣的?

# coding:utf-8
#test_fix1.py
import pytest
@pytest.fixture(scope="module")
def open():
    print("開啟瀏覽器,並且開啟百度")
def test_1():#不呼叫open
    print("test_1:搜尋fix1")
def test_2(open):
    print("test_2:搜尋fix2")
def test_3(open):
    print("test_3:搜尋fix3")
if __name__=="__main__":
    pytest.main(["-s","test_fix1.py"])  

執行結果:

從結果看出,module級別的fixture在當前.py模組裡,只會在用例test_2 第一次呼叫前執行一次。

yield執行teardown

1.前面講的是在用例前加前置條件,相當於setup,既然有setup那就有teardown,fixture裡面的teardown用yield來喚醒teardown的執行。

# coding:utf-8
#test_fix1.py
import pytest
@pytest.fixture(scope="module")
def open():
    print("開啟瀏覽器,並且開啟百度")
    yield
    print("執行teardown")
    print("最後關閉瀏覽器")
def test_1(open):#不呼叫open
    print("test_1:搜尋fix1")
def test_2():
    print("test_2:搜尋fix2")
def test_3():
    print("test_3:搜尋fix3")
if __name__=="__main__":
    pytest.main(["-s","test_fix1.py"])  

執行結果:

yield遇到異常

1.如果其中一個用例出現異常,不影響yield後面的teardown執行,執行結果互不影響,並且全部用例執行完之後,yield呼喚teardown操作

# coding:utf-8
#test_fix1.py
import pytest
@pytest.fixture(scope="module")
def open():
    print("開啟瀏覽器,並且開啟百度")
    yield
    print("執行teardown")
    print("最後關閉瀏覽器")
def test_1(open):#不呼叫open
    print("test_1:搜尋fix1")
    raise NameError
def test_2():
    print("test_2:搜尋fix2")
def test_3():
    print("test_3:搜尋fix3")
if __name__=="__main__":
    pytest.main(["-s","test_fix1.py"])  

執行結果:

2.如果在setup就異常了,那麼是不會去執行yield後面的teardown內容了

# coding:utf-8
#test_fix1.py
import pytest
@pytest.fixture(scope="module")
def open():
    print("開啟瀏覽器,並且開啟百度")
    raise NameError
    yield
    print("執行teardown")
    print("最後關閉瀏覽器")
def test_1(open):#不呼叫open
    print("test_1:搜尋fix1")
def test_2():
    print("test_2:搜尋fix2")
def test_3():
    print("test_3:搜尋fix3")
if __name__=="__main__":
    pytest.main(["-s","test_fix1.py"])  

執行結果:

addfinalizer終結函式

1.除了yield可以實現teardown,在request-context物件中註冊addfinalizer方法也可以實現終結函式。

2.yield和addfinalizer方法都是在測試完成後呼叫相應的程式碼。但是addfinalizer不同的是:

  • 他可以註冊多個終結函式。

  • 這些終結方法總是會被執行,無論在之前的setup code有沒有丟擲錯誤。這個方法對於正確關閉所有的fixture建立的資源非常便利,即使其一在建立或獲取時失敗