自動使用的 fixture(autouse)

Python 測試入門

Alexander Levin

Data Scientist

Autouse 引數

  • fixture 的可選布林引數
  • 可傳給 fixture 裝飾器
  • autouse=True 時,無論是否被請求都會執行該 fixture 函式
  • 有助於減少重複的 fixture 呼叫
Python 測試入門

何時使用

當你需要對「所有測試」套用特定的環境準備或修改時。

例如,你想確保所有測試:

  • 使用相同的資料
  • 具有相同的連線(資料、API 等)
  • 具備相同的環境設定
  • 有監控、記錄或效能分析

以上情境都應使用 「autouse」引數

Python 測試入門

Autouse 範例

「autouse」fixture 範例:

import pytest
import pandas as pd

# Autoused fixture
@pytest.fixture(autouse=True)
def set_pd_options():
    pd.set_option('display.max_columns', 5000)

# Test function
def test_pd_options():
    assert pd.get_option('display.max_columns') == 5000
Python 測試入門

Autouse 錯誤範例

「autouse」fixture 的錯誤範例:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture(autouse=True)
def wrong_fixture():
    return [1,2,3,4,5]

# Test function
def test_type():
    assert type(wrong_fixture) == list

修正後的正確 fixture 範例:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture
def correct_fixture():
    return [1,2,3,4,5]

# Test function
def test_type(correct_fixture):
    assert type(correct_fixture) == list
Python 測試入門

Autouse 範例:輸出

範例輸出:

autouse 範例輸出

Python 測試入門

重點整理

  • autouse 定義:fixture 裝飾器的可選布林引數
  • 用法@pytest.fixture(autouse=True)
  • 優點:減少多餘的 fixture 呼叫,讓程式碼更精簡
  • 特性autouse=True 時,fixture 函式會不論請求與否皆執行
  • 適用時機:需要套用特定的環境準備或修改時
  • 使用情境範例
    • 為所有測試讀取並準備資料
    • 設定連線與環境參數
    • 實作監控、記錄或效能分析
Python 測試入門

一起來練習吧!

Python 測試入門

Preparing Video For Download...