unittest を知る

Pythonによるテスト入門

Alexander Levin

Data Scientist

OOP の復習

  • OOP - オブジェクトとクラスに基づくプログラミングパラダイム。
  • クラス - メソッドと属性を持つオブジェクトのひな型。
  • メソッド - クラスに属する関数。
  • 属性 - クラスに属する変数。
  • オブジェクト - クラスのインスタンス。
  • 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 ベース: 各テストケースはクラス、各テストはメソッド。
  • テストケース - テストの単位。
  • テストスイート - テストケースの集合。
Pythonによるテスト入門

unittest と pytest の比較

unittest

  • OOP ベース - テストクラスの作成が必要
  • 組み込み(Python 配布物に含まれる)
  • アサーションメソッドが多い

pytest

  • 関数ベース - test_ で始まるスクリプト・関数を探索
  • サードパーティ(Python とは別途インストールが必要)

  • アサーションメソッドは少なめ

Pythonによるテスト入門

unittest でテストを作成する方法

累乗演算子のテスト:

import unittest

# Declaring the TestCase class
class TestSquared(unittest.TestCase):
    # Defining the test
    def test_negative(self):
        self.assertEqual((-3) ** 2, 9)
Pythonによるテスト入門

アサーションメソッド

  • .assertEqual(), .assertNotEqual()
  • .assertTrue(), .assertFalse()
  • .assertIs(), .assertIsNone()
  • .assertIsInstance(), .assertIn()
  • .assertRaises()
  • そのほか多数
Pythonによるテスト入門

まとめ

  • unittest - OOP ベースの Python 組み込みテスト自動化フレームワーク
  • テストケース - unittest におけるテスト単位
  • テストの作成:
    1. unittest.TestCase を継承するクラスを定義
    2. テスト関数を定義
  • アサーションメソッド
Pythonによるテスト入門

Ayo berlatih!

Pythonによるテスト入門

Preparing Video For Download...