danglingfarpointer's memoization

仕事周りでの気付き、メモ、愚痴などを書いていきます。

Pythonのunittestとcoverage

PythonのUnit Testとカバレッジ計測のメモです。

Pythonの標準的なUnit Testフレームワークとして、unittestがあります。 テストの書き方はいわゆるxUnitとよく似ています。

テスト対象のサンプルクラスuser.pyです。2つのメソッドを定義しています。

class User:
    def __init__(self, name, email):
        self.__name = name
        self.__email = email

    def __str__(self):
        return '[' + self.__name + ', ' + self.__email + ']'

    def get_name(self):
        return self.__name

    def get_email(self):
        return self.__email

そしてunittestを使ったコードtest_user.pyです。Userの2つのメソッドについてテストを書いています。

import unittest
from user import User

class TestUser(unittest.TestCase):
    def setUp(self):
        self._user = User('taro', 'taro@example.com')
        
    def test_get_name(self):
        self.assertEqual('taro', self._user.get_name())

    def test_get_email(self):
        self.assertEqual('taro@example.com', self._user.get_email())

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

以下のようにテストを実行できます(python test_user.pyと直接実行してもOK)

 $ python -m unittest test_user

..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

次はカバレッジです。カバレッジを計測するツールとして、coverageがあります。

http://blanktar.jp/blog/2015/03/python-unittest-coverage.html

pipでインストール後、coverage runコマンドでunittestのテストケースを走らせます。

 $ coverage run test_user.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

カバレッジ測定結果が.coverageに生成されます。それをhtmlに変換して、ブラウザで見てみます。

 $ coverage html user.py
 $ open htmlcov/index.html 

ファイルごとの実行割合がまず一覧で表示されます。ここでは1ファイルしかありませんが。 f:id:danglingfarpointer:20160128212908p:plain

ファイル名をクリックすると、そのファイルで実行されなかった文が一目でわかります。いい感じです。 f:id:danglingfarpointer:20160128213025p:plain