diadia

興味があることをやってみる。自分のメモを残しておきます。

unittestのsys.exit()の抜け方

def tashizan(a,b):
    try:
        return int(a)+int(b)
    except ValueError:
        print("a,bは整数ではなく文字列の可能性があります")
        sys.exit(1)
import unittest , tashizan

class TestTashizan(unittest.TestCase):

    def test_tashizan_1(self):
        expected = 8
        actual = tashizan(2, 6)
        self.assertEqual(expected, actual)

    def test_tashizan_2(self):
        expected = 8
        actual = tashizan(6, "2")
        self.assertEqual(expected, actual)


    def test_tashizan_3(self):
        with self.assertRaises(SystemExit):
            tashizan("a", "6")
    


if __name__ == "__main__":
    unittest.main(exit=False)

どうやらエラーのときはwith を使ってassertRaises()を使い、エラーの出る使い方をくるむようだ。