Fixture 收尾(Teardowns)

Python 測試入門

Alexander Levin

Data Scientist

什麼是 fixture 收尾

  • Fixture 收尾(Teardown):在測試環境設定期間配置或建立的資源,於結束時進行清理(teardown)的流程。

回想「野餐」的比喻:

  1. 邀朋友、準備食物
  2. 盡情玩樂!
  3. 收拾善後——這就是 teardown
Python 測試入門

為何要用 teardown

在測試結束時,清理環境 很重要。若不使用 teardown,可能造成嚴重問題:

  • 記憶體洩漏
  • 執行變慢與效能問題
  • 測試結果不正確
  • pipeline 失敗與錯誤
Python 測試入門

何時使用

何時使用:

  • 大型物件
  • 多於 1 個測試
  • 使用 autouse

何時可不必使用:

  • 只有 1 個測試的簡單腳本
Python 測試入門

Python 中的惰性評估

  • yield 是 Python 關鍵字,可用來建立產生器(generator)。
# Example of generator function
def lazy_increment(n):
    for i in range(n):
        yield i
f = lazy_increment(5)
next(f) # 0
next(f) # 1
next(f) # 2
Python 測試入門

使用方式

如何使用:

  • return 換成 yield
  • 將收尾程式碼放在 yield 之後
  • 確保設定程式碼只在 yield 之前
Python 測試入門

收尾範例

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

@pytest.fixture(autouse=True)
def add_numbers_to_list(init_list):
    # Fixture Setup
    init_list.extend([i for i in range(10)])
    # Fixture output
    yield init_list
    # Teardown statement
    init_list.clear()

def test_9(init_list):
    assert 9 in init_list
Python 測試入門

重點整理

  • 定義:Fixture 收尾是清理在設定階段配置之資源的流程。
  • 用法
    • 使用 yield 取代 return
    • 收尾程式碼放在 yield 之後
  • 優點
    • 避免軟體失敗
    • 避免效能下滑
  • 何時使用:只要超過 1 個測試就要用!
Python 測試入門

一起來練習吧!

Python 測試入門

Preparing Video For Download...