noseという単体テストフレームワークを使って、
pythonの単体テストを書いてみたのでメモを残しておきます。

nose
http://nose.readthedocs.io/en/latest/index.html

インストール

pipを使ってインストールします。

$ pip install nose

テストの記載と実行

以下のようにテストコードを記載します。

tests/test_foo.py

from nose.tools import with_setup, raises, eq_

def test_xxx():
    eq_(1,1)

nosetestsコマンドを実行して、テストを実行します。

$ nosetests
.
----------------------------------------------------------------------
Ran 1 test in 0.006s

OK

テストコードを変更して、失敗させてみます。

tests/test_foo.py

from nose.tools import with_setup, raises, eq_

def test_xxx():
    eq_(1,3)

以下が、失敗させた場合のテストの実行結果です。

$ nosetests
F
======================================================================
FAIL: test_foo.test_xxx
----------------------------------------------------------------------
Traceback (most recent call last):
  File "※パス省略※/site-packages/nose/case.py", line 198, in runTest
    self.test(*self.arg)
  File "※パス省略※/tests/test_foo.py", line 4, in test_xxx
    eq_(1,3)
AssertionError: 1 != 3

----------------------------------------------------------------------
Ran 1 test in 0.009s

FAILED (failures=1)

setuptoolsからテストを実行

以下のようにsetup.pyを準備します。

from setuptools import setup

setup (
    name = 'notest-sample',
    test_suite = 'nose.collector'
)

setup.pyから、テストを実行します。

$ python setup.py test
running test
running egg_info
creating nosetest_sample.egg-info
writing top-level names to nosetest_sample.egg-info/top_level.txt
writing dependency_links to nosetest_sample.egg-info/dependency_links.txt
writing nosetest_sample.egg-info/PKG-INFO
writing manifest file 'nosetest_sample.egg-info/SOURCES.txt'
reading manifest file 'nosetest_sample.egg-info/SOURCES.txt'
writing manifest file 'nosetest_sample.egg-info/SOURCES.txt'
running build_ext
test_foo.test_xxx ... ok

----------------------------------------------------------------------
Ran 1 test in 0.003s

OK

とりあえず、これで基本的な単体テストは実行できそうです。