Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Created June 6, 2012 13:43
Show Gist options
  • Save wonderful-panda/2881923 to your computer and use it in GitHub Desktop.
Save wonderful-panda/2881923 to your computer and use it in GitHub Desktop.
unittestでパラメタライズドテスト
# -*- coding:utf8 -*-
# unittestでパラメタライズドテストしてみるテスト
from types import MethodType
__all__ = ["param", "parameterize"]
class _Param(object):
"""
パラメータを表現するデコレータ
"""
def __init__(self, name):
self.name = name
def __call__(self, *args, **kwargs):
def decorated(f):
"""
指定されたfunctionにtest_paramsという属性を追加して、
そこに引数の情報を格納する
"""
if not hasattr(f, "test_params"):
f.test_params = {}
f.test_params[self.name] = (args, kwargs)
return f
return decorated
class _ParamFactory(object):
def __getattr__(self, name):
return _Param(name)
param = _ParamFactory()
def parameterize(cls):
"""
@para.xxxによって修飾されたメソッドから、テスト用のメソッドを生成する
クラスデコレータ
test_paramsという属性が追加されているfunctionを元にテスト用のメソッドを
生やす
"""
for method_name, method in cls.__dict__.items():
if not hasattr(method, "test_params"):
continue
for name, (args, kwargs) in method.test_params.iteritems():
if "_ret" in kwargs:
kwargs = kwargs.copy()
ret = kwargs["_ret"]
del(kwargs["_ret"])
def new_method(self, m=method, a=args, k=kwargs, expected=ret):
ret = m(self, *a, **k)
self.assertEqual(ret, expected)
else:
def new_method(self, m=method, a=args, k=kwargs):
m(self, *a, **k)
new_method_name = "test_%s_%s" % (method_name, name)
setattr(cls, new_method_name, MethodType(new_method, None, cls))
return cls
# -*- coding:utf8 -*-
# unittestでパラメタライズドテストしてみるテスト
import unittest
from parameterized import param, parameterize
@parameterize # テストクラスにparameterizeデコレータを適用
class TestSample(unittest.TestCase):
def test_success(self):
self.assertTrue(True)
@param.A(1, 2, 3) # 位置引数で指定
@param.B(a=2, b=3, result=5) # 名前つき引数で指定
@param.C(1, 2, 4) # 失敗するパターン
def add1(self, a, b, result):
self.assertEqual(a + b, result)
@param.A(1, 2, _ret=3) # _retを指定すると、戻り値をチェックする
@param.C(a=1, b=2, _ret=4)
def add2(self, a, b):
return a + b
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment