checkers.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.gunittest.checkers
  3. @brief GRASS Python testing framework checkers
  4. Copyright (C) 2014 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. @author Vaclav Petras
  9. @author Soeren Gebbert
  10. """
  11. import sys
  12. import re
  13. import doctest
  14. import grass.script.core as gcore
  15. # alternative term to check(er(s)) would be compare
  16. def unify_projection(dic):
  17. """Unifies names of projections.
  18. Some projections are referred using different names like
  19. 'Universal Transverse Mercator' and 'Universe Transverse Mercator'.
  20. This function replaces synonyms by a unified name.
  21. Example of common typo in UTM replaced by correct spelling::
  22. >>> unify_projection({'name': ['Universe Transverse Mercator']})
  23. {'name': ['Universal Transverse Mercator']}
  24. :param dic: The dictionary containing information about projection
  25. :return: The dictionary with the new values if needed or a copy of old one
  26. """
  27. # the lookup variable is a list of list, each list contains all the
  28. # possible name for a projection system
  29. lookup = [['Universal Transverse Mercator',
  30. 'Universe Transverse Mercator']]
  31. dic = dict(dic)
  32. for l in lookup:
  33. for n in range(len(dic['name'])):
  34. if dic['name'][n] in l:
  35. dic['name'][n] = l[0]
  36. return dic
  37. def unify_units(dic):
  38. """Unifies names of units.
  39. Some units have different spelling although they are the same units.
  40. This functions replaces different spelling options by unified one.
  41. Example of British English spelling replaced by US English spelling::
  42. >>> unify_units({'units': ['metres'], 'unit': ['metre']})
  43. {'units': ['meters'], 'unit': ['meter']}
  44. :param dic: The dictionary containing information about units
  45. :return: The dictionary with the new values if needed or a copy of old one
  46. """
  47. # the lookup variable is a list of list, each list contains all the
  48. # possible name for a units
  49. lookup = [['meter', 'metre'], ['meters', 'metres'],
  50. ['Meter', 'Metre'], ['Meters', 'Metres'],
  51. ['kilometer', 'kilometre'], ['kilometers', 'kilometres'],
  52. ['Kilometer', 'Kilometre'], ['Kilometers', 'Kilometres'],
  53. ]
  54. dic = dict(dic)
  55. for l in lookup:
  56. import types
  57. if not isinstance(dic['unit'], types.StringTypes):
  58. for n in range(len(dic['unit'])):
  59. if dic['unit'][n] in l:
  60. dic['unit'][n] = l[0]
  61. else:
  62. if dic['unit'] in l:
  63. dic['unit'] = l[0]
  64. if not isinstance(dic['units'], types.StringTypes):
  65. for n in range(len(dic['units'])):
  66. if dic['units'][n] in l:
  67. dic['units'][n] = l[0]
  68. else:
  69. if dic['units'] in l:
  70. dic['units'] = l[0]
  71. return dic
  72. def value_from_string(value):
  73. """Create value of a most fitting type from a string.
  74. Type conversions are applied in order ``int``, ``float``, ``string``
  75. where string is no conversion.
  76. >>> value_from_string('1')
  77. 1
  78. >>> value_from_string('5.6')
  79. 5.6
  80. >>> value_from_string(' 5.6\t ')
  81. 5.6
  82. >>> value_from_string('hello')
  83. 'hello'
  84. """
  85. not_float = False
  86. not_int = False
  87. # Convert values into correct types
  88. # We first try integer then float because
  89. # int('1.0') is ValueError (although int(1.0) is not)
  90. # while float('1') is not
  91. try:
  92. value_converted = int(value)
  93. except ValueError:
  94. not_int = True
  95. if not_int:
  96. try:
  97. value_converted = float(value)
  98. except ValueError:
  99. not_float = True
  100. # strip strings from whitespace (expecting spaces and tabs)
  101. if not_int and not_float:
  102. value_converted = value.strip()
  103. return value_converted
  104. # TODO: what is the default separator?
  105. def text_to_keyvalue(text, sep=":", val_sep=",", functions=None,
  106. skip_invalid=False, skip_empty=False,
  107. from_string=value_from_string):
  108. """Convert test to key-value pairs (dictionary-like KeyValue object).
  109. Converts a key-value text file, where entries are separated
  110. by newlines and the key and value are separated by `sep`,
  111. into a key-value dictionary and discovers/uses the correct
  112. data types (float, int or string) for values.
  113. Besides key-value pairs it also parses values itself. Value is created
  114. with the best fitting type using `value_from_string()` function by default.
  115. When val_sep is present in value part, the resulting value is
  116. a list of values.
  117. :param text: string to convert
  118. :param sep: character that separates the keys and values
  119. :param val_sep: character that separates the values of a single key
  120. :param functions: list of functions to apply on the resulting dictionary
  121. :param skip_invalid: skip all lines which does not contain separator
  122. :param skip_empty: skip empty lines
  123. :param from_string: a function used to convert strings to values,
  124. use ``lambda x: x`` for no conversion
  125. :return: a dictionary representation of text
  126. :return type: grass.script.core.KeyValue
  127. And example of converting text with text, floats, integers and list
  128. to a dictionary::
  129. >>> sorted(text_to_keyvalue('''a: Hello
  130. ... b: 1.0
  131. ... c: 1,2,3,4,5
  132. ... d : hello,8,0.1''').items()) # sorted items from the dictionary
  133. [('a', 'Hello'), ('b', 1.0), ('c', [1, 2, 3, 4, 5]), ('d', ['hello', 8, 0.1])]
  134. .. warning::
  135. And empty string is a valid input because empty dictionary is a valid
  136. dictionary. You need to test this separately according
  137. to the circumstances.
  138. """
  139. # splitting according to universal newlines approach
  140. # TODO: add also general split with vsep
  141. text = text.splitlines()
  142. kvdict = gcore.KeyValue()
  143. functions = [] if functions is None else functions
  144. for line in text:
  145. if line.find(sep) >= 0:
  146. key, value = line.split(sep, 1)
  147. key = key.strip()
  148. value = value.strip()
  149. # this strip may not be necessary, we strip each item in list
  150. # and also if there is only one value
  151. else:
  152. # lines with no separator (empty or invalid)
  153. if not line:
  154. if not skip_empty:
  155. # TODO: here should go _ for translation
  156. # TODO: the error message is not really informative
  157. # in case of skipping lines we may get here with no key
  158. msg = ("Empty line in the parsed text.")
  159. if kvdict:
  160. # key is the one from previous line
  161. msg = ("Empty line in the parsed text."
  162. " Previous line's key is <%s>") % key
  163. raise ValueError(msg)
  164. else:
  165. # line contains something but not separator
  166. if not skip_invalid:
  167. # TODO: here should go _ for translation
  168. raise ValueError(("Line <{l}> does not contain"
  169. " separator <{s}>.").format(l=line, s=sep))
  170. # if we get here we are silently ignoring the line
  171. # because it is invalid (does not contain key-value separator) or
  172. # because it is empty
  173. continue
  174. if value.find(val_sep) >= 0:
  175. # lists
  176. values = value.split(val_sep)
  177. value_list = []
  178. for value in values:
  179. value_converted = from_string(value)
  180. value_list.append(value_converted)
  181. kvdict[key] = value_list
  182. else:
  183. # single values
  184. kvdict[key] = from_string(value)
  185. for function in functions:
  186. kvdict = function(kvdict)
  187. return kvdict
  188. # TODO: decide if there should be some default for precision
  189. # TODO: define standard precisions for DCELL, FCELL, CELL, mm, ft, cm, ...
  190. # TODO: decide if None is valid, and use some default or no compare
  191. # TODO: is None a valid value for precision?
  192. def values_equal(value_a, value_b, precision=0.000001):
  193. """
  194. >>> values_equal(1.022, 1.02, precision=0.01)
  195. True
  196. >>> values_equal([1.2, 5.3, 6.8], [1.1, 5.2, 6.9], precision=0.2)
  197. True
  198. >>> values_equal(7, 5, precision=2)
  199. True
  200. >>> values_equal(1, 5.9, precision=10)
  201. True
  202. >>> values_equal('Hello', 'hello')
  203. False
  204. """
  205. # each if body needs to handle only not equal state
  206. if isinstance(value_a, float) and isinstance(value_b, float):
  207. # both values are float
  208. # this could be also changed to is None and raise TypeError
  209. # in Python 2 None is smaller than anything
  210. # in Python 3 None < 3 raises TypeError
  211. precision = float(precision)
  212. if abs(value_a - value_b) > precision:
  213. return False
  214. elif (isinstance(value_a, float) and isinstance(value_b, int)) or \
  215. (isinstance(value_b, float) and isinstance(value_a, int)):
  216. # on is float the other is int
  217. # don't accept None
  218. precision = float(precision)
  219. # we will apply precision to int-float comparison
  220. # rather than converting both to integer
  221. # (as in the original function from grass.script.core)
  222. if abs(value_a - value_b) > precision:
  223. return False
  224. elif isinstance(value_a, int) and isinstance(value_b, int) and \
  225. precision and int(precision) > 0:
  226. # both int but precision applies for them
  227. if abs(value_a - value_b) > precision:
  228. return False
  229. elif isinstance(value_a, list) and isinstance(value_b, list):
  230. if len(value_a) != len(value_b):
  231. return False
  232. for i in range(len(value_a)):
  233. # apply this function for comparison of items in the list
  234. if not values_equal(value_a[i], value_b[i], precision):
  235. return False
  236. else:
  237. if value_a != value_b:
  238. return False
  239. return True
  240. def keyvalue_equals(dict_a, dict_b, precision,
  241. def_equal=values_equal, key_equal=None,
  242. a_is_subset=False):
  243. """Compare two dictionaries.
  244. .. note::
  245. Always use keyword arguments for all parameters with defaults.
  246. It is a good idea to use keyword arguments also for the first
  247. two parameters.
  248. An example of key-value texts comparison::
  249. >>> keyvalue_equals(text_to_keyvalue('''a: Hello
  250. ... b: 1.0
  251. ... c: 1,2,3,4,5
  252. ... d: hello,8,0.1'''),
  253. ... text_to_keyvalue('''a: Hello
  254. ... b: 1.1
  255. ... c: 1,22,3,4,5
  256. ... d: hello,8,0.1'''), precision=0.1)
  257. False
  258. :param dict_a: first dictionary
  259. :param dict_b: second dictionary
  260. :param precision: precision with which the floating point values
  261. are compared (passed to equality functions)
  262. :param callable def_equal: function used for comparison by default
  263. :param dict key_equal: dictionary of functions used for comparison
  264. of specific keys, `def_equal` is used for the rest,
  265. keys in dictionary are keys in `dict_a` and `dict_b` dictionaries,
  266. values are the fuctions used to comapare the given key
  267. :param a_is_subset: `True` if `dict_a` is a subset of `dict_b`,
  268. `False` otherwise
  269. :return: `True` if identical, `False` if different
  270. Use `diff_keyvalue()` to get information about differeces.
  271. You can use this function to find out if there is a difference and then
  272. use `diff_keyvalue()` to determine all the differences between
  273. dictionaries.
  274. """
  275. key_equal = {} if key_equal is None else key_equal
  276. if not a_is_subset and sorted(dict_a.keys()) != sorted(dict_b.keys()):
  277. return False
  278. b_keys = dict_b.keys() if a_is_subset else None
  279. # iterate over subset or just any if not a_is_subset
  280. # check for missing keys in superset
  281. # compare matching keys
  282. for key in dict_a.keys():
  283. if a_is_subset and key not in b_keys:
  284. return False
  285. equal_fun = key_equal.get(key, def_equal)
  286. if not equal_fun(dict_a[key], dict_b[key], precision):
  287. return False
  288. return True
  289. # TODO: should the return depend on the a_is_subset parameter?
  290. # this function must have the same interface and behavior as keyvalue_equals
  291. def diff_keyvalue(dict_a, dict_b, precision,
  292. def_equal=values_equal, key_equal=None,
  293. a_is_subset=False):
  294. """Determine the difference of two dictionaries.
  295. The function returns missing keys and different values for common keys::
  296. >>> a = {'c': 2, 'b': 3, 'a': 4}
  297. >>> b = {'c': 1, 'b': 3, 'd': 5}
  298. >>> diff_keyvalue(a, b, precision=0)
  299. (['d'], ['a'], [('c', 2, 1)])
  300. You can provide only a subset of values in dict_a, in this case
  301. first item in tuple is an emptu list::
  302. >>> diff_keyvalue(a, b, a_is_subset=True, precision=0)
  303. ([], ['a'], [('c', 2, 1)])
  304. This function behaves the same as `keyvalue_equals()`.
  305. :returns: A tuple of lists, fist is list of missing keys in dict_a,
  306. second missing keys in dict_b and third is a list of mismatched
  307. values as tuples (key, value_from_a, value_from_b)
  308. :rtype: (list, list, list)
  309. Comparing to the Python ``difflib`` package this function does not create
  310. any difference output. It just returns the dictionaries.
  311. Comparing to the Python ``unittest`` ``assertDictEqual()``,
  312. this function does not issues error or exception, it just determines
  313. what it the difference.
  314. """
  315. key_equal = {} if key_equal is None else key_equal
  316. a_keys = dict_a.keys()
  317. b_keys = dict_b.keys()
  318. missing_in_a = []
  319. missing_in_b = []
  320. mismatched = []
  321. if not a_is_subset:
  322. for key in b_keys:
  323. if key not in a_keys:
  324. missing_in_a.append(key)
  325. # iterate over a, so we know that it is in a
  326. for key in a_keys:
  327. # check if it is in b
  328. if key not in b_keys:
  329. missing_in_b.append(key)
  330. else:
  331. equal_fun = key_equal.get(key, def_equal)
  332. if not equal_fun(dict_a[key], dict_b[key], precision):
  333. mismatched.append((key, dict_a[key], dict_b[key]))
  334. return sorted(missing_in_a), sorted(missing_in_b), sorted(mismatched)
  335. def proj_info_equals(text_a, text_b):
  336. """Test if two PROJ_INFO texts are equal."""
  337. def compare_sums(list_a, list_b, precision):
  338. """Compare difference of sums of two list using precision"""
  339. # derived from the code in grass.script.core
  340. if abs(sum(list_a) - sum(list_b)) > precision:
  341. return False
  342. sep = ':'
  343. val_sep = ','
  344. key_equal = {'+towgs84': compare_sums}
  345. dict_a = text_to_keyvalue(text_a, sep=sep, val_sep=val_sep,
  346. functions=[unify_projection])
  347. dict_b = text_to_keyvalue(text_b, sep=sep, val_sep=val_sep,
  348. functions=[unify_projection])
  349. return keyvalue_equals(dict_a, dict_b,
  350. precision=0.000001,
  351. def_equal=values_equal,
  352. key_equal=key_equal)
  353. def proj_units_equals(text_a, text_b):
  354. """Test if two PROJ_UNITS texts are equal."""
  355. def lowercase_equals(string_a, string_b, precision=None):
  356. # we don't need a waring for unused precision
  357. # pylint: disable=W0613
  358. """Test equality of two strings ignoring their case using ``lower()``.
  359. Precision is accepted as require by `keyvalue_equals()` but ignored.
  360. """
  361. return string_a.lower() == string_b.lower()
  362. sep = ':'
  363. val_sep = ','
  364. key_equal = {'unit': lowercase_equals, 'units': lowercase_equals}
  365. dict_a = text_to_keyvalue(text_a, sep=sep, val_sep=val_sep,
  366. functions=[unify_units])
  367. dict_b = text_to_keyvalue(text_b, sep, val_sep,
  368. functions=[unify_units])
  369. return keyvalue_equals(dict_a, dict_b,
  370. precision=0.000001,
  371. def_equal=values_equal,
  372. key_equal=key_equal)
  373. # TODO: support also float (with E, e, inf, nan, ...?) and int (###, ##.)
  374. # http://hg.python.org/cpython/file/943d3e289ab4/Lib/decimal.py#l6098
  375. # perhaps a separate function?
  376. # alternative names: looks like, correspond with/to
  377. # TODO: change checking over lines?
  378. # TODO: change parameter order?
  379. # TODO: the behavior with last \n is strange but now using DOTALL and $
  380. def check_text_ellipsis(reference, actual):
  381. r"""
  382. >>> check_text_ellipsis("Vector map <...> contains ... points.",
  383. ... "Vector map <bridges> contains 5268 points.")
  384. True
  385. >>> check_text_ellipsis("user: ...\\nname: elevation",
  386. ... "user: some_user\\nname: elevation")
  387. True
  388. >>> check_text_ellipsis("user: ...\\nname: elevation",
  389. ... "user: \\nname: elevation")
  390. False
  391. The ellipsis is always considered even if it is followed by another
  392. dots. Consequently, a dot at the end of the sentence with preceding
  393. ellipsis will work as well as a line filled with undefined number of dots.
  394. >>> check_text_ellipsis("The result is ....",
  395. ... "The result is 25.")
  396. True
  397. >>> check_text_ellipsis("max ..... ...",
  398. ... "max ....... 6")
  399. True
  400. However, there is no way how to express that the dot should be in the
  401. beginning and the ellipsis is at the end of the group of dots.
  402. >>> check_text_ellipsis("The result is ....",
  403. ... "The result is .25")
  404. False
  405. The matching goes over lines (TODO: should this be changed?):
  406. >>> check_text_ellipsis("a=11\nb=...", "a=11\nb=22\n")
  407. True
  408. This function is based on regular expression containing .+ but no other
  409. regular expression matching will be done.
  410. >>> check_text_ellipsis("Result: [569] (...)",
  411. ... "Result: 9 (too high)")
  412. False
  413. """
  414. ref_escaped = re.escape(reference)
  415. exp = re.compile(r'\\\.\\\.\\\.') # matching escaped ...
  416. ref_regexp = exp.sub('.+', ref_escaped) + "$"
  417. if re.match(ref_regexp, actual, re.DOTALL):
  418. return True
  419. else:
  420. return False
  421. def check_text_ellipsis_doctest(reference, actual):
  422. """
  423. >>> check_text_ellipsis_doctest("user: ...\\nname: elevation",
  424. ... "user: some_user\\nname: elevation")
  425. True
  426. >>> check_text_ellipsis_doctest("user: ...\\nname: elevation",
  427. ... "user: \\nname: elevation")
  428. True
  429. This function is using doctest's function to check the result, so we
  430. will discuss here how the underlying function behaves.
  431. >>> checker = doctest.OutputChecker()
  432. >>> checker.check_output("user: some_user\\nname: elevation",
  433. ... "user: some_user\\nname: elevation",
  434. ... optionflags=None)
  435. True
  436. >>> checker.check_output("user: user1\\nname: elevation",
  437. ... "user: some_user\\nname: elevation",
  438. ... optionflags=doctest.ELLIPSIS)
  439. False
  440. >>> checker.check_output("user: ...\\nname: elevation",
  441. ... "user: some_user\\nname: elevation",
  442. ... optionflags=doctest.ELLIPSIS)
  443. True
  444. The ellipsis matches also an empty string, so the following matches:
  445. >>> checker.check_output("user: ...\\nname: elevation",
  446. ... "user: \\nname: elevation",
  447. ... optionflags=doctest.ELLIPSIS)
  448. True
  449. It is robust concerning misspelled matching string but does not allow
  450. ellipsis followed by a dot, e.g. at the end of the sentence:
  451. >>> checker.check_output("user: ....\\nname: elevation",
  452. ... "user: some_user\\nname: elevation",
  453. ... optionflags=doctest.ELLIPSIS)
  454. False
  455. """
  456. # this can be also global
  457. checker = doctest.OutputChecker()
  458. return checker.check_output(reference, actual,
  459. optionflags=doctest.ELLIPSIS)
  460. import hashlib
  461. # optimal size depends on file system and maybe on hasher.block_size
  462. _BUFFER_SIZE = 2**16
  463. # TODO: accept also open file object
  464. def file_md5(filename):
  465. """Get MD5 (check) sum of a file."""
  466. hasher = hashlib.md5()
  467. with open(filename, 'rb') as f:
  468. buf = f.read(_BUFFER_SIZE)
  469. while len(buf) > 0:
  470. hasher.update(buf)
  471. buf = f.read(_BUFFER_SIZE)
  472. return hasher.hexdigest()
  473. def text_file_md5(filename, exclude_lines=None,
  474. prepend_lines=None, append_lines=None):
  475. """Get a MD5 (check) sum of a text file.
  476. Works in the same way as `file_md5()` function but allows to
  477. exclude lines from the file as well as prepend or append them.
  478. .. todo::
  479. Implement this function.
  480. """
  481. raise NotImplementedError("Implement, or use file_md5() function instead")
  482. def files_equal_md5(filename_a, filename_b):
  483. """Check equality of two files according to their MD5 sums"""
  484. return file_md5(filename_a) == file_md5(filename_b)
  485. def main(): # pragma: no cover
  486. """Run the doctest"""
  487. ret = doctest.testmod()
  488. return ret.failed
  489. if __name__ == '__main__': # pragma: no cover
  490. sys.exit(main())