認識 unittest

Python 測試入門

Alexander Levin

Data Scientist

OOP 重點回顧

  • OOP:以物件與類別為基礎的程式設計典範。
  • Class:物件的樣板,可包含方法與屬性。
  • Method:隸屬於類別的函式或程序。
  • Attribute:隸屬於類別的變數。
  • Object:類別的實例。
  • Python 類別範例
    class Rectangle:
      # Constructor of Rectangle
      def __init__(self, a, b):
          self.a = a
          self.b = b
      # Area method
      def get_area(self):
          return self.a * self.b
    # Usage example
    r = Rectangle(4, 5)
    print(r.get_area())
    
>> 20
Python 測試入門

OOP 繼承

  • 類別可以從其他類別繼承屬性與行為。
  • 在新類別名稱後的括號中放入類別。
    class RedRectangle(Rectangle):
      self.color = 'red'
    
Python 測試入門

什麼是 unittest

  • unittest:內建的 Python 自動化測試框架(隨 Python 一起安裝)。
  • unittest 不僅限於單元測試。
  • 基於 OOP:每個測試案例是類別,每個測試是方法。
  • Test case:一次具體的測試實例。
  • Test suite:測試案例的集合。
Python 測試入門

unittest vs. pytest

unittest

  • 基於 OOP(需要建立測試類別)
  • 內建(隨 Python 發行版安裝)
  • 斷言方法較多

pytest

  • 基於函式(搜尋以 test_ 開頭的腳本與函式)
  • 第三方套件(需與 Python 發行版分開安裝)

  • 斷言方法較少

Python 測試入門

如何用 unittest 建立測試

冪次運算子的測試:

import unittest

# 宣告 TestCase 類別
class TestSquared(unittest.TestCase):
    # 定義測試
    def test_negative(self):
        self.assertEqual((-3) ** 2, 9)
Python 測試入門

斷言方法

  • .assertEqual().assertNotEqual()
  • .assertTrue().assertFalse()
  • .assertIs().assertIsNone()
  • .assertIsInstance().assertIn()
  • .assertRaises()
  • 以及更多
Python 測試入門

總結

  • unittest:基於 OOP 的內建 Python 自動化測試框架
  • Test case:在 unittest 中的一次測試實例
  • 建立測試
    1. 宣告繼承自 unittest.TestCase 的類別
    2. 定義測試函式
  • 斷言方法
Python 測試入門

一起來練習吧!

Python 測試入門

Preparing Video For Download...