「PythonでJavaのOptionalクラスを実装する」のユニットテスト
ユニットテストも書いたので載せておく。 Optionクラスはsrcディレクトリ配下のoption.pyに実装している。
from unittest import TestCase from src.option import Option class TestOption(TestCase): def test_値の存在チェックができる(self): for value, expect in [(1, True), (None, False)]: with self.subTest(): target = Option(value) actual = target.is_present() self.assertEqual(actual, expect) def test_値を取得するときに分岐処理ができる(self): for value, expect in [(1, 1), (None, 2)]: with self.subTest(): target = Option(value) actual = target.or_else(2) self.assertEqual(actual, expect) def test_マッピング処理ができる(self): for value, expect in [("hoge", "piyo"), (None, None)]: with self.subTest(): target = Option(value) actual = target.map(lambda x: "piyo").get() self.assertEqual(actual, expect) def test_フィルター処理ができる(self): for value, expect in [("hoge", "hoge"), ("piyo", None), (None, None)]: with self.subTest(): target = Option(value) actual = target.filter(lambda x: x == "hoge").get() self.assertEqual(actual, expect)