parameterized.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. """
  2. tl;dr: all code code is licensed under simplified BSD, unless stated otherwise.
  3. Unless stated otherwise in the source files, all code is copyright 2010 David
  4. Wolever <david@wolever.net>. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are met:
  7. 1. Redistributions of source code must retain the above copyright notice,
  8. this list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright notice,
  10. this list of conditions and the following disclaimer in the documentation
  11. and/or other materials provided with the distribution.
  12. THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR
  13. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  14. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  15. EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  16. INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  17. BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  18. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  19. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  20. OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  21. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. The views and conclusions contained in the software and documentation are those
  23. of the authors and should not be interpreted as representing official policies,
  24. either expressed or implied, of David Wolever.
  25. """
  26. import re
  27. import inspect
  28. import warnings
  29. from functools import wraps
  30. from types import MethodType
  31. from collections import namedtuple
  32. try:
  33. from collections import OrderedDict as MaybeOrderedDict
  34. except ImportError:
  35. MaybeOrderedDict = dict
  36. from unittest import TestCase
  37. _param = namedtuple("param", "args kwargs")
  38. class param(_param):
  39. """ Represents a single parameter to a test case.
  40. For example::
  41. >>> p = param("foo", bar=16)
  42. >>> p
  43. param("foo", bar=16)
  44. >>> p.args
  45. ('foo', )
  46. >>> p.kwargs
  47. {'bar': 16}
  48. Intended to be used as an argument to ``@parameterized``::
  49. @parameterized([
  50. param("foo", bar=16),
  51. ])
  52. def test_stuff(foo, bar=16):
  53. pass
  54. """
  55. def __new__(cls, *args , **kwargs):
  56. return _param.__new__(cls, args, kwargs)
  57. @classmethod
  58. def explicit(cls, args=None, kwargs=None):
  59. """ Creates a ``param`` by explicitly specifying ``args`` and
  60. ``kwargs``::
  61. >>> param.explicit([1,2,3])
  62. param(*(1, 2, 3))
  63. >>> param.explicit(kwargs={"foo": 42})
  64. param(*(), **{"foo": "42"})
  65. """
  66. args = args or ()
  67. kwargs = kwargs or {}
  68. return cls(*args, **kwargs)
  69. @classmethod
  70. def from_decorator(cls, args):
  71. """ Returns an instance of ``param()`` for ``@parameterized`` argument
  72. ``args``::
  73. >>> param.from_decorator((42, ))
  74. param(args=(42, ), kwargs={})
  75. >>> param.from_decorator("foo")
  76. param(args=("foo", ), kwargs={})
  77. """
  78. if isinstance(args, param):
  79. return args
  80. elif isinstance(args, (str,)):
  81. args = (args, )
  82. try:
  83. return cls(*args)
  84. except TypeError as e:
  85. if "after * must be" not in str(e):
  86. raise
  87. raise TypeError(
  88. "Parameters must be tuples, but %r is not (hint: use '(%r, )')"
  89. %(args, args),
  90. )
  91. def __repr__(self):
  92. return "param(*%r, **%r)" %self
  93. class QuietOrderedDict(MaybeOrderedDict):
  94. """ When OrderedDict is available, use it to make sure that the kwargs in
  95. doc strings are consistently ordered. """
  96. __str__ = dict.__str__
  97. __repr__ = dict.__repr__
  98. def parameterized_argument_value_pairs(func, p):
  99. """Return tuples of parameterized arguments and their values.
  100. This is useful if you are writing your own doc_func
  101. function and need to know the values for each parameter name::
  102. >>> def func(a, foo=None, bar=42, **kwargs): pass
  103. >>> p = param(1, foo=7, extra=99)
  104. >>> parameterized_argument_value_pairs(func, p)
  105. [("a", 1), ("foo", 7), ("bar", 42), ("**kwargs", {"extra": 99})]
  106. If the function's first argument is named ``self`` then it will be
  107. ignored::
  108. >>> def func(self, a): pass
  109. >>> p = param(1)
  110. >>> parameterized_argument_value_pairs(func, p)
  111. [("a", 1)]
  112. Additionally, empty ``*args`` or ``**kwargs`` will be ignored::
  113. >>> def func(foo, *args): pass
  114. >>> p = param(1)
  115. >>> parameterized_argument_value_pairs(func, p)
  116. [("foo", 1)]
  117. >>> p = param(1, 16)
  118. >>> parameterized_argument_value_pairs(func, p)
  119. [("foo", 1), ("*args", (16, ))]
  120. """
  121. argspec = inspect.getargspec(func)
  122. arg_offset = 1 if argspec.args[:1] == ["self"] else 0
  123. named_args = argspec.args[arg_offset:]
  124. result = list(zip(named_args, p.args))
  125. named_args = argspec.args[len(result) + arg_offset:]
  126. varargs = p.args[len(result):]
  127. result.extend([
  128. (name, p.kwargs.get(name, default))
  129. for (name, default)
  130. in zip(named_args, argspec.defaults or [])
  131. ])
  132. seen_arg_names = {n for (n, _) in result}
  133. keywords = QuietOrderedDict(sorted([
  134. (name, p.kwargs[name])
  135. for name in p.kwargs
  136. if name not in seen_arg_names
  137. ]))
  138. if varargs:
  139. result.append(("*%s" %(argspec.varargs, ), tuple(varargs)))
  140. if keywords:
  141. result.append(("**%s" %(argspec.keywords, ), keywords))
  142. return result
  143. def short_repr(x, n=64):
  144. """ A shortened repr of ``x`` which is guaranteed to be ``unicode``::
  145. >>> short_repr("foo")
  146. u"foo"
  147. >>> short_repr("123456789", n=4)
  148. u"12...89"
  149. """
  150. x_repr = repr(x)
  151. if isinstance(x_repr, bytes):
  152. try:
  153. x_repr = str(x_repr, "utf-8")
  154. except UnicodeDecodeError:
  155. x_repr = str(x_repr, "latin1")
  156. if len(x_repr) > n:
  157. x_repr = x_repr[:n//2] + "..." + x_repr[len(x_repr) - n//2:]
  158. return x_repr
  159. def default_doc_func(func, num, p):
  160. if func.__doc__ is None:
  161. return None
  162. all_args_with_values = parameterized_argument_value_pairs(func, p)
  163. # Assumes that the function passed is a bound method.
  164. descs = [f'{n}={short_repr(v)}' for n, v in all_args_with_values]
  165. # The documentation might be a multiline string, so split it
  166. # and just work with the first string, ignoring the period
  167. # at the end if there is one.
  168. first, nl, rest = func.__doc__.lstrip().partition("\n")
  169. suffix = ""
  170. if first.endswith("."):
  171. suffix = "."
  172. first = first[:-1]
  173. args = "%s[with %s]" %(len(first) and " " or "", ", ".join(descs))
  174. return "".join([first.rstrip(), args, suffix, nl, rest])
  175. def default_name_func(func, num, p):
  176. base_name = func.__name__
  177. name_suffix = "_%s" %(num, )
  178. if len(p.args) > 0 and isinstance(p.args[0], (str,)):
  179. name_suffix += "_" + parameterized.to_safe_name(p.args[0])
  180. return base_name + name_suffix
  181. # force nose for numpy purposes.
  182. _test_runner_override = 'nose'
  183. _test_runner_guess = False
  184. _test_runners = set(["unittest", "unittest2", "nose", "nose2", "pytest"])
  185. _test_runner_aliases = {
  186. "_pytest": "pytest",
  187. }
  188. def set_test_runner(name):
  189. global _test_runner_override
  190. if name not in _test_runners:
  191. raise TypeError(
  192. "Invalid test runner: %r (must be one of: %s)"
  193. %(name, ", ".join(_test_runners)),
  194. )
  195. _test_runner_override = name
  196. def detect_runner():
  197. """ Guess which test runner we're using by traversing the stack and looking
  198. for the first matching module. This *should* be reasonably safe, as
  199. it's done during test discovery where the test runner should be the
  200. stack frame immediately outside. """
  201. if _test_runner_override is not None:
  202. return _test_runner_override
  203. global _test_runner_guess
  204. if _test_runner_guess is False:
  205. stack = inspect.stack()
  206. for record in reversed(stack):
  207. frame = record[0]
  208. module = frame.f_globals.get("__name__").partition(".")[0]
  209. if module in _test_runner_aliases:
  210. module = _test_runner_aliases[module]
  211. if module in _test_runners:
  212. _test_runner_guess = module
  213. break
  214. else:
  215. _test_runner_guess = None
  216. return _test_runner_guess
  217. class parameterized:
  218. """ Parameterize a test case::
  219. class TestInt:
  220. @parameterized([
  221. ("A", 10),
  222. ("F", 15),
  223. param("10", 42, base=42)
  224. ])
  225. def test_int(self, input, expected, base=16):
  226. actual = int(input, base=base)
  227. assert_equal(actual, expected)
  228. @parameterized([
  229. (2, 3, 5)
  230. (3, 5, 8),
  231. ])
  232. def test_add(a, b, expected):
  233. assert_equal(a + b, expected)
  234. """
  235. def __init__(self, input, doc_func=None):
  236. self.get_input = self.input_as_callable(input)
  237. self.doc_func = doc_func or default_doc_func
  238. def __call__(self, test_func):
  239. self.assert_not_in_testcase_subclass()
  240. @wraps(test_func)
  241. def wrapper(test_self=None):
  242. test_cls = test_self and type(test_self)
  243. original_doc = wrapper.__doc__
  244. for num, args in enumerate(wrapper.parameterized_input):
  245. p = param.from_decorator(args)
  246. unbound_func, nose_tuple = self.param_as_nose_tuple(test_self, test_func, num, p)
  247. try:
  248. wrapper.__doc__ = nose_tuple[0].__doc__
  249. # Nose uses `getattr(instance, test_func.__name__)` to get
  250. # a method bound to the test instance (as opposed to a
  251. # method bound to the instance of the class created when
  252. # tests were being enumerated). Set a value here to make
  253. # sure nose can get the correct test method.
  254. if test_self is not None:
  255. setattr(test_cls, test_func.__name__, unbound_func)
  256. yield nose_tuple
  257. finally:
  258. if test_self is not None:
  259. delattr(test_cls, test_func.__name__)
  260. wrapper.__doc__ = original_doc
  261. wrapper.parameterized_input = self.get_input()
  262. wrapper.parameterized_func = test_func
  263. test_func.__name__ = "_parameterized_original_%s" %(test_func.__name__, )
  264. return wrapper
  265. def param_as_nose_tuple(self, test_self, func, num, p):
  266. nose_func = wraps(func)(lambda *args: func(*args[:-1], **args[-1]))
  267. nose_func.__doc__ = self.doc_func(func, num, p)
  268. # Track the unbound function because we need to setattr the unbound
  269. # function onto the class for nose to work (see comments above), and
  270. # Python 3 doesn't let us pull the function out of a bound method.
  271. unbound_func = nose_func
  272. if test_self is not None:
  273. nose_func = MethodType(nose_func, test_self)
  274. return unbound_func, (nose_func, ) + p.args + (p.kwargs or {}, )
  275. def assert_not_in_testcase_subclass(self):
  276. parent_classes = self._terrible_magic_get_defining_classes()
  277. if any(issubclass(cls, TestCase) for cls in parent_classes):
  278. raise Exception("Warning: '@parameterized' tests won't work "
  279. "inside subclasses of 'TestCase' - use "
  280. "'@parameterized.expand' instead.")
  281. def _terrible_magic_get_defining_classes(self):
  282. """ Returns the set of parent classes of the class currently being defined.
  283. Will likely only work if called from the ``parameterized`` decorator.
  284. This function is entirely @brandon_rhodes's fault, as he suggested
  285. the implementation: http://stackoverflow.com/a/8793684/71522
  286. """
  287. stack = inspect.stack()
  288. if len(stack) <= 4:
  289. return []
  290. frame = stack[4]
  291. code_context = frame[4] and frame[4][0].strip()
  292. if not (code_context and code_context.startswith("class ")):
  293. return []
  294. _, _, parents = code_context.partition("(")
  295. parents, _, _ = parents.partition(")")
  296. return eval("[" + parents + "]", frame[0].f_globals, frame[0].f_locals)
  297. @classmethod
  298. def input_as_callable(cls, input):
  299. if callable(input):
  300. return lambda: cls.check_input_values(input())
  301. input_values = cls.check_input_values(input)
  302. return lambda: input_values
  303. @classmethod
  304. def check_input_values(cls, input_values):
  305. # Explicitly convert non-list inputs to a list so that:
  306. # 1. A helpful exception will be raised if they aren't iterable, and
  307. # 2. Generators are unwrapped exactly once (otherwise `nosetests
  308. # --processes=n` has issues; see:
  309. # https://github.com/wolever/nose-parameterized/pull/31)
  310. if not isinstance(input_values, list):
  311. input_values = list(input_values)
  312. return [ param.from_decorator(p) for p in input_values ]
  313. @classmethod
  314. def expand(cls, input, name_func=None, doc_func=None, **legacy):
  315. """ A "brute force" method of parameterizing test cases. Creates new
  316. test cases and injects them into the namespace that the wrapped
  317. function is being defined in. Useful for parameterizing tests in
  318. subclasses of 'UnitTest', where Nose test generators don't work.
  319. >>> @parameterized.expand([("foo", 1, 2)])
  320. ... def test_add1(name, input, expected):
  321. ... actual = add1(input)
  322. ... assert_equal(actual, expected)
  323. ...
  324. >>> locals()
  325. ... 'test_add1_foo_0': <function ...> ...
  326. >>>
  327. """
  328. if "testcase_func_name" in legacy:
  329. warnings.warn("testcase_func_name= is deprecated; use name_func=",
  330. DeprecationWarning, stacklevel=2)
  331. if not name_func:
  332. name_func = legacy["testcase_func_name"]
  333. if "testcase_func_doc" in legacy:
  334. warnings.warn("testcase_func_doc= is deprecated; use doc_func=",
  335. DeprecationWarning, stacklevel=2)
  336. if not doc_func:
  337. doc_func = legacy["testcase_func_doc"]
  338. doc_func = doc_func or default_doc_func
  339. name_func = name_func or default_name_func
  340. def parameterized_expand_wrapper(f, instance=None):
  341. stack = inspect.stack()
  342. frame = stack[1]
  343. frame_locals = frame[0].f_locals
  344. parameters = cls.input_as_callable(input)()
  345. for num, p in enumerate(parameters):
  346. name = name_func(f, num, p)
  347. frame_locals[name] = cls.param_as_standalone_func(p, f, name)
  348. frame_locals[name].__doc__ = doc_func(f, num, p)
  349. f.__test__ = False
  350. return parameterized_expand_wrapper
  351. @classmethod
  352. def param_as_standalone_func(cls, p, func, name):
  353. @wraps(func)
  354. def standalone_func(*a):
  355. return func(*(a + p.args), **p.kwargs)
  356. standalone_func.__name__ = name
  357. # place_as is used by py.test to determine what source file should be
  358. # used for this test.
  359. standalone_func.place_as = func
  360. # Remove __wrapped__ because py.test will try to look at __wrapped__
  361. # to determine which parameters should be used with this test case,
  362. # and obviously we don't need it to do any parameterization.
  363. try:
  364. del standalone_func.__wrapped__
  365. except AttributeError:
  366. pass
  367. return standalone_func
  368. @classmethod
  369. def to_safe_name(cls, s):
  370. return str(re.sub("[^a-zA-Z0-9_]+", "_", s))