case.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  1. # -*- coding: utf-8 -*-
  2. """GRASS Python testing framework test case
  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
  8. """
  9. import os
  10. import subprocess
  11. import StringIO
  12. import hashlib
  13. import uuid
  14. import unittest
  15. from grass.pygrass.modules import Module
  16. from grass.exceptions import CalledModuleError
  17. from .gmodules import call_module, SimpleModule
  18. from .checkers import (check_text_ellipsis,
  19. text_to_keyvalue, keyvalue_equals, diff_keyvalue,
  20. file_md5, files_equal_md5)
  21. from .utils import safe_repr
  22. from .gutils import is_map_in_mapset
  23. class TestCase(unittest.TestCase):
  24. # we dissable R0904 for all TestCase classes because their purpose is to
  25. # provide a lot of assert methods
  26. # pylint: disable=R0904
  27. """
  28. Always use keyword arguments for all parameters other than first two. For
  29. the first two, it is recommended to use keyword arguments but not required.
  30. """
  31. longMessage = True # to get both standard and custom message
  32. maxDiff = None # we can afford long diffs
  33. _temp_region = None # to control the temporary region
  34. html_reports = False # output additional HTML files with failure details
  35. readable_names = False # prefer shorter but unreadable map and file names
  36. def __init__(self, methodName):
  37. super(TestCase, self).__init__(methodName)
  38. self.grass_modules = []
  39. self.supplementary_files = []
  40. # Python unittest doc is saying that strings use assertMultiLineEqual
  41. # but only unicode type is registered
  42. # TODO: report this as a bug? is this in Python 3.x?
  43. self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
  44. def _formatMessage(self, msg, standardMsg):
  45. """Honor the longMessage attribute when generating failure messages.
  46. If longMessage is False this means:
  47. * Use only an explicit message if it is provided
  48. * Otherwise use the standard message for the assert
  49. If longMessage is True:
  50. * Use the standard message
  51. * If an explicit message is provided, return string with both messages
  52. Based on Python unittest _formatMessage, formatting changed.
  53. """
  54. if not self.longMessage:
  55. return msg or standardMsg
  56. if msg is None:
  57. return standardMsg
  58. try:
  59. # don't switch to '{}' formatting in Python 2.X
  60. # it changes the way unicode input is handled
  61. return '%s \n%s' % (msg, standardMsg)
  62. except UnicodeDecodeError:
  63. return '%s \n%s' % (safe_repr(msg), safe_repr(standardMsg))
  64. @classmethod
  65. def use_temp_region(cls):
  66. """Use temporary region instead of the standard one for this process.
  67. If you use this method, you have to call it in `setUpClass()`
  68. and call `del_temp_region()` in `tearDownClass()`. By this you
  69. ensure that each test method will have its own region and will
  70. not influence other classes.
  71. ::
  72. @classmethod
  73. def setUpClass(self):
  74. self.use_temp_region()
  75. @classmethod
  76. def tearDownClass(self):
  77. self.del_temp_region()
  78. You can also call the methods in `setUp()` and `tearDown()` if
  79. you are using them.
  80. Copies the current region to a temporary region with
  81. ``g.region save=``, then sets ``WIND_OVERRIDE`` to refer
  82. to that region.
  83. """
  84. # we use just the class name since we rely on the invokation system
  85. # where each test file is separate process and nothing runs
  86. # in parallel inside
  87. name = "tmp.%s" % (cls.__name__)
  88. call_module("g.region", save=name, overwrite=True)
  89. os.environ['WIND_OVERRIDE'] = name
  90. cls._temp_region = name
  91. @classmethod
  92. def del_temp_region(cls):
  93. """Remove the temporary region.
  94. Unsets ``WIND_OVERRIDE`` and removes any region named by it.
  95. """
  96. assert cls._temp_region
  97. name = os.environ.pop('WIND_OVERRIDE')
  98. if name != cls._temp_region:
  99. # be strict about usage of region
  100. raise RuntimeError("Inconsistent use of"
  101. " TestCase.use_temp_region, WIND_OVERRIDE"
  102. " or temporary region in general\n"
  103. "Region to which should be now deleted ({n})"
  104. " by TestCase class"
  105. "does not corresond to currently set"
  106. " WIND_OVERRIDE ({c})",
  107. n=cls._temp_region, c=name)
  108. call_module("g.remove", quiet=True, flags='f', type='region', name=name)
  109. # TODO: we don't know if user calls this
  110. # so perhaps some decorator which would use with statemet
  111. # but we have zero chance of infuencing another test class
  112. # since we use class-specific name for temporary region
  113. def assertMultiLineEqual(self, first, second, msg=None):
  114. r"""Test that the multiline string first is equal to the string second.
  115. When not equal a diff of the two strings highlighting the differences
  116. will be included in the error message. This method is used by default
  117. when comparing strings with assertEqual().
  118. This method replaces platform dependent newline characters
  119. by ``\n`` (LF) in both parameters. This is
  120. different from the same method implemented in Python ``unittest``
  121. package which preserves the original newline characters.
  122. This function removes the burden of getting the newline characters
  123. right on each platfrom. You can just use ``\n`` everywhere and this
  124. function will ensure that it does not matter if for example,
  125. a module generates (as expected) ``\r\n`` (CRLF) newline characters
  126. on MS Windows.
  127. .. warning::
  128. If you need to test the actual newline characters, use the standard
  129. string comparison and functions such as ``find()``.
  130. """
  131. if os.linesep != '\n':
  132. if os.linesep in first:
  133. first = first.replace(os.linesep, '\n')
  134. if os.linesep in second:
  135. second = second.replace(os.linesep, '\n')
  136. return super(TestCase, self).assertMultiLineEqual(
  137. first=first, second=second, msg=msg)
  138. def assertLooksLike(self, actual, reference, msg=None):
  139. r"""Test that ``actual`` text is the same as ``referece`` with ellipses.
  140. If ``actual`` contains platform dependent newline characters,
  141. these will replaced by ``\n`` which is expected to be in the test data.
  142. See :func:`check_text_ellipsis` for details of behavior.
  143. """
  144. self.assertTrue(isinstance(actual, basestring), (
  145. 'actual argument is not a string'))
  146. self.assertTrue(isinstance(reference, basestring), (
  147. 'reference argument is not a string'))
  148. if os.linesep != '\n' and os.linesep in actual:
  149. actual = actual.replace(os.linesep, '\n')
  150. if not check_text_ellipsis(actual=actual, reference=reference):
  151. # TODO: add support for multiline (first line general, others with details)
  152. standardMsg = '"%s" does not correspond with "%s"' % (actual,
  153. reference)
  154. self.fail(self._formatMessage(msg, standardMsg))
  155. # TODO: decide if precision is mandatory
  156. # (note that we don't need precision for strings and usually for integers)
  157. # TODO: auto-determine precision based on the map type
  158. # TODO: we can have also more general function without the subset reference
  159. # TODO: change name to Module
  160. def assertModuleKeyValue(self, module, reference, sep,
  161. precision, msg=None, **parameters):
  162. """Test that output of a module is the same as provided subset.
  163. ::
  164. self.assertModuleKeyValue('r.info', map='elevation', flags='gr',
  165. reference=dict(min=55.58, max=156.33),
  166. precision=0.01, sep='=')
  167. ::
  168. module = SimpleModule('r.info', map='elevation', flags='gr')
  169. self.assertModuleKeyValue(module,
  170. reference=dict(min=55.58, max=156.33),
  171. precision=0.01, sep='=')
  172. The output of the module should be key-value pairs (shell script style)
  173. which is typically obtained using ``-g`` flag.
  174. """
  175. if isinstance(reference, basestring):
  176. reference = text_to_keyvalue(reference, sep=sep, skip_empty=True)
  177. module = _module_from_parameters(module, **parameters)
  178. self.runModule(module, expecting_stdout=True)
  179. raster_univar = text_to_keyvalue(module.outputs.stdout,
  180. sep=sep, skip_empty=True)
  181. if not keyvalue_equals(dict_a=reference, dict_b=raster_univar,
  182. a_is_subset=True, precision=precision):
  183. unused, missing, mismatch = diff_keyvalue(dict_a=reference,
  184. dict_b=raster_univar,
  185. a_is_subset=True,
  186. precision=precision)
  187. # TODO: add region vs map extent and res check in case of error
  188. if missing:
  189. raise ValueError("%s output does not contain"
  190. " the following keys"
  191. " provided in reference"
  192. ": %s\n" % (module, ", ".join(missing)))
  193. if mismatch:
  194. stdMsg = "%s difference:\n" % module
  195. stdMsg += "mismatch values"
  196. stdMsg += " (key, reference, actual): %s\n" % mismatch
  197. stdMsg += 'command: %s %s' % (module, parameters)
  198. else:
  199. # we can probably remove this once we have more tests
  200. # of keyvalue_equals and diff_keyvalue against each other
  201. raise RuntimeError("keyvalue_equals() showed difference but"
  202. " diff_keyvalue() did not. This can be"
  203. " a bug in one of them or in the caller"
  204. " (assertModuleKeyValue())")
  205. self.fail(self._formatMessage(msg, stdMsg))
  206. def assertRasterFitsUnivar(self, raster, reference,
  207. precision=None, msg=None):
  208. r"""Test that raster map has the values obtained by r.univar module.
  209. The function does not require all values from r.univar.
  210. Only the provided values are tested.
  211. Typical example is checking minimum, maximum and number of NULL cells
  212. in the map::
  213. values = 'null_cells=0\nmin=55.5787925720215\nmax=156.329864501953'
  214. self.assertRasterFitsUnivar(raster='elevation', reference=values)
  215. Use keyword arguments syntax for all function parameters.
  216. Does not -e (extended statistics) flag, use `assertModuleKeyValue()`
  217. for the full interface of arbitrary module.
  218. """
  219. self.assertModuleKeyValue(module='r.univar',
  220. map=raster,
  221. separator='=',
  222. flags='g',
  223. reference=reference, msg=msg, sep='=',
  224. precision=precision)
  225. def assertRasterFitsInfo(self, raster, reference,
  226. precision=None, msg=None):
  227. r"""Test that raster map has the values obtained by r.univar module.
  228. The function does not require all values from r.univar.
  229. Only the provided values are tested.
  230. Typical example is checking minimum, maximum and type of the map::
  231. minmax = 'min=0\nmax=1451\ndatatype=FCELL'
  232. self.assertRasterFitsInfo(raster='elevation', reference=minmax)
  233. Use keyword arguments syntax for all function parameters.
  234. This function supports values obtained -r (range) and
  235. -e (extended metadata) flags.
  236. """
  237. self.assertModuleKeyValue(module='r.info',
  238. map=raster, flags='gre',
  239. reference=reference, msg=msg, sep='=',
  240. precision=precision)
  241. def assertRaster3dFitsUnivar(self, raster, reference,
  242. precision=None, msg=None):
  243. r"""Test that 3D raster map has the values obtained by r3.univar module.
  244. The function does not require all values from r3.univar.
  245. Only the provided values are tested.
  246. Use keyword arguments syntax for all function parameters.
  247. Function does not use -e (extended statistics) flag,
  248. use `assertModuleKeyValue()` for the full interface of arbitrary
  249. module.
  250. """
  251. self.assertModuleKeyValue(module='r3.univar',
  252. map=raster,
  253. separator='=',
  254. flags='g',
  255. reference=reference, msg=msg, sep='=',
  256. precision=precision)
  257. def assertRaster3dFitsInfo(self, raster, reference,
  258. precision=None, msg=None):
  259. r"""Test that raster map has the values obtained by r3.info module.
  260. The function does not require all values from r3.info.
  261. Only the provided values are tested.
  262. Use keyword arguments syntax for all function parameters.
  263. This function supports values obtained by -g (info) and -r (range).
  264. """
  265. self.assertModuleKeyValue(module='r3.info',
  266. map=raster, flags='gr',
  267. reference=reference, msg=msg, sep='=',
  268. precision=precision)
  269. def assertVectorFitsTopoInfo(self, vector, reference, msg=None):
  270. r"""Test that raster map has the values obtained by ``v.info`` module.
  271. This function uses ``-t`` flag of ``v.info`` module to get topology
  272. info, so the reference dictionary should contain appropriate set or
  273. subset of values (only the provided values are tested).
  274. A example of checking number of points::
  275. topology = dict(points=10938, primitives=10938)
  276. self.assertVectorFitsTopoInfo(vector='bridges', reference=topology)
  277. Note that here we are checking also the number of primitives to prove
  278. that there are no other features besides points.
  279. No precision is applied (no difference is required). So, this function
  280. is not suitable for testing items which are floating point number
  281. (no such items are currently in topological information).
  282. Use keyword arguments syntax for all function parameters.
  283. """
  284. self.assertModuleKeyValue(module='v.info',
  285. map=vector, flags='t',
  286. reference=reference, msg=msg, sep='=',
  287. precision=0)
  288. def assertVectorFitsRegionInfo(self, vector, reference,
  289. precision, msg=None):
  290. r"""Test that raster map has the values obtained by ``v.info`` module.
  291. This function uses ``-g`` flag of ``v.info`` module to get topology
  292. info, so the reference dictionary should contain appropriate set or
  293. subset of values (only the provided values are tested).
  294. Use keyword arguments syntax for all function parameters.
  295. """
  296. self.assertModuleKeyValue(module='v.info',
  297. map=vector, flags='g',
  298. reference=reference, msg=msg, sep='=',
  299. precision=precision)
  300. def assertVectorFitsExtendedInfo(self, vector, reference, msg=None):
  301. r"""Test that raster map has the values obtained by ``v.info`` module.
  302. This function uses ``-e`` flag of ``v.info`` module to get topology
  303. info, so the reference dictionary should contain appropriate set or
  304. subset of values (only the provided values are tested).
  305. The most useful items for testing (considering circumstances of test
  306. invocation) are name, title, level and num_dblinks. (When testing
  307. storing of ``v.info -e`` metadata, the selection might be different.)
  308. No precision is applied (no difference is required). So, this function
  309. is not suitable for testing items which are floating point number.
  310. Use keyword arguments syntax for all function parameters.
  311. """
  312. self.assertModuleKeyValue(module='v.info',
  313. map=vector, flags='e',
  314. reference=reference, msg=msg, sep='=',
  315. precision=0)
  316. def assertVectorInfoEqualsVectorInfo(self, actual, reference, precision,
  317. msg=None):
  318. """Test that two vectors are equal according to ``v.info -tg``.
  319. This function does not test geometry itself just the region of the
  320. vector map and number of features.
  321. """
  322. module = SimpleModule('v.info', flags='t', map=reference)
  323. self.runModule(module)
  324. ref_topo = text_to_keyvalue(module.outputs.stdout, sep='=')
  325. module = SimpleModule('v.info', flags='g', map=reference)
  326. self.runModule(module)
  327. ref_info = text_to_keyvalue(module.outputs.stdout, sep='=')
  328. self.assertVectorFitsTopoInfo(vector=actual, reference=ref_topo,
  329. msg=msg)
  330. self.assertVectorFitsRegionInfo(vector=actual, reference=ref_info,
  331. precision=precision, msg=msg)
  332. def assertVectorFitsUnivar(self, map, column, reference, msg=None,
  333. layer=None, type=None, where=None,
  334. precision=None):
  335. r"""Test that vector map has the values obtained by v.univar module.
  336. The function does not require all values from v.univar.
  337. Only the provided values are tested.
  338. Typical example is checking minimum and maximum of a column::
  339. minmax = 'min=0\nmax=1451'
  340. self.assertVectorFitsUnivar(map='bridges', column='WIDTH',
  341. reference=minmax)
  342. Use keyword arguments syntax for all function parameters.
  343. Does not support -d (geometry distances) flag, -e (extended statistics)
  344. flag and few other, use `assertModuleKeyValue` for the full interface
  345. of arbitrary module.
  346. """
  347. parameters = dict(map=map, column=column, flags='g')
  348. if layer:
  349. parameters.update(layer=layer)
  350. if type:
  351. parameters.update(type=type)
  352. if where:
  353. parameters.update(where=where)
  354. self.assertModuleKeyValue(module='v.univar',
  355. reference=reference, msg=msg, sep='=',
  356. precision=precision,
  357. **parameters)
  358. # TODO: use precision?
  359. # TODO: write a test for this method with r.in.ascii
  360. def assertRasterMinMax(self, map, refmin, refmax, msg=None):
  361. """Test that raster map minimum and maximum are within limits.
  362. Map minimum and maximum is tested against expression::
  363. refmin <= actualmin and refmax >= actualmax
  364. Use keyword arguments syntax for all function parameters.
  365. To check that more statistics have certain values use
  366. `assertRasterFitsUnivar()` or `assertRasterFitsInfo()`
  367. """
  368. stdout = call_module('r.info', map=map, flags='r')
  369. actual = text_to_keyvalue(stdout, sep='=')
  370. if refmin > actual['min']:
  371. stdmsg = ('The actual minimum ({a}) is smaller than the reference'
  372. ' one ({r}) for raster map {m}'
  373. ' (with maximum {o})'.format(
  374. a=actual['min'], r=refmin, m=map, o=actual['max']))
  375. self.fail(self._formatMessage(msg, stdmsg))
  376. if refmax < actual['max']:
  377. stdmsg = ('The actual maximum ({a}) is greater than the reference'
  378. ' one ({r}) for raster map {m}'
  379. ' (with minimum {o})'.format(
  380. a=actual['max'], r=refmax, m=map, o=actual['min']))
  381. self.fail(self._formatMessage(msg, stdmsg))
  382. # TODO: use precision?
  383. # TODO: write a test for this method with r.in.ascii
  384. # TODO: almost the same as 2D version
  385. def assertRaster3dMinMax(self, map, refmin, refmax, msg=None):
  386. """Test that 3D raster map minimum and maximum are within limits.
  387. Map minimum and maximum is tested against expression::
  388. refmin <= actualmin and refmax >= actualmax
  389. Use keyword arguments syntax for all function parameters.
  390. To check that more statistics have certain values use
  391. `assertRaster3DFitsUnivar()` or `assertRaster3DFitsInfo()`
  392. """
  393. stdout = call_module('r3.info', map=map, flags='r')
  394. actual = text_to_keyvalue(stdout, sep='=')
  395. if refmin > actual['min']:
  396. stdmsg = ('The actual minimum ({a}) is smaller than the reference'
  397. ' one ({r}) for 3D raster map {m}'
  398. ' (with maximum {o})'.format(
  399. a=actual['min'], r=refmin, m=map, o=actual['max']))
  400. self.fail(self._formatMessage(msg, stdmsg))
  401. if refmax < actual['max']:
  402. stdmsg = ('The actual maximum ({a}) is greater than the reference'
  403. ' one ({r}) for 3D raster map {m}'
  404. ' (with minimum {o})'.format(
  405. a=actual['max'], r=refmax, m=map, o=actual['min']))
  406. self.fail(self._formatMessage(msg, stdmsg))
  407. def _get_detailed_message_about_no_map(self, name, type):
  408. msg = ("There is no map <{n}> of type <{t}>"
  409. " in the current mapset".format(n=name, t=type))
  410. related = call_module('g.list', type='raster,raster3d,vector',
  411. flags='imt', pattern='*' + name + '*')
  412. if related:
  413. msg += "\nSee available maps:\n"
  414. msg += related
  415. else:
  416. msg += "\nAnd there are no maps containing the name anywhere\n"
  417. return msg
  418. def assertRasterExists(self, name, msg=None):
  419. """Checks if the raster map exists in current mapset"""
  420. if not is_map_in_mapset(name, type='raster'):
  421. stdmsg = self._get_detailed_message_about_no_map(name, 'raster')
  422. self.fail(self._formatMessage(msg, stdmsg))
  423. def assertRaster3dExists(self, name, msg=None):
  424. """Checks if the 3D raster map exists in current mapset"""
  425. if not is_map_in_mapset(name, type='raster3d'):
  426. stdmsg = self._get_detailed_message_about_no_map(name, 'raster3d')
  427. self.fail(self._formatMessage(msg, stdmsg))
  428. def assertVectorExists(self, name, msg=None):
  429. """Checks if the vector map exists in current mapset"""
  430. if not is_map_in_mapset(name, type='vector'):
  431. stdmsg = self._get_detailed_message_about_no_map(name, 'vector')
  432. self.fail(self._formatMessage(msg, stdmsg))
  433. def assertFileExists(self, filename, msg=None,
  434. skip_size_check=False, skip_access_check=False):
  435. """Test the existence of a file.
  436. .. note:
  437. By default this also checks if the file size is greater than 0
  438. since we rarely want a file to be empty. It also checks
  439. if the file is accessible for reading since we expect that user
  440. wants to look at created files.
  441. """
  442. if not os.path.isfile(filename):
  443. stdmsg = 'File %s does not exist' % filename
  444. self.fail(self._formatMessage(msg, stdmsg))
  445. if not skip_size_check and not os.path.getsize(filename):
  446. stdmsg = 'File %s is empty' % filename
  447. self.fail(self._formatMessage(msg, stdmsg))
  448. if not skip_access_check and not os.access(filename, os.R_OK):
  449. stdmsg = 'File %s is not accessible for reading' % filename
  450. self.fail(self._formatMessage(msg, stdmsg))
  451. def assertFileMd5(self, filename, md5, msg=None):
  452. """Test that file MD5 sum is equal to the provided sum.
  453. The typical workflow is that you create a file in a way you
  454. trust (that you obtain the right file). Then you compute MD5
  455. sum of the file. And provide the sum in a test as a string::
  456. self.assertFileMd5('result.txt', md5='807bba4ffa...')
  457. Use `file_md5()` function from this package::
  458. file_md5('original_result.txt')
  459. Or in command line, use ``md5sum`` command if available:
  460. .. code-block:: sh
  461. md5sum some_file.txt
  462. Finaly, you can use Python ``hashlib`` to obtain MD5::
  463. import hashlib
  464. hasher = hashlib.md5()
  465. # expecting the file to fit into memory
  466. hasher.update(open('original_result.txt', 'rb').read())
  467. hasher.hexdigest()
  468. """
  469. self.assertFileExists(filename, msg=msg)
  470. actual = file_md5(filename)
  471. if not actual == md5:
  472. standardMsg = ('File <{name}> does not have the right MD5 sum.\n'
  473. 'Expected is <{expected}>,'
  474. ' actual is <{actual}>'.format(
  475. name=filename, expected=md5, actual=actual))
  476. self.fail(self._formatMessage(msg, standardMsg))
  477. def assertFilesEqualMd5(self, filename, reference, msg=None):
  478. """Test that files are the same using MD5 sum.
  479. This functions requires you to provide a file to test and
  480. a reference file. For both, MD5 sum will be computed and compared with
  481. each other.
  482. """
  483. self.assertFileExists(filename, msg=msg)
  484. # nothing for ref, missing ref_filename is an error not a test failure
  485. if not files_equal_md5(filename, reference):
  486. stdmsg = 'Files %s and %s don\'t have the same MD5 sums' % (filename,
  487. reference)
  488. self.fail(self._formatMessage(msg, stdmsg))
  489. def _get_unique_name(self, name):
  490. """Create standardized map or file name which is unique
  491. If ``readable_names`` attribute is `True`, it uses the *name* string
  492. to create the unique name. Otherwise, it creates a unique name.
  493. Even if you expect ``readable_names`` to be `True`, provide *name*
  494. which is unique
  495. The *name* parameter should be valid raster name, vector name and file
  496. name and should be always provided.
  497. """
  498. # TODO: possible improvement is to require some descriptive name
  499. # and ensure uniqueness by add UUID
  500. if self.readable_names:
  501. return 'tmp_' + self.id().replace('.', '_') + '_' + name
  502. else:
  503. # UUID might be overkill (and expensive) but it's safe and simple
  504. # alternative is to create hash from the readable name
  505. return 'tmp_' + str(uuid.uuid4()).replace('-', '')
  506. def _compute_difference_raster(self, first, second, name_part):
  507. """Compute difference of two rasters (first - second)
  508. The name of the new raster is a long name designed to be as unique as
  509. possible and contains names of two input rasters.
  510. :param first: raster to subtract from
  511. :param second: raster used as decrement
  512. :param name_part: a unique string to be used in the difference name
  513. :returns: name of a new raster
  514. """
  515. diff = self._get_unique_name('compute_difference_raster_' + name_part
  516. + '_' + first + '_minus_' + second)
  517. call_module('r.mapcalc',
  518. stdin='"{d}" = "{f}" - "{s}"'.format(d=diff,
  519. f=first,
  520. s=second))
  521. return diff
  522. # TODO: name of map generation is repeted three times
  523. # TODO: this method is almost the same as the one for 2D
  524. def _compute_difference_raster3d(self, first, second, name_part):
  525. """Compute difference of two rasters (first - second)
  526. The name of the new raster is a long name designed to be as unique as
  527. possible and contains names of two input rasters.
  528. :param first: raster to subtract from
  529. :param second: raster used as decrement
  530. :param name_part: a unique string to be used in the difference name
  531. :returns: name of a new raster
  532. """
  533. diff = self._get_unique_name('compute_difference_raster_' + name_part
  534. + '_' + first + '_minus_' + second)
  535. call_module('r3.mapcalc',
  536. stdin='"{d}" = "{f}" - "{s}"'.format(d=diff,
  537. f=first,
  538. s=second))
  539. return diff
  540. def _compute_vector_xor(self, ainput, alayer, binput, blayer, name_part):
  541. """Compute symmetric difference (xor) of two vectors
  542. :returns: name of a new vector
  543. """
  544. diff = self._get_unique_name('compute_difference_vector_' + name_part
  545. + '_' + ainput + '_' + alayer + '_minus_'
  546. + binput + '_' + blayer)
  547. call_module('v.overlay', operator='xor', ainput=ainput, binput=binput,
  548. alayer=alayer, blayer=blayer,
  549. output=diff, atype='area', btype='area', olayer='')
  550. # trying to avoid long reports full of categories by olayer=''
  551. # olayer Output layer for new category, ainput and binput
  552. # If 0 or not given, the category is not written
  553. return diff
  554. # TODO: -z and 3D support
  555. def _import_ascii_vector(self, filename, name_part):
  556. """Import a vector stored in GRASS vector ASCII format.
  557. :returns: name of a new vector
  558. """
  559. # hash is the easiest way how to get a valied vector name
  560. # TODO: introduce some function which will make file valid
  561. hasher = hashlib.md5()
  562. hasher.update(filename)
  563. namehash = hasher.hexdigest()
  564. vector = self._get_unique_name('import_ascii_vector_' + name_part
  565. + '_' + namehash)
  566. call_module('v.in.ascii', input=filename,
  567. output=vector, format='standard')
  568. return vector
  569. # TODO: -z and 3D support
  570. def _export_ascii_vector(self, vector, name_part, digits):
  571. """Import a vector stored in GRASS vector ASCII format.
  572. :returns: name of a new vector
  573. """
  574. # TODO: perhaps we can afford just simple file name
  575. filename = self._get_unique_name('export_ascii_vector_'
  576. + name_part + '_' + vector)
  577. call_module('v.out.ascii', input=vector,
  578. output=filename, format='standard', layer='-1',
  579. precision=digits)
  580. return filename
  581. def assertRastersNoDifference(self, actual, reference,
  582. precision, statistics=None, msg=None):
  583. """Test that `actual` raster is not different from `reference` raster
  584. Method behaves in the same way as `assertRasterFitsUnivar()`
  585. but works on difference ``reference - actual``.
  586. If statistics is not given ``dict(min=-precision, max=precision)``
  587. is used.
  588. """
  589. if statistics is None or sorted(statistics.keys()) == ['max', 'min']:
  590. if statistics is None:
  591. statistics = dict(min=-precision, max=precision)
  592. diff = self._compute_difference_raster(reference, actual,
  593. 'assertRastersNoDifference')
  594. try:
  595. self.assertModuleKeyValue('r.info', map=diff, flags='r',
  596. sep='=', precision=precision,
  597. reference=statistics, msg=msg)
  598. finally:
  599. call_module('g.remove', flags='f', type='raster', name=diff)
  600. else:
  601. # general case
  602. # TODO: we are using r.info min max and r.univar min max interchangably
  603. # but they might be different if region is different from map
  604. # not considered as an huge issue since we expect the tested maps
  605. # to match with region, however a documentation should containe a notice
  606. self.assertRastersDifference(actual=actual, reference=reference,
  607. statistics=statistics,
  608. precision=precision, msg=msg)
  609. def assertRastersDifference(self, actual, reference,
  610. statistics, precision, msg=None):
  611. """Test statistical values of difference of reference and actual rasters
  612. For cases when you are interested in no or minimal difference,
  613. use `assertRastersNoDifference()` instead.
  614. This method should not be used to test r.mapcalc or r.univar.
  615. """
  616. diff = self._compute_difference_raster(reference, actual,
  617. 'assertRastersDifference')
  618. try:
  619. self.assertRasterFitsUnivar(raster=diff, reference=statistics,
  620. precision=precision, msg=msg)
  621. finally:
  622. call_module('g.remove', flags='f', type='raster', name=diff)
  623. def assertRasters3dNoDifference(self, actual, reference,
  624. precision, statistics=None, msg=None):
  625. """Test that `actual` raster is not different from `reference` raster
  626. Method behaves in the same way as `assertRasterFitsUnivar()`
  627. but works on difference ``reference - actual``.
  628. If statistics is not given ``dict(min=-precision, max=precision)``
  629. is used.
  630. """
  631. if statistics is None or sorted(statistics.keys()) == ['max', 'min']:
  632. if statistics is None:
  633. statistics = dict(min=-precision, max=precision)
  634. diff = self._compute_difference_raster3d(reference, actual,
  635. 'assertRasters3dNoDifference')
  636. try:
  637. self.assertModuleKeyValue('r3.info', map=diff, flags='r',
  638. sep='=', precision=precision,
  639. reference=statistics, msg=msg)
  640. finally:
  641. call_module('g.remove', flags='f', type='raster_3d', name=diff)
  642. else:
  643. # general case
  644. # TODO: we are using r.info min max and r.univar min max interchangably
  645. # but they might be different if region is different from map
  646. # not considered as an huge issue since we expect the tested maps
  647. # to match with region, however a documentation should contain a notice
  648. self.assertRasters3dDifference(actual=actual, reference=reference,
  649. statistics=statistics,
  650. precision=precision, msg=msg)
  651. def assertRasters3dDifference(self, actual, reference,
  652. statistics, precision, msg=None):
  653. """Test statistical values of difference of reference and actual rasters
  654. For cases when you are interested in no or minimal difference,
  655. use `assertRastersNoDifference()` instead.
  656. This method should not be used to test r3.mapcalc or r3.univar.
  657. """
  658. diff = self._compute_difference_raster3d(reference, actual,
  659. 'assertRasters3dDifference')
  660. try:
  661. self.assertRaster3dFitsUnivar(raster=diff, reference=statistics,
  662. precision=precision, msg=msg)
  663. finally:
  664. call_module('g.remove', flags='f', type='raster_3d', name=diff)
  665. # TODO: this works only in 2D
  666. # TODO: write tests
  667. def assertVectorIsVectorBuffered(self, actual, reference, precision, msg=None):
  668. """
  669. This method should not be used to test v.buffer, v.overlay or v.select.
  670. """
  671. # TODO: if msg is None: add info specific to this function
  672. layer = '-1'
  673. self.assertVectorInfoEqualsVectorInfo(actual=actual,
  674. reference=reference,
  675. precision=precision, msg=msg)
  676. remove = []
  677. buffered = reference + '_buffered' # TODO: more unique name
  678. intersection = reference + '_intersection' # TODO: more unique name
  679. self.runModule('v.buffer', input=reference, layer=layer,
  680. output=buffered, distance=precision)
  681. remove.append(buffered)
  682. try:
  683. self.runModule('v.overlay', operator='and', ainput=actual,
  684. binput=reference,
  685. alayer=layer, blayer=layer,
  686. output=intersection, atype='area', btype='area',
  687. olayer='')
  688. remove.append(intersection)
  689. # TODO: this would use some refactoring
  690. # perhaps different functions or more low level functions would
  691. # be more appropriate
  692. module = SimpleModule('v.info', flags='t', map=reference)
  693. self.runModule(module)
  694. ref_topo = text_to_keyvalue(module.outputs.stdout, sep='=')
  695. self.assertVectorFitsTopoInfo(vector=intersection,
  696. reference=ref_topo,
  697. msg=msg)
  698. module = SimpleModule('v.info', flags='g', map=reference)
  699. self.runModule(module)
  700. ref_info = text_to_keyvalue(module.outputs.stdout, sep='=')
  701. self.assertVectorFitsRegionInfo(vector=intersection,
  702. reference=ref_info,
  703. msg=msg, precision=precision)
  704. finally:
  705. call_module('g.remove', flags='f', type='vector', name=remove)
  706. # TODO: write tests
  707. def assertVectorsNoAreaDifference(self, actual, reference, precision,
  708. layer=1, msg=None):
  709. """Test statistical values of difference of reference and actual rasters
  710. Works only for areas.
  711. Use keyword arguments syntax for all function parameters.
  712. This method should not be used to test v.overlay or v.select.
  713. """
  714. diff = self._compute_xor_vectors(ainput=reference, binput=actual,
  715. alayer=layer, blayer=layer,
  716. name_part='assertVectorsNoDifference')
  717. try:
  718. module = SimpleModule('v.to.db', map=diff,
  719. flags='pc', separator='=')
  720. self.runModule(module)
  721. # the output of v.to.db -pc sep== should look like:
  722. # ...
  723. # 43=98606087.5818323
  724. # 44=727592.902311112
  725. # total area=2219442027.22035
  726. total_area = module.outputs.stdout.splitlines()[-1].split('=')[-1]
  727. if total_area > precision:
  728. stdmsg = ("Area of difference of vectors <{va}> and <{vr}>"
  729. " should be 0"
  730. " in the given precision ({p}) not {a}").format(
  731. va=actual, vr=reference, p=precision, a=total_area)
  732. self.fail(self._formatMessage(msg, stdmsg))
  733. finally:
  734. call_module('g.remove', flags='f', type='vector', name=diff)
  735. # TODO: here we have to have significant digits which is not consistent
  736. # TODO: documentation for all new asserts
  737. # TODO: same can be created for raster and 3D raster
  738. def assertVectorEqualsVector(self, actual, reference, digits, precision, msg=None):
  739. """Test that two vectors are equal.
  740. .. note:
  741. This test should not be used to test ``v.in.ascii`` and
  742. ``v.out.ascii`` modules.
  743. .. warning:
  744. ASCII files for vectors are loaded into memory, so this
  745. function works well only for "not too big" vector maps.
  746. """
  747. # both vectors to ascii
  748. # text diff of two ascii files
  749. # may also do other comparisons on vectors themselves (asserts)
  750. self.assertVectorInfoEqualsVectorInfo(actual=actual, reference=reference, precision=precision, msg=msg)
  751. factual = self._export_ascii_vector(vector=actual,
  752. name_part='assertVectorEqualsVector_actual',
  753. digits=digits)
  754. freference = self._export_ascii_vector(vector=reference,
  755. name_part='assertVectorEqualsVector_reference',
  756. digits=digits)
  757. self.assertVectorAsciiEqualsVectorAscii(actual=factual,
  758. reference=freference,
  759. remove_files=True,
  760. msg=msg)
  761. def assertVectorEqualsAscii(self, actual, reference, digits, precision, msg=None):
  762. """Test that vector is equal to the vector stored in GRASS ASCII file.
  763. .. note:
  764. This test should not be used to test ``v.in.ascii`` and
  765. ``v.out.ascii`` modules.
  766. .. warning:
  767. ASCII files for vectors are loaded into memory, so this
  768. function works well only for "not too big" vector maps.
  769. """
  770. # vector to ascii
  771. # text diff of two ascii files
  772. # it may actually import the file and do other asserts
  773. factual = self._export_ascii_vector(vector=actual,
  774. name_part='assertVectorEqualsAscii_actual',
  775. digits=digits)
  776. vreference = None
  777. try:
  778. vreference = self._import_ascii_vector(filename=reference,
  779. name_part='assertVectorEqualsAscii_reference')
  780. self.assertVectorInfoEqualsVectorInfo(actual=actual,
  781. reference=vreference,
  782. precision=precision, msg=msg)
  783. self.assertVectorAsciiEqualsVectorAscii(actual=factual,
  784. reference=reference,
  785. remove_files=False,
  786. msg=msg)
  787. finally:
  788. # TODO: manage using cleanup settings
  789. # we rely on fail method to either raise or return (soon)
  790. os.remove(factual)
  791. if vreference:
  792. self.runModule('g.remove', flags='f', type='vector', name=vreference)
  793. # TODO: we expect v.out.ascii to give the same order all the time, is that OK?
  794. def assertVectorAsciiEqualsVectorAscii(self, actual, reference,
  795. remove_files=False, msg=None):
  796. """Test that two GRASS ASCII vector files are equal.
  797. .. note:
  798. This test should not be used to test ``v.in.ascii`` and
  799. ``v.out.ascii`` modules.
  800. .. warning:
  801. ASCII files for vectors are loaded into memory, so this
  802. function works well only for "not too big" vector maps.
  803. """
  804. import difflib
  805. # 'U' taken from difflib documentation
  806. fromlines = open(actual, 'U').readlines()
  807. tolines = open(reference, 'U').readlines()
  808. context_lines = 3 # number of context lines
  809. # TODO: filenames are set to "actual" and "reference", isn't it too general?
  810. # it is even more useful if map names or file names are some generated
  811. # with hash or some other unreadable things
  812. # other styles of diffs are available too
  813. # but unified is a good choice if you are used to svn or git
  814. # workaround for missing -h (do not print header) flag in v.out.ascii
  815. num_lines_of_header = 10
  816. diff = difflib.unified_diff(fromlines[num_lines_of_header:],
  817. tolines[num_lines_of_header:],
  818. 'reference', 'actual', n=context_lines)
  819. # TODO: this should be solved according to cleanup policy
  820. # but the parameter should be kept if it is an existing file
  821. # or using this method by itself
  822. if remove_files:
  823. os.remove(actual)
  824. os.remove(reference)
  825. stdmsg = ("There is a difference between vectors when compared as"
  826. " ASCII files.\n")
  827. output = StringIO.StringIO()
  828. # TODO: there is a diff size constant which we can use
  829. # we are setting it unlimited but we can just set it large
  830. maxlines = 100
  831. i = 0
  832. for line in diff:
  833. if i >= maxlines:
  834. break
  835. output.write(line)
  836. i += 1
  837. stdmsg += output.getvalue()
  838. output.close()
  839. # it seems that there is not better way of asking whether there was
  840. # a difference (always a iterator object is returned)
  841. if i > 0:
  842. # do HTML diff only if there is not too many lines
  843. # TODO: this might be tough to do with some more sophisticated way of reports
  844. if self.html_reports and i < maxlines:
  845. # TODO: this might be here and somehow stored as file or done in reporter again if right information is stored
  846. # i.e., files not deleted or the whole strings passed
  847. # alternative is make_table() which is the same but creates just a table not a whole document
  848. # TODO: all HTML files might be collected by the main reporter
  849. # TODO: standardize the format of name of HTML file
  850. # for one test id there is only one possible file of this name
  851. htmldiff_file_name = self.id() + '_ascii_diff' + '.html'
  852. self.supplementary_files.append(htmldiff_file_name)
  853. htmldiff = difflib.HtmlDiff().make_file(fromlines, tolines,
  854. 'reference', 'actual',
  855. context=True,
  856. numlines=context_lines)
  857. htmldiff_file = open(htmldiff_file_name, 'w')
  858. for line in htmldiff:
  859. htmldiff_file.write(line)
  860. htmldiff_file.close()
  861. self.fail(self._formatMessage(msg, stdmsg))
  862. @classmethod
  863. def runModule(cls, module, expecting_stdout=False, **kwargs):
  864. """Run PyGRASS module.
  865. Runs the module and raises an exception if the module ends with
  866. non-zero return code. Usually, this is the same as testing the
  867. return code and raising exception but by using this method,
  868. you give testing framework more control over the execution,
  869. error handling and storing of output.
  870. In terms of testing framework, this function causes a common error,
  871. not a test failure.
  872. :raises CalledModuleError: if the module failed
  873. """
  874. module = _module_from_parameters(module, **kwargs)
  875. _check_module_run_parameters(module)
  876. try:
  877. module.run()
  878. except CalledModuleError:
  879. # here exception raised by run() with finish_=True would be
  880. # almost enough but we want some additional info to be included
  881. # in the test report
  882. errors = module.outputs.stderr
  883. # provide diagnostic at least in English locale
  884. # TODO: standardized error code would be handy here
  885. import re
  886. if re.search('Raster map.*not found', errors, flags=re.DOTALL):
  887. errors += "\nSee available raster maps:\n"
  888. errors += call_module('g.list', type='raster')
  889. if re.search('Vector map.*not found', errors, flags=re.DOTALL):
  890. errors += "\nSee available vector maps:\n"
  891. errors += call_module('g.list', type='vector')
  892. # TODO: message format, parameters
  893. raise CalledModuleError(module.popen.returncode, module.name,
  894. module.get_python(),
  895. errors=errors)
  896. # TODO: use this also in assert and apply when appropriate
  897. if expecting_stdout and not module.outputs.stdout.strip():
  898. if module.outputs.stderr:
  899. errors = " The errors are:\n" + module.outputs.stderr
  900. else:
  901. errors = " There were no error messages."
  902. if module.outputs.stdout:
  903. # this is not appropriate for translation but we don't want
  904. # and don't need testing to be translated
  905. got = "only whitespace."
  906. else:
  907. got = "nothing."
  908. raise RuntimeError("Module call " + module.get_python() +
  909. " ended successfully but we were expecting"
  910. " output and got " + got + errors)
  911. # TODO: we can also comapre time to some expected but that's tricky
  912. # maybe we should measure time but the real benchmarks with stdin/stdout
  913. # should be done by some other function
  914. # TODO: this should be the function used for valgrind or profiling or debug
  915. # TODO: it asserts the rc but it does much more, so testModule?
  916. # TODO: do we need special function for testing module failures or just add parameter returncode=0?
  917. # TODO: consider not allowing to call this method more than once
  918. # the original idea was to run this method just once for test method
  919. # but for "integration" tests (script-like tests with more than one module)
  920. # it would be better to be able to use this multiple times
  921. # TODO: enable merging streams?
  922. def assertModule(self, module, msg=None, **kwargs):
  923. """Run PyGRASS module in controlled way and assert non-zero return code.
  924. You should use this method to invoke module you are testing.
  925. By using this method, you give testing framework more control over
  926. the execution, error handling and storing of output.
  927. It will not print module stdout and stderr, instead it will always
  928. store them for further examination. Streams are stored separately.
  929. This method is not suitable for testing error states of the module.
  930. If you want to test behavior which involves non-zero return codes
  931. and examine stderr in test, use `assertModuleFail()` method.
  932. Runs the module and causes test failure if module ends with
  933. non-zero return code.
  934. """
  935. module = _module_from_parameters(module, **kwargs)
  936. _check_module_run_parameters(module)
  937. try:
  938. module.run()
  939. self.grass_modules.append(module.name)
  940. except CalledModuleError:
  941. print module.outputs.stdout
  942. print module.outputs.stderr
  943. # TODO: message format
  944. # TODO: stderr?
  945. stdmsg = ('Running <{m.name}> module ended'
  946. ' with non-zero return code ({m.popen.returncode})\n'
  947. 'Called: {code}\n'
  948. 'See the folowing errors:\n'
  949. '{errors}'.format(
  950. m=module, code=module.get_python(),
  951. errors=module.outputs.stderr
  952. ))
  953. self.fail(self._formatMessage(msg, stdmsg))
  954. print module.outputs.stdout
  955. print module.outputs.stderr
  956. # log these to final report
  957. # TODO: always or only if the calling test method failed?
  958. # in any case, this must be done before self.fail()
  959. # module.outputs['stdout'].value
  960. # module.outputs['stderr'].value
  961. # TODO: should we merge stderr to stdout in this case?
  962. def assertModuleFail(self, module, msg=None, **kwargs):
  963. """Test that module fails with a non-zero return code.
  964. Works like `assertModule()` but expects module to fail.
  965. """
  966. module = _module_from_parameters(module, **kwargs)
  967. _check_module_run_parameters(module)
  968. # note that we cannot use finally because we do not leave except
  969. try:
  970. module.run()
  971. self.grass_modules.append(module.name)
  972. except CalledModuleError:
  973. print module.outputs.stdout
  974. print module.outputs.stderr
  975. else:
  976. print module.outputs.stdout
  977. print module.outputs.stderr
  978. stdmsg = ('Running <%s> ended with zero (successful) return code'
  979. ' when expecting module to fail' % module.get_python())
  980. self.fail(self._formatMessage(msg, stdmsg))
  981. # TODO: add tests and documentation to methods which are using this function
  982. # some test and documentation add to assertModuleKeyValue
  983. def _module_from_parameters(module, **kwargs):
  984. if kwargs:
  985. if not isinstance(module, basestring):
  986. raise ValueError('module can be only string or PyGRASS Module')
  987. if isinstance(module, Module):
  988. raise ValueError('module can be only string if other'
  989. ' parameters are given')
  990. # allow to pass all parameters in one dictionary called parameters
  991. if kwargs.keys() == ['parameters']:
  992. kwargs = kwargs['parameters']
  993. module = SimpleModule(module, **kwargs)
  994. return module
  995. def _check_module_run_parameters(module):
  996. # in this case module already run and we would start it again
  997. if module.run_:
  998. raise ValueError('Do not run the module manually, set run_=False')
  999. if not module.finish_:
  1000. raise ValueError('This function will always finish module run,'
  1001. ' set finish_=None or finish_=True.')
  1002. # we expect most of the usages with stdout=PIPE
  1003. # TODO: in any case capture PIPE always?
  1004. if module.stdout_ is None:
  1005. module.stdout_ = subprocess.PIPE
  1006. elif module.stdout_ != subprocess.PIPE:
  1007. raise ValueError('stdout_ can be only PIPE or None')
  1008. if module.stderr_ is None:
  1009. module.stderr_ = subprocess.PIPE
  1010. elif module.stderr_ != subprocess.PIPE:
  1011. raise ValueError('stderr_ can be only PIPE or None')
  1012. # because we want to capture it