Pythonでエラーが発生することをテストする

テストケースでエラーが発生するかどうかをテストするというのは、rubyの案件でrspecを使っているときはよくやってた覚えがあるんですが、djangoで、というかpythonでどうやるのか、調べる機会があったのでメモしておきます

unittest.TestCaseにassertRaisesというのが使えます。

class DoSomethingError(Exception):
    pass

def do_something():
    raise DoSomethingError('error')
# coding=utf-8
import unittest

class SampleTest(unittest.TestCase):

    def test_do_something(self):
        """do_something関数がDoSomethingErrorをraiseすることをテストする
        """
        with self.assertRaises(DoSomethingError) as cm:
            do_something()
        exception = cm.exception
        self.assertEquals(exception.message, 'error')


もしdo_something関数がDoSomethingErrorをraiseしなかった場合は以下のようにテスト失敗になります

AssertionError: DoSomethingError not raised