_parameterized.py 15 KB

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