店播爬取Python脚本

_parameterized.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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.TestCase):
  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 individual test cases can be tuples (with positional parameters)
  48. or dictionaries (with named parameters):
  49. class AdditionExample(parameterized.TestCase):
  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 named_parameters 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.TestCase):
  73. @parameterized.named_parameters(
  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. TestCase 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.TestCase):
  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.TestCase):
  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.TestCase):
  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 functools
  123. import re
  124. import types
  125. try:
  126. import unittest2 as unittest
  127. except ImportError:
  128. import unittest
  129. import uuid
  130. import six
  131. try:
  132. # Since python 3
  133. import collections.abc as collections_abc
  134. except ImportError:
  135. # Won't work after python 3.8
  136. import collections as collections_abc
  137. ADDR_RE = re.compile(r'\<([a-zA-Z0-9_\-\.]+) object at 0x[a-fA-F0-9]+\>')
  138. _SEPARATOR = uuid.uuid1().hex
  139. _FIRST_ARG = object()
  140. _ARGUMENT_REPR = object()
  141. def _CleanRepr(obj):
  142. return ADDR_RE.sub(r'<\1>', repr(obj))
  143. # Helper function formerly from the unittest module, removed from it in
  144. # Python 2.7.
  145. def _StrClass(cls):
  146. return '%s.%s' % (cls.__module__, cls.__name__)
  147. def _NonStringIterable(obj):
  148. return (isinstance(obj, collections_abc.Iterable) and not
  149. isinstance(obj, six.string_types))
  150. def _FormatParameterList(testcase_params):
  151. if isinstance(testcase_params, collections_abc.Mapping):
  152. return ', '.join('%s=%s' % (argname, _CleanRepr(value))
  153. for argname, value in testcase_params.items())
  154. elif _NonStringIterable(testcase_params):
  155. return ', '.join(map(_CleanRepr, testcase_params))
  156. else:
  157. return _FormatParameterList((testcase_params,))
  158. class _ParameterizedTestIter(object):
  159. """Callable and iterable class for producing new test cases."""
  160. def __init__(self, test_method, testcases, naming_type):
  161. """Returns concrete test functions for a test and a list of parameters.
  162. The naming_type is used to determine the name of the concrete
  163. functions as reported by the unittest framework. If naming_type is
  164. _FIRST_ARG, the testcases must be tuples, and the first element must
  165. have a string representation that is a valid Python identifier.
  166. Args:
  167. test_method: The decorated test method.
  168. testcases: (list of tuple/dict) A list of parameter
  169. tuples/dicts for individual test invocations.
  170. naming_type: The test naming type, either _NAMED or _ARGUMENT_REPR.
  171. """
  172. self._test_method = test_method
  173. self.testcases = testcases
  174. self._naming_type = naming_type
  175. def __call__(self, *args, **kwargs):
  176. raise RuntimeError('You appear to be running a parameterized test case '
  177. 'without having inherited from parameterized.'
  178. 'TestCase. This is bad because none of '
  179. 'your test cases are actually being run.')
  180. def __iter__(self):
  181. test_method = self._test_method
  182. naming_type = self._naming_type
  183. def MakeBoundParamTest(testcase_params):
  184. @functools.wraps(test_method)
  185. def BoundParamTest(self):
  186. if isinstance(testcase_params, collections_abc.Mapping):
  187. test_method(self, **testcase_params)
  188. elif _NonStringIterable(testcase_params):
  189. test_method(self, *testcase_params)
  190. else:
  191. test_method(self, testcase_params)
  192. if naming_type is _FIRST_ARG:
  193. # Signal the metaclass that the name of the test function is unique
  194. # and descriptive.
  195. BoundParamTest.__x_use_name__ = True
  196. BoundParamTest.__name__ += str(testcase_params[0])
  197. testcase_params = testcase_params[1:]
  198. elif naming_type is _ARGUMENT_REPR:
  199. # __x_extra_id__ is used to pass naming information to the __new__
  200. # method of TestGeneratorMetaclass.
  201. # The metaclass will make sure to create a unique, but nondescriptive
  202. # name for this test.
  203. BoundParamTest.__x_extra_id__ = '(%s)' % (
  204. _FormatParameterList(testcase_params),)
  205. else:
  206. raise RuntimeError('%s is not a valid naming type.' % (naming_type,))
  207. BoundParamTest.__doc__ = '%s(%s)' % (
  208. BoundParamTest.__name__, _FormatParameterList(testcase_params))
  209. if test_method.__doc__:
  210. BoundParamTest.__doc__ += '\n%s' % (test_method.__doc__,)
  211. return BoundParamTest
  212. return (MakeBoundParamTest(c) for c in self.testcases)
  213. def _IsSingletonList(testcases):
  214. """True iff testcases contains only a single non-tuple element."""
  215. return len(testcases) == 1 and not isinstance(testcases[0], tuple)
  216. def _ModifyClass(class_object, testcases, naming_type):
  217. assert not getattr(class_object, '_id_suffix', None), (
  218. 'Cannot add parameters to %s,'
  219. ' which already has parameterized methods.' % (class_object,))
  220. class_object._id_suffix = id_suffix = {}
  221. # We change the size of __dict__ while we iterate over it,
  222. # which Python 3.x will complain about, so use copy().
  223. for name, obj in class_object.__dict__.copy().items():
  224. if (name.startswith(unittest.TestLoader.testMethodPrefix)
  225. and isinstance(obj, types.FunctionType)):
  226. delattr(class_object, name)
  227. methods = {}
  228. _UpdateClassDictForParamTestCase(
  229. methods, id_suffix, name,
  230. _ParameterizedTestIter(obj, testcases, naming_type))
  231. for name, meth in methods.items():
  232. setattr(class_object, name, meth)
  233. def _ParameterDecorator(naming_type, testcases):
  234. """Implementation of the parameterization decorators.
  235. Args:
  236. naming_type: The naming type.
  237. testcases: Testcase parameters.
  238. Returns:
  239. A function for modifying the decorated object.
  240. """
  241. def _Apply(obj):
  242. if isinstance(obj, type):
  243. _ModifyClass(
  244. obj,
  245. list(testcases) if not isinstance(testcases, collections_abc.Sequence)
  246. else testcases,
  247. naming_type)
  248. return obj
  249. else:
  250. return _ParameterizedTestIter(obj, testcases, naming_type)
  251. if _IsSingletonList(testcases):
  252. assert _NonStringIterable(testcases[0]), (
  253. 'Single parameter argument must be a non-string iterable')
  254. testcases = testcases[0]
  255. return _Apply
  256. def parameters(*testcases): # pylint: disable=invalid-name
  257. """A decorator for creating parameterized tests.
  258. See the module docstring for a usage example.
  259. Args:
  260. *testcases: Parameters for the decorated method, either a single
  261. iterable, or a list of tuples/dicts/objects (for tests
  262. with only one argument).
  263. Returns:
  264. A test generator to be handled by TestGeneratorMetaclass.
  265. """
  266. return _ParameterDecorator(_ARGUMENT_REPR, testcases)
  267. def named_parameters(*testcases): # pylint: disable=invalid-name
  268. """A decorator for creating parameterized tests.
  269. See the module docstring for a usage example. The first element of
  270. each parameter tuple should be a string and will be appended to the
  271. name of the test method.
  272. Args:
  273. *testcases: Parameters for the decorated method, either a single
  274. iterable, or a list of tuples.
  275. Returns:
  276. A test generator to be handled by TestGeneratorMetaclass.
  277. """
  278. return _ParameterDecorator(_FIRST_ARG, testcases)
  279. class TestGeneratorMetaclass(type):
  280. """Metaclass for test cases with test generators.
  281. A test generator is an iterable in a testcase that produces callables. These
  282. callables must be single-argument methods. These methods are injected into
  283. the class namespace and the original iterable is removed. If the name of the
  284. iterable conforms to the test pattern, the injected methods will be picked
  285. up as tests by the unittest framework.
  286. In general, it is supposed to be used in conjunction with the
  287. parameters decorator.
  288. """
  289. def __new__(mcs, class_name, bases, dct):
  290. dct['_id_suffix'] = id_suffix = {}
  291. for name, obj in dct.items():
  292. if (name.startswith(unittest.TestLoader.testMethodPrefix) and
  293. _NonStringIterable(obj)):
  294. iterator = iter(obj)
  295. dct.pop(name)
  296. _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator)
  297. return type.__new__(mcs, class_name, bases, dct)
  298. def _UpdateClassDictForParamTestCase(dct, id_suffix, name, iterator):
  299. """Adds individual test cases to a dictionary.
  300. Args:
  301. dct: The target dictionary.
  302. id_suffix: The dictionary for mapping names to test IDs.
  303. name: The original name of the test case.
  304. iterator: The iterator generating the individual test cases.
  305. """
  306. for idx, func in enumerate(iterator):
  307. assert callable(func), 'Test generators must yield callables, got %r' % (
  308. func,)
  309. if getattr(func, '__x_use_name__', False):
  310. new_name = func.__name__
  311. else:
  312. new_name = '%s%s%d' % (name, _SEPARATOR, idx)
  313. assert new_name not in dct, (
  314. 'Name of parameterized test case "%s" not unique' % (new_name,))
  315. dct[new_name] = func
  316. id_suffix[new_name] = getattr(func, '__x_extra_id__', '')
  317. class TestCase(unittest.TestCase):
  318. """Base class for test cases using the parameters decorator."""
  319. __metaclass__ = TestGeneratorMetaclass
  320. def _OriginalName(self):
  321. return self._testMethodName.split(_SEPARATOR)[0]
  322. def __str__(self):
  323. return '%s (%s)' % (self._OriginalName(), _StrClass(self.__class__))
  324. def id(self): # pylint: disable=invalid-name
  325. """Returns the descriptive ID of the test.
  326. This is used internally by the unittesting framework to get a name
  327. for the test to be used in reports.
  328. Returns:
  329. The test id.
  330. """
  331. return '%s.%s%s' % (_StrClass(self.__class__),
  332. self._OriginalName(),
  333. self._id_suffix.get(self._testMethodName, ''))
  334. def CoopTestCase(other_base_class):
  335. """Returns a new base class with a cooperative metaclass base.
  336. This enables the TestCase to be used in combination
  337. with other base classes that have custom metaclasses, such as
  338. mox.MoxTestBase.
  339. Only works with metaclasses that do not override type.__new__.
  340. Example:
  341. import google3
  342. import mox
  343. from google3.testing.pybase import parameterized
  344. class ExampleTest(parameterized.CoopTestCase(mox.MoxTestBase)):
  345. ...
  346. Args:
  347. other_base_class: (class) A test case base class.
  348. Returns:
  349. A new class object.
  350. """
  351. metaclass = type(
  352. 'CoopMetaclass',
  353. (other_base_class.__metaclass__,
  354. TestGeneratorMetaclass), {})
  355. return metaclass(
  356. 'CoopTestCase',
  357. (other_base_class, TestCase), {})