parameterized.py 16 KB

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