parameterized.py 18 KB

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