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