Pythonのunittestモジュールのほんとにちょっとしたtips

だれかが書いてそうだけど、Pythonのunittestモジュールのtipsをめも。
私はほとんど以下のようにunittest.main()しか使わないのですが、
ユニットテスト実行時にオプションを指定することで、個別にユニットテストが実行できるみたい。
ということに今頃気づきました。

if __name__ == "__main__": unittest.main()

まず、"-h"オプションでUsageが表示されます。

$ python pyramidTest.py -h
Usage: pyramidTest.py [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output

Examples:
  pyramidTest.py                               - run default set of tests
  pyramidTest.py MyTestSuite                   - run suite 'MyTestSuite'
  pyramidTest.py MyTestCase.testSomething      - run MyTestCase.testSomething
  pyramidTest.py MyTestCase                    - run all 'test*' test methods
                                               in MyTestCase

おぉ。で、個別に実行したいときは、自分で書いたテスト名とかも覚えてないので、pydocとかでメソッド名みて、それを指定してやればいいわけです。
いままで、全実行しかやってなかったけど、これでテストケースごとにできるね。

$ pydoc pyramidTest
Help on module pyramidTest:

NAME
    pyramidTest

FILE
    /Users/hattori/Programming/Python/ut_sample/pyramidTest.py

CLASSES
    unittest.TestCase(__builtin__.object)
        pyramidTestCase

    class pyramidTestCase(unittest.TestCase)
     |  Method resolution order:
     |      pyramidTestCase
     |      unittest.TestCase
     |      __builtin__.object
     |
     |  Methods defined here:
     |
     |  testdouble(self)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

で、さらに。"-v"オプションなんかをつけると、れぽーとにできそうな出力になります。

$ python pyramidTest.py -v pyramidTestCase.testdouble
testdouble (__main__.pyramidTestCase) ... ok

                                                                                                                                          • -
Ran 1 test in 0.000s OK

と、ここまでです。なんかテストツールに興味わいてきたなぁ。
伝え聞いたことのあるテストスーツは以下くらい。(関係ないものもあるかも。。。)ちょっと調べてみよっと。


テストコードと本体のコードをいちお。

#pyramidTest.py
import unittest
import pyramid

class pyramidTestCase(unittest.TestCase):
    def testsingle(self):
        self.assertEqual("*", pyramid.returnAster(1))
    def testdouble(self):
        self.assertEqual("*\n**", pyramid.returnAster(2))

if __name__ == "__main__": unittest.main()
#pyramid.py
def returnAster(count):
    ret = ""
    for i in range(count):
        for j in range(i+1):
            ret += "*"
        ret += "\n"
    ret = ret[:-1]
    return ret

if __name__ == "__main__":
    for i in range(5):
        print returnAster(i)
        print "\n"