nose まとめ4 (nose.tools を使う)

はじめに

nose には、簡単にテストするための機能が用意されています。
機能は、 nose.tools パッケージにまとまっています。
いくつかの機能は、前回までに出ていますが、あらためて書いてあります。

使い方

nose.tools.ok_
   ok_(expr, msg=None)

expr が True かどうかを評価します。
msg がある場合は、テスト結果に出力します。

nose.tools.eq_
   eq_(a, b, msg=None)

a と b が等しいかどうかを評価します。
msg がある場合は、テスト結果に出力します。

nose.tools.raises
   @raises(TypeError)
   def raise_test():
     raise TypeError("This test passes")

   @raises(TypeError, ValueError)
   def raise_test():
     pass

テスト関数に期待する値が、例外の場合に使用します。
raises デコレータは、値を複数持てます。

nose.tools.timed
   @timed(.1)
   def time_test():
     import time
     time.sleep(.5)

テスト実行に制限時間を持たせる場合に使用します。
timed で指定した時間を越えた場合は、テスト失敗になります。

nose.tools.with_setup
   @with_setup(setup=x_setup, teardown=x_teardown)
   def x_test():
     pass

テストごとに setup と teardown を実行させる場合に使用します。
パッケージレベル、モジュールレベルの setup/teardown は実行されます。

nose.tools.istest
   @istest
   def skip():
     pass

テストと見なされない関数をテストとして実行させる場合に使用します。

nose.tools.nottest
   @nottest
   def skip_test():
     pass

テストをスキップさせたい場合に使用します。

サンプル

# coding: utf-8
"""
例題3 nose.tools を使う。
"""

from nose.tools import *

def ok_test():
  """ nose.tools.ok_ : expr が True かどうかを評価します。 """
  ok_(1 == 1)

def eq_test():
  """ nose.tools.eq_ : a と b が等しいかどうかを評価します。 """
  eq_(1 + 1, 2)

@raises(TypeError)
def except_test():
  """ nose.tools.raises : テスト関数に期待する値が、例外の場合に使用します。 """
  raise TypeError("This test passes")

@timed(.1)
def time_test():
  """ nose.tools.timed : テスト実行の制限時間を設定します。 このテストは失敗します。 """
  import time
  time.sleep(.5)

def ex3_setup():
  pass

def ex3_teardown():
  pass

@with_setup(setup=ex3_setup, teardown=ex3_teardown)
def ex3_test():
  """ nose.tools.with_setup : テストごとに、setup/teardown を実行します。"""
  ok_(True)

@istest
def skip():
  """ nose.tools.istest : 通常はスキップされますが、テストとして見なされます。 """
  ok_(True)

@nottest
def run_test():
  """ nose.tools.nottest : 通常は実行されますが、テストしません。
  ** run_test は、表示されません。**
  """
  ok_(True)

まとめ

nose.tools を一通り使えば、複雑なテストでない限りはそう困らないと思います。