tachitomonn’s blog

IT技術関連の学習メモがメインでたまに趣味のこととか

Python でテスト nose

前回で標準ライブラリの unittest の基本を押さえたところで今回はより簡単にユニットテストを実行できる nose というライブラリの基本を押さえてみます。

公式ドキュメント
Note to Users — nose 1.3.7 documentation
を参照しながらやってみました。

サードパーティーのライブラリなのでまずはインストール。 pip で入れます。

pip install nose

バージョン 1.3.7 が入りました。

インストールが完了するとテスト対象の自動探索とテスト実行を行ってくれる nosetests コマンドを使えるようになります。
テスト対象には unittest.TestCase のサブクラスも含まれます。試しに前回作成した study_unittest.py をテストしてみます。

>nosetests c:\selfstudy\study_unittest.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

テストが実行されました。 -v オプションで詳細なログを出力してくれます。

>nosetests -v c:\selfstudy\study_unittest.py
test_heisei2seireki (study_unittest.TestSample) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.004s

OK

このように unittest.TestCase のサブクラスで実装したテストケースのテストランナーとしても使えますが、 nose ではテストケースをより容易に関数として書くことができます。またテストをより簡単に書くための関数が用意されているのでテストスクリプトを nose 向けに書き直してみたのがこちら。

test_sample.py

#! /usr/bin/env python

u"""noseの勉強用サンプル
"""

from nose.tools import eq_, raises

from study_doctest import heisei2seireki

def test_heisei2seireki():
    eq_([heisei2seireki(n) for n in range(1, 32)],
            [1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])

@raises(ValueError)
def test_heisei2seireki_exception1():
    heisei2seireki(-1)
    
@raises(ValueError)
def test_heisei2seireki_exception2():
    heisei2seireki(0)

@raises(ValueError)
def test_heisei2seireki_exception3():
    heisei2seireki(1.5)

@raises(ValueError)
def test_heisei2seireki_exception4():
    heisei2seireki(32)

このスクリプトを配置したディレクトリを対象にテストを実行してみます。 nose は test をファイル名に含むファイルを自動的にテスト対象にしてくれます。

>nosetests -v c:\selfstudy
test_sample.test_heisei2seireki ... ok
test_sample.test_heisei2seireki_exception1 ... ok
test_sample.test_heisei2seireki_exception2 ... ok
test_sample.test_heisei2seireki_exception3 ... ok
test_sample.test_heisei2seireki_exception4 ... ok

----------------------------------------------------------------------
Ran 5 tests in 0.014s

OK

いちいちテストケースをクラス定義しなくても良いのは楽ですね。