nose tutorial documentation

nose plugin の作成

«  nose.tools を使う   ::   Contents   ::   nose plugin の実行  »

nose plugin の作成

はじめに

nose のプラグインの作成方法です。

役割

テスト関数から外れた処理をする場合は、プラグインを作成する必要があります。

たとえば、次のような場合にプラグインを作成します。

  • 各テスト実行後に特定処理を実行させたいが、テスト関数ごとに teardown を書くのがめんどくさい。
  • レポートの出力形式を独自のものにしたい。

書き方

nose.plugins.Plugin を継承したクラスを作成します。

必要なことは、 name を指定すること、プラグインを動作させたいエントリポイントをオーバーライドすることです。

name は、実行時にプラグインを指定するときに使用します。

エントリポイントは、プラグインの動作を定義します。

from nose.plugins import Plugin

class AfterLog(Plugin):
  """テスト実行ごとに、ログを出力させます。
  """

  name = 'afterlog'

プラグインを afterlog という名前で登録しています。 実行時には、 –with-afterlog というオプションが生成されており、 –with-afterlog を付与するとプラグインが呼び出されます。

def afterTest(self, test):
  fd = open('/Users/kuma8/Desktop/log.txt', 'a')
  fd.write('after ')
  fd.write(test.__repr__())
  fd.write('\n')
  fd.close()

テスト実行後に、ファイルに記録させています。

afterTest というエントリポイントは、テスト実行後に実行されます。

ソースコード

テスト関数実行ごとに実行関数をファイルに記録する。

class logplug.AfterLog[source]

テスト実行後にログを書き出す。

afterTest(test)[source]
name = 'afterlog'
score = 2

動作結果

$ nosetest -v --with-afterlog ex1_test.py
$ cat /tmp/after.txt
after Test(sample_test.add_test)

«  nose.tools を使う   ::   Contents   ::   nose plugin の実行  »