unittest 中的 Fixtures

Python 測試入門

Alexander Levin

Data Scientist

Fixtures 重點回顧

  • Fixture
    • 測試的預備環境
    • 將前置作業與測試程式碼分離
  • Fixture setup - 為測試建立所需資源
  • Fixture teardown - 釋放(「清理」)已配置的資源
  • 比喻:像是野餐前備餐,結束後收拾清理
Python 測試入門

unittest 函式庫中的 Fixtures

  • unittest 的 Fixture:執行一個或多個測試所需的前置準備
  • .setUp():在實際測試前呼叫,用來準備測試用的 fixture
  • .tearDown():在測試方法之後呼叫,用來清理環境
1 https://docs.python.org/3/library/unittest.html
Python 測試入門

程式碼範例

import unittest

class TestLi(unittest.TestCase):
    # Fixture setup method
    def setUp(self):
        self.li = [i for i in range(100)]

    # Fixture teardown method
    def tearDown(self):
        self.li.clear()

    # Test method
    def test_your_list(self):
        self.assertIn(99, self.li)
        self.assertNotIn(100, self.li)
Python 測試入門

U 與 D 要大寫

  • 正確寫法:setUpU 要大寫、tearDownD 要大寫。

    class TestLi(unittest.TestCase):
      # Fixture setup method
      def setUp(self):
          self.li = [i for i in range(100)]
    
      # Fixture teardown method
      def tearDown(self):
          self.li.clear()
    
Python 測試入門

輸出範例

指令:python3 -m unittest test_in_list.py

包含 .setUp().tearDown() 的執行輸出:

有 fixture 的一次執行輸出

Python 測試入門

方法名稱錯誤的情況

使用 .set_up()(名稱錯誤)時的執行輸出:

fixture 名稱錯誤時的一次執行輸出

Python 測試入門

重點總結

  • unittest 的 Fixture:執行一個或多個測試所需的前置準備
  • 建立 fixture:
    • 實作 .setUp() 方法
    • 實作 .tearDown() 方法
  • .setUp():在實際測試前呼叫,用來準備測試用的 fixture。
  • .tearDown():在測試方法之後呼叫,用來清理環境。
Python 測試入門

一起來練習吧!

Python 測試入門

Preparing Video For Download...