checkers.py 22 KB

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