checkers.py 23 KB

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