unittestとは
単体テスト(ユニットテストと呼ばれることもあります)は、プログラムを構成する比較的小さな単位(ユニット)が個々の機能を正しく果たしているかどうかを検証するテストです。
通常、関数やメソッドが単体テストの単位(ユニット)となります
単体テスト(ユニットテスト)とは | ソフトウェアの検証の種類 | テクマトリックス株式会社
要するに関数とかがちゃんと動いているかチェックするテストである。
先に関数の振る舞いを決めてテストを書いてから関数の実物を書くのがテスト駆動開発-TDD(あっているか自信なし)
どんな風に書くん?
import unittest
import <テストしたい関数とか>
class Test<テストしたい(ry>(unittest.TestCase): # 名前は重要ではないけどunittest.TestCaseを引き継ぐのは必須
def test_<テストする関数>(self): # test_*と書くと自動でテストだと認識してくれるらしい
"""テストの説明
"""
self.assertEqual(出てくるべき答え, <テストしたい関数>(引数))
基本的にはこんな感じでいいらしい
例
こんな感じのディレクトリ構成だとする
projectroot
├── src
│ └── hoge.py
└── test
└── test_hoge.py
hoge.py
をテストするtest_hoge.py
がある
hoge.py
def foo(a: int, b: int) -> int:
return a + b
def bar(a: int, b: int) -> int:
return a - b
test_hoge.py
import unittest
from src import hoge
class TestHoge(unittest.TestCase):
def test_foo(self):
"""fooのテスト
"""
expected = 2
actual = hoge.foo(1, 1)
self.assertEqual(expected, actual)
def test_bar(self):
"""barのテスト
"""
expected = 0
actual = hoge.bar(1, 1)
self.assertEqual(expected, actual)
testの実行は次のようになる
python -m unittest discover -s test -v
projectroot
直下でtest内のコードを実行している
実行結果
test_foo (test_hoge)
fooのテスト ... ok
test_bar (test_hoge)
barのテスト ... ok
----------------------------------------------------------------------
Ran 1 test in 0.003s
OK