Amazon

2011年9月3日土曜日

Pythonでテスト駆動開発2 -Aptanaからnoseの実行-

前回noseを使って、Pythonでテストを実行する方法について書いた
今回はAptana(Eclipse)からPythonのテストフレームワークのnoseを使用する方法をまとめます。

テストするクラスとテストコードは前回のtest1.py, test2.py

test1.py, test2.pyでは使用していないけど、
テストコードで以下の一文があると、まずライブラリが見つからないとAptana(Eclipse)から怒られる。
from nose.tools import ok_, eq_

ということで解決策
1. プロジェクトを右クリックしてプロパティ
2. PyDev - PYTHONPATHにnoseのライブラリフォルダを追加
 (C:\Python27\Lib\site-packages\nose-1.1.2-py2.7.egg)

テストの実行は
test2.pyの最後に
if __name__ == '__main__':
    import nose
    nose.main()
の記述を入れると、pythonの実行ファイルと認識されて、Eclipseの実行設定ファイルで読み込めるようになる。

ちなみに実行設定ファイルは以下の通り。




で、上記を実行すると
Failure: ImportError (No module named testdata) ... ERROR
Failure: ImportError (No module named sancho.unittest) ... ERROR
Failure: ImportError (No module named sancho.unittest) ... ERROR
Failure: ImportError (No module named sancho.unittest) ... ERROR
Failure: ImportError (No module named sancho.unittest) ... ERROR
Failure: ImportError (No module named sancho.unittest) ... ERROR
Failure: ImportError (No module named sancho.unittest) ... ERROR
Failure: ImportError (cannot import name AES) ... ERROR
Failure: ImportError (No module named testdata) ... ERROR
という結果になる。

このプロジェクト内のテスト(class Testxxx)を全部実行するため、 本来テストしたいもの以外も実行されてしまっている。

ということで、必要なテストだけを実行する場合は--tests=NAMEオプションを付けて実行する。
通常はnose.main()にargs=["-v","--name=tests2.py"] を渡して
test.py
if __name__ == '__main__':
    import nose
    nose.main(args=["-v","--name=tests2.py"] )
とするのが一般的のようだけど、何故か引数が有効にならない。
Aptana(Eclipse)を使用する場合はmainへの引数は実行設定ファイルで設定するようです。



で実行するとverboseモードになって(test.xxx ... okみたいな)テスト結果が表示される。

test2.TestDollar.Multiplicaton_test ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK


○注意点
class名はTestxxxとTestで始めること
メソッド名はyyy_testとすること

1 件のコメント:

  1. Unfortunately I can't speak or even read Japanese, but maybe you can help me. I am using pycrypto, and I think this module makes use of testdata module. But my django project in Aptana cannot run. The console says "no module named testdata". Do you know how to solve it?

    Thx in advance

    返信削除

Amazon3