checkers.py 23 KB

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