nose まとめ3 (nose のsetup/teardown)

はじめに

nose の基本的な使い方その2です。

setup/teardown の動作についてです。

役割

テストを行う上で、あらかじめデータを用意しておく必要あったり、
テスト後に作成したデータを削除するときに利用します。

詳しくは、他のブログなどをみましょう。

書き方

nose では、パッケージレベル、モジュールレベル、関数レベルで定義することができます。

パッケージレベルでは、 __init__.py に setup/teardown を定義します。

モジュールレベルでは、テスト用モジュールに setup/teardown を定義します。

関数レベルでは、 nose.tools.with_setup に関数ごとに呼び出したい、setup/teardown をデコレータに渡します。

呼び出し順

テストパッケージ内に上の3つのレベルで、 setup/teardown が定義されていると呼び出し順序は次のようになります。

  1. パッケージの setup
  2. モジュールの setup
  3. 個々の関数の setup/teardown
  4. モジュールの teardown
  5. パッケージの teardown

サンプル

# coding: utf-8
"""
例題2 setup/teardown 付きのテストケースを記述してあります。                                                             
"""

from nose.tools import ok_, eq_, with_setup

def debug_write(message):
  debug_file = open('debug.txt', 'a')
  debug_file.write(message)
  debug_file.close()

def setup():
  debug_write("module setup\n")

def teardown():
  debug_write("module teardown\n")

def b_setup():
  debug_write("func b setup\n")

def b_teardown():
  debug_write("func b teardown\n")

def a_test():
  """ テスト a の呼び出し確認 """
  debug_write(a_test.__str__() + '\n')
  ok_(True)

@with_setup(b_setup, b_teardown) 
def b_test():
  """ テスト b の呼び出し確認 """
  debug_write(b_test.__str__() + '\n')
  ok_(True)

出力結果

$ cat debug.txt
module setup

func b setup

func b teardown
module teardown