106
109

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python でテスト

Posted at

doctest

docstring 内に書ける。凡例として使える。

使い方

doctest を import し、docstring 内で以下のように書き、doctest.testmod() を呼ぶ。実行する際は python ${ファイル名}.py -v とする。

サンプルコード

sample.py
# -*- coding: utf-8 -*-

import doctest

def twice(n):
    """ 引数を 2 倍して返す関数
    >>> twice(8)
    16
    >>> twice(1850923)
    3701846
    """
    return n * 2

if __name__ == "__main__":
    doctest.testmod()

実行

python sample.py -v

結果

Trying:
    twice(8)
Expecting:
    16
ok
Trying:
    twice(1850923)
Expecting:
    3701846
ok
1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.twice
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

docstring を読んでみる

python
import sample
help(sample.twice)
twice(n)
    引数を 2 倍して返す関数
    >>> twice(8)
    16
    >>> twice(1850923)
    3701846

これは…ありがたい…

Instance Method をテストする場合

  • testmod に引数として extraglobs を与える。extraglobs で定義された dictionary の key と値のセットは global 変数にマージされる。
sample.py
# -*- coding: utf-8 -*-

class IntUtil:
    def twice(self, n):
        """ 引数を 2 倍して返す関数
        >>> mine.twice(8)
        16
        >>> mine.twice(1850923)
        3701846
        """
        return n * 2

if __name__ == "__main__":
    import doctest
    doctest.testmod(extraglobs = {'mine': IntUtil()})

unittest

一般的な単体テストおよび結合テストはこちらのモジュールで行う

開始処理と終了処理

setUp: 開始時実行
tearDown: 終了時実行

functions

関数名 説明
assertEqual(a, b, msg=None) a == b
assertNotEqual(a, b, msg=None) a != b
assertTrue(expr, msg=None) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) a is None
assertIsNotNone(x) a is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)
sample_test.py
# -*- coding: utf-8 -*-

import unittest
import sample

class SampleTest(unittest.TestCase):
    def setUp(self):
        self.util = sample.IntUtil()
    def test_twice(self):
        # 足した数と同値か
        import random
        roop = 0
        while roop != 10000:
            n = random.randint(0, 100)
            ans = n + n
            self.assertEqual(self.util.twice(n), ans)
            roop += 1

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

参考資料

106
109
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
106
109

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?