_parameterized.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. #! /usr/bin/env python
  2. #
  3. # Protocol Buffers - Google's data interchange format
  4. # Copyright 2008 Google Inc. All rights reserved.
  5. #
  6. # Use of this source code is governed by a BSD-style
  7. # license that can be found in the LICENSE file or at
  8. # https://developers.google.com/open-source/licenses/bsd
  9. """Adds support for parameterized tests to Python's unittest TestCase class.
  10. A parameterized test is a method in a test case that is invoked with different
  11. argument tuples.
  12. A simple example:
  13. class AdditionExample(_parameterized.TestCase):
  14. @_parameterized.parameters(
  15. (1, 2, 3),
  16. (4, 5, 9),
  17. (1, 1, 3))
  18. def testAddition(self, op1, op2, result):
  19. self.assertEqual(result, op1 + op2)
  20. Each invocation is a separate test case and properly isolated just
  21. like a normal test method, with its own setUp/tearDown cycle. In the
  22. example above, there are three separate testcases, one of which will
  23. fail due to an assertion error (1 + 1 != 3).
  24. Parameters for individual test cases can be tuples (with positional parameters)
  25. or dictionaries (with named parameters):
  26. class AdditionExample(_parameterized.TestCase):
  27. @_parameterized.parameters(
  28. {'op1': 1, 'op2': 2, 'result': 3},
  29. {'op1': 4, 'op2': 5, 'result': 9},
  30. )
  31. def testAddition(self, op1, op2, result):
  32. self.assertEqual(result, op1 + op2)
  33. If a parameterized test fails, the error message will show the
  34. original test name (which is modified internally) and the arguments
  35. for the specific invocation, which are part of the string returned by
  36. the shortDescription() method on test cases.
  37. The id method of the test, used internally by the unittest framework,
  38. is also modified to show the arguments. To make sure that test names
  39. stay the same across several invocations, object representations like
  40. >>> class Foo(object):
  41. ... pass
  42. >>> repr(Foo())
  43. '<__main__.Foo object at 0x23d8610>'
  44. are turned into '<__main__.Foo>'. For even more descriptive names,
  45. especially in test logs, you can use the named_parameters decorator. In
  46. this case, only tuples are supported, and the first parameters has to
  47. be a string (or an object that returns an apt name when converted via
  48. str()):
  49. class NamedExample(_parameterized.TestCase):
  50. @_parameterized.named_parameters(
  51. ('Normal', 'aa', 'aaa', True),
  52. ('EmptyPrefix', '', 'abc', True),
  53. ('BothEmpty', '', '', True))
  54. def testStartsWith(self, prefix, string, result):
  55. self.assertEqual(result, strings.startswith(prefix))
  56. Named tests also have the benefit that they can be run individually
  57. from the command line:
  58. $ testmodule.py NamedExample.testStartsWithNormal
  59. .
  60. --------------------------------------------------------------------
  61. Ran 1 test in 0.000s
  62. OK
  63. Parameterized Classes
  64. =====================
  65. If invocation arguments are shared across test methods in a single
  66. TestCase class, instead of decorating all test methods
  67. individually, the class itself can be decorated:
  68. @_parameterized.parameters(
  69. (1, 2, 3)
  70. (4, 5, 9))
  71. class ArithmeticTest(_parameterized.TestCase):
  72. def testAdd(self, arg1, arg2, result):
  73. self.assertEqual(arg1 + arg2, result)
  74. def testSubtract(self, arg2, arg2, result):
  75. self.assertEqual(result - arg1, arg2)
  76. Inputs from Iterables
  77. =====================
  78. If parameters should be shared across several test cases, or are dynamically
  79. created from other sources, a single non-tuple iterable can be passed into
  80. the decorator. This iterable will be used to obtain the test cases:
  81. class AdditionExample(_parameterized.TestCase):
  82. @_parameterized.parameters(
  83. c.op1, c.op2, c.result for c in testcases
  84. )
  85. def testAddition(self, op1, op2, result):
  86. self.assertEqual(result, op1 + op2)
  87. Single-Argument Test Methods
  88. ============================
  89. If a test method takes only one argument, the single argument does not need to
  90. be wrapped into a tuple:
  91. class NegativeNumberExample(_parameterized.TestCase):
  92. @_parameterized.parameters(
  93. -1, -3, -4, -5
  94. )
  95. def testIsNegative(self, arg):
  96. self.assertTrue(IsNegative(arg))
  97. """
  98. __author__ = 'tmarek@google.com (Torsten Marek)'
  99. import functools
  100. import re
  101. import types
  102. import unittest
  103. import uuid
  104. try:
  105. # Since python 3
  106. import collections.abc as collections_abc
  107. except ImportError:
  108. # Won't work after python 3.8
  109. import collections as collections_abc
  110. ADDR_RE = re.compile(r'\<([a-zA-Z0-9_\-\.]+) object at 0x[a-fA-F0-9]+\>')
  111. _SEPARATOR = uuid.uuid1().hex
  112. _FIRST_ARG = object()
  113. _ARGUMENT_REPR = object()
  114. def _CleanRepr(obj):
  115. return ADDR_RE.sub(r'<\1>', repr(obj))
  116. # Helper function formerly from the unittest module, removed from it in
  117. # Python 2.7.
  118. def _StrClass(cls):
  119. return '%s.%s' % (cls.__module__, cls.__name__)
  120. def _NonStringIterable(obj):
  121. return (isinstance(obj, collections_abc.Iterable) and
  122. not isinstance(obj, str))
  123. def _FormatParameterList(testcase_params):
  124. if isinstance(testcase_params, collections_abc.Mapping):
  125. return ', '.join('%s=%s' % (argname, _CleanRepr(value))
  126. for argname, value in testcase_params.items())
  127. elif _NonStringIterable(testcase_params):
  128. return ', '.join(map(_CleanRepr, testcase_params))
  129. else:
  130. return _FormatParameterList((testcase_params,))
  131. class _ParameterizedTestIter(object):
  132. """Callable and iterable class for producing new test cases."""
  133. def __init__(self, test_method, testcases, naming_type):
  134. """Returns concrete test functions for a test and a list of parameters.
  135. The naming_type is used to determine the name of the concrete
  136. functions as reported by the unittest framework. If naming_type is
  137. _FIRST_ARG, the testcases must be tuples, and the first element must
  138. have a string representation that is a valid Python identifier.
  139. Args:
  140. test_method: The decorated test method.
  141. testcases: (list of tuple/dict) A list of parameter
  142. tuples/dicts for individual test invocations.
  143. naming_type: The test naming type, either _NAMED or _ARGUMENT_REPR.
  144. """
  145. self._test_method = test_method
  146. self.testcases = testcases
  147. self._naming_type = naming_type
  148. def __call__(self, *args, **kwargs):
  149. raise RuntimeError('You appear to be running a parameterized test case '
  150. 'without having inherited from parameterized.'
  151. 'TestCase. This is bad because none of '
  152. 'your test cases are actually being run.')
  153. def __iter__(self):
  154. test_method = self._test_method
  155. naming_type = self._naming_type
  156. def MakeBoundParamTest(testcase_params):
  157. @functools.wraps(test_method)
  158. def BoundParamTest(self):
  159. if isinstance(testcase_params, collections_abc.Mapping):
  160. test_method(self, **testcase_params)
  161. elif _NonStringIterable(testcase_params):
  162. test_method(self, *testcase_params)
  163. else:
  164. test_method(self, testcase_params)
  165. if naming_type is _FIRST_ARG:
  166. # Signal the metaclass that the name of the test function is unique
  167. # and descriptive.
  168. BoundParamTest.__x_use_name__ = True
  169. BoundParamTest.__name__ += str(testcase_params[0])
  170. testcase_params = testcase_params[1:]
  171. elif naming_type is _ARGUMENT_REPR:
  172. # __x_extra_id__ is used to pass naming information to the __new__
  173. # method of TestGeneratorMetaclass.
  174. # The metaclass will make sure to create a unique, but nondescriptive
  175. # name for this test.
  176. BoundParamTest.__x_extra_id__ = '(%s)' % (
  177. _FormatParameterList(testcase_params),)
  178. else:
  179. raise RuntimeError('%s is not a valid naming type.' % (naming_type,))
  180. BoundParamTest.__doc__ = '%s(%s)' % (
  181. BoundParamTest.__name__, _FormatParameterList(testcase_params))
  182. if test_method.__doc__:
  183. BoundParamTest.__doc__ += '\n%s' % (test_method.__doc__,)
  184. return BoundParamTest
  185. return (MakeBoundParamTest(c) for c in self.testcases)
  186. def _IsSingletonList(testcases):
  187. """True iff testcases contains only a single non-tuple element."""
  188. return len(testcases) == 1 and not isinstance(testcases[0], tuple)
  189. def _ModifyClass(class_object, testcases, naming_type):
  190. assert not getattr(class_object, '_id_suffix', None), (
  191. 'Cannot add parameters to %s,'
  192. ' which already has parameterized methods.' % (class_object,))
  193. class_object._id_suffix = id_suffix = {}
  194. # We change the size of __dict__ while we iterate over it,
  195. # which Python 3.x will complain about, so use copy().
  196. for name, obj in class_object.__dict__.copy().items():
  197. if (name.startswith(unittest.TestLoader.testMethodPrefix)
  198. and isinstance(obj, types.FunctionType)):
  199. delattr(class_object, name)
  200. methods = {}
  201. _UpdateClassDictForParamTestCase(
  202. methods, id_suffix, name,
  203. _ParameterizedTestIter(obj, testcases, naming_type))
  204. for name, meth in methods.items():
  205. setattr(class_object, name, meth)
  206. def _ParameterDecorator(naming_type, testcases):
  207. """Implementation of the parameterization decorators.
  208. Args:
  209. naming_type: The naming type.
  210. testcases: Testcase parameters.
  211. Returns:
  212. A function for modifying the decorated object.
  213. """
  214. def _Apply(obj):
  215. if isinstance(obj, type):
  216. _ModifyClass(
  217. obj,
  218. list(testcases) if not isinstance(testcases, collections_abc.Sequence)
  219. else testcases,
  220. naming_type)
  221. return obj
  222. else:
  223. return _ParameterizedTestIter(obj, testcases, naming_type)
  224. if _IsSingletonList(testcases):
  225. assert _NonStringIterable(testcases[0]), (
  226. 'Single parameter argument must be a non-string iterable')
  227. testcases = testcases[0]
  228. return _Apply
  229. def parameters(*testcases): # pylint: disable=invalid-name
  230. """A decorator for creating parameterized tests.
  231. See the module docstring for a usage example.
  232. Args:
  233. *testcases: Parameters for the decorated method, either a single
  234. iterable, or a list of tuples/dicts/objects (for tests
  235. with only one argument).
  236. Returns:
  237. A test generator to be handled by TestGeneratorMetaclass.
  238. """
  239. return _ParameterDecorator(_ARGUMENT_REPR, testcases)
  240. def named_parameters(*testcases): # pylint: disable=invalid-name
  241. """A decorator for creating parameterized tests.
  242. See the module docstring for a usage example. The first element of
  243. each parameter tuple should be a string and will be appended to the
  244. name of the test method.
  245. Args:
  246. *testcases: Parameters for the decorated method, either a single
  247. iterable, or a list of tuples.
  248. Returns:
  249. A test generator to be handled by TestGeneratorMetaclass.
  250. """
  251. return _ParameterDecorator(_FIRST_ARG, testcases)
  252. class TestGeneratorMetaclass(type):
  253. """Metaclass for test cases with test generators.
  254. A test generator is an iterable in a testcase that produces callables. These
  255. callables must be single-argument methods. These methods are injected into
  256. the class namespace and the original iterable is removed. If the name of the
  257. iterable conforms to the test pattern, the injected methods will be picked
  258. up as tests by the unittest framework.
  259. In general, it is supposed to be used in conjunction with the
  260. parameters decorator.
  261. """
  262. def __new__(mcs, class_name, bases, dct):
  263. dct['_id_suffix'] = id_suffix = {}
  264. for name, obj in dct.copy().items():
  265. if (name.startswith(unittest.TestLoader.testMethodPrefix) and
  266. _NonStringIterable(obj)):
  267. iterator = iter(obj)
  268. dct.pop(name)
  269. _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator)
  270. return type.__new__(mcs, class_name, bases, dct)
  271. def _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator):
  272. """Adds individual test cases to a dictionary.
  273. Args:
  274. dct: The target dictionary.
  275. id_suffix: The dictionary for mapping names to test IDs.
  276. name: The original name of the test case.
  277. iterator: The iterator generating the individual test cases.
  278. """
  279. for idx, func in enumerate(iterator):
  280. assert callable(func), 'Test generators must yield callables, got %r' % (
  281. func,)
  282. if getattr(func, '__x_use_name__', False):
  283. new_name = func.__name__
  284. else:
  285. new_name = '%s%s%d' % (name, _SEPARATOR, idx)
  286. assert new_name not in dct, (
  287. 'Name of parameterized test case "%s" not unique' % (new_name,))
  288. dct[new_name] = func
  289. id_suffix[new_name] = getattr(func, '__x_extra_id__', '')
  290. class TestCase(unittest.TestCase, metaclass=TestGeneratorMetaclass):
  291. """Base class for test cases using the parameters decorator."""
  292. def _OriginalName(self):
  293. return self._testMethodName.split(_SEPARATOR)[0]
  294. def __str__(self):
  295. return '%s (%s)' % (self._OriginalName(), _StrClass(self.__class__))
  296. def id(self): # pylint: disable=invalid-name
  297. """Returns the descriptive ID of the test.
  298. This is used internally by the unittesting framework to get a name
  299. for the test to be used in reports.
  300. Returns:
  301. The test id.
  302. """
  303. return '%s.%s%s' % (_StrClass(self.__class__),
  304. self._OriginalName(),
  305. self._id_suffix.get(self._testMethodName, ''))
  306. def CoopTestCase(other_base_class):
  307. """Returns a new base class with a cooperative metaclass base.
  308. This enables the TestCase to be used in combination
  309. with other base classes that have custom metaclasses, such as
  310. mox.MoxTestBase.
  311. Only works with metaclasses that do not override type.__new__.
  312. Example:
  313. import google3
  314. import mox
  315. from google.protobuf.internal import _parameterized
  316. class ExampleTest(parameterized.CoopTestCase(mox.MoxTestBase)):
  317. ...
  318. Args:
  319. other_base_class: (class) A test case base class.
  320. Returns:
  321. A new class object.
  322. """
  323. metaclass = type(
  324. 'CoopMetaclass',
  325. (other_base_class.__metaclass__,
  326. TestGeneratorMetaclass), {})
  327. return metaclass(
  328. 'CoopTestCase',
  329. (other_base_class, TestCase), {})