【pytest官方文檔】解讀fixtures - 5. fixtures的autouse

如今咱們已經知道了,fixtures是一個很是強大的功能。app

那麼有的時候,咱們可能會寫一個fixture,而這個fixture全部的測試函數都會用到它。那這個時候,就能夠用
autouse自動讓全部的測試函數都請求它,不須要在每一個測試函數裏顯示的請求一遍。函數

具體用法就是,將autouse=True傳遞給fixture的裝飾器便可。測試

import pytest


@pytest.fixture
def first_entry():
    return "a"


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


@pytest.fixture(autouse=True)
def append_first(order, first_entry):
    return order.append(first_entry)


def test_string_only(order, first_entry):
    assert order == [first_entry]


def test_string_and_int(order, first_entry):
    order.append(2)
    assert order == [first_entry, 2]

先來看第一個測試函數test_string_only(order, first_entry)的執行狀況:code

  1. 雖然在測試函數裏請求了2個fixture函數,可是order拿到的並非[]first_entry拿到的也並非"a"
  2. 由於存在了一個autouse=True的fixture函數,因此append_first先會被調用執行。
  3. 在執行append_first過程當中,又分別請求了order、 first_entry這2和fixture函數。
  4. 接着,append_first對分別拿到的[]"a"進行append處理,最終返回了["a"]
    因此,斷言assert order == [first_entry]是成功的。

同理,第二個測試函數test_string_and_int(order, first_entry)的執行過程亦是如此。string

相關文章
相關標籤/搜索