東山n条より

京都在住情報系学生のメモ。

Python のテストフレームワーク nose の setup teardown のまとめ

Python のテストフレームワーク nose を使ってテストを書く時に, setup と teardown がいつ実行されるかがよくわからなかったので,まとめました.

まとめ

各テストケースの前後に setup/treadown を行いたい場合 -> クラスを使う
テストを行う前後1回だけ setup/teardown を行いたい場合 -> モジュールを使う

各テストケースの前後に setup/treadown を行いたい場合

クラスを使ってテストを書きます。

#! /usr/bin/env python
#-*- encoding: utf-8 -*-

import nose

class TestMyUtillClass:

    def out(self, message):
        debug_file = open('debug4class.txt', 'a')
        debug_file.write(message + "\n")
        debug_file.close()
        
    def setup(self):
        self.out("setup")
            
    def test_one(self):
        self.out(__name__)
                

    def test_two(self):
        self.out(__name__)

    def teardown(self):
        self.out("teardown")

これを実行すると,結果は以下のようになります.

$ cat debug4class.txt
setup
TestMyUtillClass
teardown
setup
TestMyUtillClass
teardown

テストを行う前後1回だけ setup/teardown を行いたい場合

モジュールを使ってテストを書きます.

#! /usr/bin/env python
#-*- encoding: utf-8 -*-

import nose

def out(message):
    debug_file = open('debug4module.txt', 'a')
    debug_file.write(message + "\n")
    debug_file.close()

def setup():
    out("setup")

def test_one():
    out(__name__)
    

def test_twot():
    out(__name__)

def teardown():
    out("teardown")

これを実行すると,結果は以下のようになります.

$ cat debug4module.txt
setup
TestMyUtill
TestMyUtill
teardown

参考にさせて頂いたサイト

[Python] nose まとめ3 (nose のsetup/teardown)