您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

311 行
9.7KB

  1. # -*- coding: utf-8 -*-
  2. # This file is a part of DDT (https://github.com/txels/ddt)
  3. # Copyright 2012-2015 Carles Barrobés and DDT contributors
  4. # For the exact contribution history, see the git revision log.
  5. # DDT is licensed under the MIT License, included in
  6. # https://github.com/txels/ddt/blob/master/LICENSE.md
  7. import inspect
  8. import json
  9. import os
  10. import re
  11. import codecs
  12. from functools import wraps
  13. try:
  14. import yaml
  15. except ImportError: # pragma: no cover
  16. _have_yaml = False
  17. else:
  18. _have_yaml = True
  19. __version__ = '1.2.1'
  20. # These attributes will not conflict with any real python attribute
  21. # They are added to the decorated test method and processed later
  22. # by the `ddt` class decorator.
  23. DATA_ATTR = '%values' # store the data the test must run with
  24. FILE_ATTR = '%file_path' # store the path to JSON file
  25. UNPACK_ATTR = '%unpack' # remember that we have to unpack values
  26. index_len = 5 # default max length of case index
  27. try:
  28. trivial_types = (type(None), bool, int, float, basestring)
  29. except NameError:
  30. trivial_types = (type(None), bool, int, float, str)
  31. def is_trivial(value):
  32. if isinstance(value, trivial_types):
  33. return True
  34. elif isinstance(value, (list, tuple)):
  35. return all(map(is_trivial, value))
  36. return False
  37. def unpack(func):
  38. """
  39. Method decorator to add unpack feature.
  40. """
  41. setattr(func, UNPACK_ATTR, True)
  42. return func
  43. def data(*values):
  44. """
  45. Method decorator to add to your test methods.
  46. Should be added to methods of instances of ``unittest.TestCase``.
  47. """
  48. global index_len
  49. index_len = len(str(len(values)))
  50. return idata(values)
  51. def idata(iterable):
  52. """
  53. Method decorator to add to your test methods.
  54. Should be added to methods of instances of ``unittest.TestCase``.
  55. """
  56. def wrapper(func):
  57. setattr(func, DATA_ATTR, iterable)
  58. return func
  59. return wrapper
  60. def file_data(value):
  61. """
  62. Method decorator to add to your test methods.
  63. Should be added to methods of instances of ``unittest.TestCase``.
  64. ``value`` should be a path relative to the directory of the file
  65. containing the decorated ``unittest.TestCase``. The file
  66. should contain JSON encoded data, that can either be a list or a
  67. dict.
  68. In case of a list, each value in the list will correspond to one
  69. test case, and the value will be concatenated to the test method
  70. name.
  71. In case of a dict, keys will be used as suffixes to the name of the
  72. test case, and values will be fed as test data.
  73. """
  74. def wrapper(func):
  75. setattr(func, FILE_ATTR, value)
  76. return func
  77. return wrapper
  78. def mk_test_name(name, value, index=0):
  79. """
  80. Generate a new name for a test case.
  81. It will take the original test name and append an ordinal index and a
  82. string representation of the value, and convert the result into a valid
  83. python identifier by replacing extraneous characters with ``_``.
  84. We avoid doing str(value) if dealing with non-trivial values.
  85. The problem is possible different names with different runs, e.g.
  86. different order of dictionary keys (see PYTHONHASHSEED) or dealing
  87. with mock objects.
  88. Trivial scalar values are passed as is.
  89. A "trivial" value is a plain scalar, or a tuple or list consisting
  90. only of trivial values.
  91. """
  92. # Add zeros before index to keep order
  93. index = "{0:0{1}}".format(index + 1, index_len)
  94. if not is_trivial(value):
  95. return "{0}_{1}".format(name, index)
  96. try:
  97. value = str(value)
  98. except UnicodeEncodeError:
  99. # fallback for python2
  100. value = value.encode('ascii', 'backslashreplace')
  101. test_name = "{0}_{1}_{2}".format(name, index, value)
  102. return re.sub(r'\W|^(?=\d)', '_', test_name)
  103. def feed_data(func, new_name, test_data_docstring, *args, **kwargs):
  104. """
  105. This internal method decorator feeds the test data item to the test.
  106. """
  107. @wraps(func)
  108. def wrapper(self):
  109. return func(self, *args, **kwargs)
  110. wrapper.__name__ = new_name
  111. wrapper.__wrapped__ = func
  112. # set docstring if exists
  113. if test_data_docstring is not None:
  114. wrapper.__doc__ = test_data_docstring
  115. else:
  116. # Try to call format on the docstring
  117. if func.__doc__:
  118. try:
  119. wrapper.__doc__ = func.__doc__.format(*args, **kwargs)
  120. except (IndexError, KeyError):
  121. # Maybe the user has added some of the formating strings
  122. # unintentionally in the docstring. Do not raise an exception
  123. # as it could be that user is not aware of the
  124. # formating feature.
  125. pass
  126. return wrapper
  127. def add_test(cls, test_name, test_docstring, func, *args, **kwargs):
  128. """
  129. Add a test case to this class.
  130. The test will be based on an existing function but will give it a new
  131. name.
  132. """
  133. setattr(cls, test_name, feed_data(func, test_name, test_docstring,
  134. *args, **kwargs))
  135. def process_file_data(cls, name, func, file_attr):
  136. """
  137. Process the parameter in the `file_data` decorator.
  138. """
  139. cls_path = os.path.abspath(inspect.getsourcefile(cls))
  140. data_file_path = os.path.join(os.path.dirname(cls_path), file_attr)
  141. def create_error_func(message): # pylint: disable-msg=W0613
  142. def func(*args):
  143. raise ValueError(message % file_attr)
  144. return func
  145. # If file does not exist, provide an error function instead
  146. if not os.path.exists(data_file_path):
  147. test_name = mk_test_name(name, "error")
  148. test_docstring = """Error!"""
  149. add_test(cls, test_name, test_docstring,
  150. create_error_func("%s does not exist"), None)
  151. return
  152. _is_yaml_file = data_file_path.endswith((".yml", ".yaml"))
  153. # Don't have YAML but want to use YAML file.
  154. if _is_yaml_file and not _have_yaml:
  155. test_name = mk_test_name(name, "error")
  156. test_docstring = """Error!"""
  157. add_test(
  158. cls,
  159. test_name,
  160. test_docstring,
  161. create_error_func("%s is a YAML file, please install PyYAML"),
  162. None
  163. )
  164. return
  165. with codecs.open(data_file_path, 'r', 'utf-8') as f:
  166. # Load the data from YAML or JSON
  167. if _is_yaml_file:
  168. data = yaml.safe_load(f)
  169. else:
  170. data = json.load(f)
  171. _add_tests_from_data(cls, name, func, data)
  172. def _add_tests_from_data(cls, name, func, data):
  173. """
  174. Add tests from data loaded from the data file into the class
  175. """
  176. for i, elem in enumerate(data):
  177. if isinstance(data, dict):
  178. key, value = elem, data[elem]
  179. test_name = mk_test_name(name, key, i)
  180. elif isinstance(data, list):
  181. value = elem
  182. test_name = mk_test_name(name, value, i)
  183. if isinstance(value, dict):
  184. add_test(cls, test_name, test_name, func, **value)
  185. else:
  186. add_test(cls, test_name, test_name, func, value)
  187. def _is_primitive(obj):
  188. """Finds out if the obj is a "primitive". It is somewhat hacky but it works.
  189. """
  190. return not hasattr(obj, '__dict__')
  191. def _get_test_data_docstring(func, value):
  192. """Returns a docstring based on the following resolution strategy:
  193. 1. Passed value is not a "primitive" and has a docstring, then use it.
  194. 2. In all other cases return None, i.e the test name is used.
  195. """
  196. if not _is_primitive(value) and value.__doc__:
  197. return value.__doc__
  198. else:
  199. return None
  200. def ddt(cls):
  201. """
  202. Class decorator for subclasses of ``unittest.TestCase``.
  203. Apply this decorator to the test case class, and then
  204. decorate test methods with ``@data``.
  205. For each method decorated with ``@data``, this will effectively create as
  206. many methods as data items are passed as parameters to ``@data``.
  207. The names of the test methods follow the pattern
  208. ``original_test_name_{ordinal}_{data}``. ``ordinal`` is the position of the
  209. data argument, starting with 1.
  210. For data we use a string representation of the data value converted into a
  211. valid python identifier. If ``data.__name__`` exists, we use that instead.
  212. For each method decorated with ``@file_data('test_data.json')``, the
  213. decorator will try to load the test_data.json file located relative
  214. to the python file containing the method that is decorated. It will,
  215. for each ``test_name`` key create as many methods in the list of values
  216. from the ``data`` key.
  217. """
  218. for name, func in list(cls.__dict__.items()):
  219. if hasattr(func, DATA_ATTR):
  220. for i, v in enumerate(getattr(func, DATA_ATTR)):
  221. test_name = mk_test_name(name, getattr(v, "__name__", v), i)
  222. test_data_docstring = _get_test_data_docstring(func, v)
  223. if hasattr(func, UNPACK_ATTR):
  224. if isinstance(v, tuple) or isinstance(v, list):
  225. add_test(
  226. cls,
  227. test_name,
  228. test_data_docstring,
  229. func,
  230. *v
  231. )
  232. else:
  233. # unpack dictionary
  234. add_test(
  235. cls,
  236. test_name,
  237. test_data_docstring,
  238. func,
  239. **v
  240. )
  241. else:
  242. add_test(cls, test_name, test_data_docstring, func, v)
  243. delattr(cls, name)
  244. elif hasattr(func, FILE_ATTR):
  245. file_attr = getattr(func, FILE_ATTR)
  246. process_file_data(cls, name, func, file_attr)
  247. delattr(cls, name)
  248. return cls