【pytest官方文檔】解讀fixtures - 6. Fixture errors,當fixtures拋錯後

既然fixtures函數也是我們本身寫的,那不免會發生異常,當fixture函數異常後,pytest中如何處理呢?app

首先,在pytest中,若是一個測試函數中傳入了多個fixture函數,那麼pytest會盡量的按線性順序前後執行。
若是,先執行的fixture函數有問題引起了異常,那麼pytest將會中止執行這個測試函數的fixture,而且標記此測試函數有錯誤。函數

可是,當測試被標記爲有錯誤時,並非說這個測試函數的結果失敗了,這僅僅意味着測試函數所依賴的fixture有問題,
致使測試函數不能正常進行。測試

因此,這就引出了另外一個值得關注的點:fixture雖靈活好用,切記不要濫用code

在實際應用中,要儘量的減小沒必要要的依賴關係。這樣的話,測試函數就不會由於其餘不相關的問題,致使本身不能正常運行。test

結合代碼示例,進一步瞭解:import

import pytest


@pytest.fixture
def order():
    return []


@pytest.fixture
def append_first(order):
    order.append(1)


@pytest.fixture
def append_second(order, append_first):
    order.extend([2])


@pytest.fixture(autouse=True)
def append_third(order, append_second):
    order += [3]


def test_order(order):
    assert order == [1, 2, 3]

首先聲明,這段代碼是能夠正常運行的,測試函數test_order也是正常經過的。im

假設,無論怎樣,在order.append(1)處總會報錯。這時候,咱們其實沒法肯定order.extend([2])order +=[3]
是否也有問題。異常

append_first報錯拋出異常後,pytest就不會繼續運行任何的fixture函數了,就連測試函數test_order自己也不會運行。sse

相關文章
相關標籤/搜索