parameterized.py 18 KB

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