case.py 53 KB

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