【python】unittestを使用して、関数などのテストを行う

標準モジュールのunittestを使うことで、クラスや関数が正しく機能しているかどうかをテストする事ができる。

準備

unittestのインポートをする。

import unittest

テストを行う関数の作成

URLからドメイン部分だけを抜き出す簡単な関数を作成。
引数がURLではない場合(httpで始まらない文字列の場合)は、UrlErrorにする。

class UrlError(Exception):
    """入力がURLじゃない場合のエラー"""
    
def get_domain(url):

    if not url.startswith('http'):
        raise UrlError
        
    domain = url.replace('http://','').replace('https://','')
    if '/' in domain:
        domain = domain.split('/')[0]
    
    return domain

上記の関数のユニットテスト

引数にunittest.TestCaseを指定して、テスト用のclassを作成する。

class TestGetDomain(unittest.TestCase):

    #引数がURLの場合    
    def test__get_domain(self):
        test_domain =  get_domain('http://example.com/')
        self.assertEqual(test_domain, 'example.com')
        
    #引数がURL以外の文字列の場合
    def test__not_url(self):
        with self.assertRaises(UrlError):
            test_domain =  get_domain('tp://example.com/')

テストの実行

テストはunittest.main()で実行する。

if __name__ == '__main__':
    unittest.main()

#テスト結果
..
----------------------------------------------------------------------
Ran 1 tests in 0.005s

OK

ただし、IPythonやJupyter notebookでunittestを行おうとすると下記のエラーが発生する。

AttributeError: module '__main__' has no attribute ~~~~~~~~~~~

jupyter notebookでunittestを行う場合は、下記の記述に変更が必要。

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

まとめ

今までテストをする時は適当な引数を渡して、ちまちまとテストしてたが
unittestなんていう便利なものがあるらしい・・。

本番環境で動かしてみると予想外のエラーが起こるということは頻繁にあるので、
日頃からテストを書く習慣をつけておくようにしたい。