case.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.gunittest.case
  3. @brief GRASS Python testing framework test case
  4. Copyright (C) 2014 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. @author Vaclav Petras
  9. """
  10. import os
  11. import subprocess
  12. import unittest
  13. from unittest.util import safe_repr
  14. from grass.pygrass.modules import Module
  15. from grass.exceptions import CalledModuleError
  16. from .gmodules import call_module, SimpleModule
  17. from .checkers import (check_text_ellipsis,
  18. text_to_keyvalue, keyvalue_equals, diff_keyvalue,
  19. file_md5, files_equal_md5)
  20. class TestCase(unittest.TestCase):
  21. # we dissable R0904 for all TestCase classes because their purpose is to
  22. # provide a lot of assert methods
  23. # pylint: disable=R0904
  24. """
  25. Always use keyword arguments for all parameters other than first two. For
  26. the first two, it is recommended to use keyword arguments but not required.
  27. """
  28. longMessage = True # to get both standard and custom message
  29. maxDiff = None # we can afford long diffs
  30. _temp_region = None # to control the temporary region
  31. def __init__(self, methodName):
  32. super(TestCase, self).__init__(methodName)
  33. def _formatMessage(self, msg, standardMsg):
  34. """Honor the longMessage attribute when generating failure messages.
  35. If longMessage is False this means:
  36. * Use only an explicit message if it is provided
  37. * Otherwise use the standard message for the assert
  38. If longMessage is True:
  39. * Use the standard message
  40. * If an explicit message is provided, return string with both messages
  41. Based on Python unittest _formatMessage, formatting changed.
  42. """
  43. if not self.longMessage:
  44. return msg or standardMsg
  45. if msg is None:
  46. return standardMsg
  47. try:
  48. # don't switch to '{}' formatting in Python 2.X
  49. # it changes the way unicode input is handled
  50. return '%s \n%s' % (msg, standardMsg)
  51. except UnicodeDecodeError:
  52. return '%s \n%s' % (safe_repr(msg), safe_repr(standardMsg))
  53. @classmethod
  54. def use_temp_region(cls):
  55. """Use temporary region instead of the standard one for this process.
  56. If you use this method, you have to call it in `setUpClass()`
  57. and call `del_temp_region()` in `tearDownClass()`. By this you
  58. ensure that each test method will have its own region and will
  59. not influence other classes.
  60. ::
  61. @classmethod
  62. def setUpClass(self):
  63. self.use_temp_region()
  64. @classmethod
  65. def tearDownClass(self):
  66. self.del_temp_region()
  67. You can also call the methods in `setUp()` and `tearDown()` if
  68. you are using them.
  69. Copies the current region to a temporary region with
  70. ``g.region save=``, then sets ``WIND_OVERRIDE`` to refer
  71. to that region.
  72. """
  73. # we use just the class name since we rely on the invokation system
  74. # where each test file is separate process and nothing runs
  75. # in parallel inside
  76. name = "tmp.%s" % (cls.__name__)
  77. call_module("g.region", save=name, overwrite=True)
  78. os.environ['WIND_OVERRIDE'] = name
  79. cls._temp_region = name
  80. @classmethod
  81. def del_temp_region(cls):
  82. """Remove the temporary region.
  83. Unsets ``WIND_OVERRIDE`` and removes any region named by it.
  84. """
  85. assert cls._temp_region
  86. name = os.environ.pop('WIND_OVERRIDE')
  87. if name != cls._temp_region:
  88. # be strict about usage of region
  89. raise RuntimeError("Inconsistent use of"
  90. " TestCase.use_temp_region, WIND_OVERRIDE"
  91. " or temporary region in general\n"
  92. "Region to which should be now deleted ({n})"
  93. " by TestCase class"
  94. "does not corresond to currently set"
  95. " WIND_OVERRIDE ({c})",
  96. n=cls._temp_region, c=name)
  97. call_module("g.remove", quiet=True, region=name)
  98. # TODO: we don't know if user calls this
  99. # so perhaps some decorator which would use with statemet
  100. # but we have zero chance of infuencing another test class
  101. # since we use class-specific name for temporary region
  102. def assertLooksLike(self, actual, reference, msg=None):
  103. """Test that ``actual`` text is the same as ``referece`` with ellipses.
  104. See :func:`check_text_ellipsis` for details of behavior.
  105. """
  106. self.assertTrue(isinstance(actual, basestring), (
  107. 'actual argument is not a string'))
  108. self.assertTrue(isinstance(reference, basestring), (
  109. 'reference argument is not a string'))
  110. if not check_text_ellipsis(actual=actual, reference=reference):
  111. # TODO: add support for multiline (first line general, others with details)
  112. standardMsg = '"%s" does not correspond with "%s"' % (actual,
  113. reference)
  114. self.fail(self._formatMessage(msg, standardMsg))
  115. # TODO: decide if precision is mandatory
  116. # (note that we don't need precision for strings and usually for integers)
  117. # TODO: auto-determine precision based on the map type
  118. # TODO: we can have also more general function without the subset reference
  119. # TODO: change name to Module
  120. def assertModuleKeyValue(self, module, reference, sep,
  121. precision, msg=None, **parameters):
  122. """Test that output of a module is the same as provided subset.
  123. ::
  124. self.assertModuleKeyValue('r.info', map='elevation', flags='gr',
  125. reference=dict(min=55.58, max=156.33),
  126. precision=0.01, sep='=')
  127. ::
  128. module = SimpleModule('r.info', map='elevation', flags='gr')
  129. self.assertModuleKeyValue(module,
  130. reference=dict(min=55.58, max=156.33),
  131. precision=0.01, sep='=')
  132. The output of the module should be key-value pairs (shell script style)
  133. which is typically obtained using ``-g`` flag.
  134. """
  135. if isinstance(reference, basestring):
  136. reference = text_to_keyvalue(reference, sep=sep, skip_empty=True)
  137. module = _module_from_parameters(module, **parameters)
  138. self.runModule(module)
  139. raster_univar = text_to_keyvalue(module.outputs.stdout,
  140. sep=sep, skip_empty=True)
  141. if not keyvalue_equals(dict_a=reference, dict_b=raster_univar,
  142. a_is_subset=True, precision=precision):
  143. unused, missing, mismatch = diff_keyvalue(dict_a=reference,
  144. dict_b=raster_univar,
  145. a_is_subset=True,
  146. precision=precision)
  147. if missing:
  148. raise ValueError("%s output does not contain"
  149. " the following keys"
  150. " provided in reference"
  151. ": %s\n" % (module, ", ".join(missing)))
  152. if mismatch:
  153. stdMsg = "%s difference:\n" % module
  154. stdMsg += "mismatch values"
  155. stdMsg += "(key, reference, actual): %s\n" % mismatch
  156. stdMsg += 'command: %s %s' % (module, parameters)
  157. else:
  158. # we can probably remove this once we have more tests
  159. # of keyvalue_equals and diff_keyvalue against each other
  160. raise RuntimeError("keyvalue_equals() showed difference but"
  161. " diff_keyvalue() did not. This can be"
  162. " a bug in one of them or in the caller"
  163. " (assertModuleKeyValue())")
  164. self.fail(self._formatMessage(msg, stdMsg))
  165. def assertRasterFitsUnivar(self, raster, reference,
  166. precision=None, msg=None):
  167. r"""Test that raster map has the values obtained by r.univar module.
  168. The function does not require all values from r.univar.
  169. Only the provided values are tested.
  170. Typical example is checking minimum, maximum and number of NULL cells
  171. in the map::
  172. values = 'null_cells=0\nmin=55.5787925720215\nmax=156.329864501953'
  173. self.assertRasterFitsUnivar(map='elevation', reference=values)
  174. Use keyword arguments syntax for all function parameters.
  175. Does not -e (extended statistics) flag, use `assertModuleKeyValue()`
  176. for the full interface of arbitrary module.
  177. """
  178. self.assertModuleKeyValue(module='r.univar',
  179. map=raster,
  180. separator='=',
  181. flags='g',
  182. reference=reference, msg=msg, sep='=',
  183. precision=precision)
  184. def assertRasterFitsInfo(self, raster, reference,
  185. precision=None, msg=None):
  186. r"""Test that raster map has the values obtained by r.univar module.
  187. The function does not require all values from r.univar.
  188. Only the provided values are tested.
  189. Typical example is checking minimum, maximum and type of the map::
  190. minmax = 'min=0\nmax=1451\ndatatype=FCELL'
  191. self.assertRasterFitsInfo(map='elevation', reference=values)
  192. Use keyword arguments syntax for all function parameters.
  193. This function supports values obtained -r (range) and
  194. -e (extended metadata) flags.
  195. """
  196. self.assertModuleKeyValue(module='r.info',
  197. map=raster, flags='gre',
  198. reference=reference, msg=msg, sep='=',
  199. precision=precision)
  200. def assertRaster3dFitsUnivar(self, raster, reference,
  201. precision=None, msg=None):
  202. r"""Test that 3D raster map has the values obtained by r3.univar module.
  203. The function does not require all values from r3.univar.
  204. Only the provided values are tested.
  205. Use keyword arguments syntax for all function parameters.
  206. Does not -e (extended statistics) flag, use `assertModuleKeyValue()`
  207. for the full interface of arbitrary module.
  208. """
  209. self.assertModuleKeyValue(module='r3.univar',
  210. map=raster,
  211. separator='=',
  212. flags='g',
  213. reference=reference, msg=msg, sep='=',
  214. precision=precision)
  215. def assertRaster3dFitsInfo(self, raster, reference,
  216. precision=None, msg=None):
  217. r"""Test that raster map has the values obtained by r3.info module.
  218. The function does not require all values from r3.info.
  219. Only the provided values are tested.
  220. Use keyword arguments syntax for all function parameters.
  221. This function supports values obtained by -g (info) and -r (range).
  222. """
  223. self.assertModuleKeyValue(module='r3.info',
  224. map=raster, flags='gr',
  225. reference=reference, msg=msg, sep='=',
  226. precision=precision)
  227. def assertVectorFitsTopoInfo(self, vector, reference, msg=None):
  228. r"""Test that raster map has the values obtained by ``v.info`` module.
  229. This function uses ``-t`` flag of ``v.info`` module to get topology
  230. info, so the reference dictionary should contain appropriate set or
  231. subset of values (only the provided values are tested).
  232. A example of checking number of points::
  233. topology = dict(points=10938, primitives=10938)
  234. self.assertVectorFitsTopoInfo(map='bridges', reference=topology)
  235. Note that here we are checking also the number of primitives to prove
  236. that there are no other features besides points.
  237. No precision is applied (no difference is required). So, this function
  238. is not suitable for testing items which are floating point number
  239. (no such items are currently in topological information).
  240. Use keyword arguments syntax for all function parameters.
  241. """
  242. self.assertModuleKeyValue(module='v.info',
  243. map=vector, flags='t',
  244. reference=reference, msg=msg, sep='=',
  245. precision=0)
  246. def assertVectorFitsRegionInfo(self, vector, reference,
  247. precision, msg=None):
  248. r"""Test that raster map has the values obtained by ``v.info`` module.
  249. This function uses ``-g`` flag of ``v.info`` module to get topology
  250. info, so the reference dictionary should contain appropriate set or
  251. subset of values (only the provided values are tested).
  252. Use keyword arguments syntax for all function parameters.
  253. """
  254. self.assertModuleKeyValue(module='v.info',
  255. map=vector, flags='g',
  256. reference=reference, msg=msg, sep='=',
  257. precision=precision)
  258. def assertVectorFitsExtendedInfo(self, vector, reference, msg=None):
  259. r"""Test that raster map has the values obtained by ``v.info`` module.
  260. This function uses ``-e`` 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. The most useful items for testing (considering circumstances of test
  264. invocation) are name, title, level and num_dblinks. (When testing
  265. storing of ``v.info -e`` metadata, the selection might be different.)
  266. No precision is applied (no difference is required). So, this function
  267. is not suitable for testing items which are floating point number.
  268. Use keyword arguments syntax for all function parameters.
  269. """
  270. self.assertModuleKeyValue(module='v.info',
  271. map=vector, flags='e',
  272. reference=reference, msg=msg, sep='=',
  273. precision=0)
  274. def assertVectorFitsUnivar(self, map, column, reference, msg=None,
  275. layer=None, type=None, where=None,
  276. precision=None):
  277. r"""Test that vector map has the values obtained by v.univar module.
  278. The function does not require all values from v.univar.
  279. Only the provided values are tested.
  280. Typical example is checking minimum and maximum of a column::
  281. minmax = 'min=0\nmax=1451'
  282. self.assertVectorFitsUnivar(map='bridges', column='WIDTH',
  283. reference=minmax)
  284. Use keyword arguments syntax for all function parameters.
  285. Does not support -d (geometry distances) flag, -e (extended statistics)
  286. flag and few other, use `assertModuleKeyValue` for the full interface
  287. of arbitrary module.
  288. """
  289. parameters = dict(map=map, column=column, flags='g')
  290. if layer:
  291. parameters.update(layer=layer)
  292. if type:
  293. parameters.update(type=type)
  294. if where:
  295. parameters.update(where=where)
  296. self.assertModuleKeyValue(module='v.univar',
  297. reference=reference, msg=msg, sep='=',
  298. precision=precision,
  299. **parameters)
  300. # TODO: use precision?
  301. # TODO: write a test for this method with r.in.ascii
  302. def assertRasterMinMax(self, map, refmin, refmax, msg=None):
  303. """Test that raster map minimum and maximum are within limits.
  304. Map minimum and maximum is tested against expression::
  305. refmin <= actualmin and refmax >= actualmax
  306. Use keyword arguments syntax for all function parameters.
  307. To check that more statistics have certain values use
  308. `assertRasterFitsUnivar()` or `assertRasterFitsInfo()`
  309. """
  310. stdout = call_module('r.info', map=map, flags='r')
  311. actual = text_to_keyvalue(stdout, sep='=')
  312. if refmin > actual['min']:
  313. stdmsg = ('The actual minimum ({a}) is smaller than the reference'
  314. ' one ({r}) for raster map {m}'
  315. ' (with maximum {o})'.format(
  316. a=actual['min'], r=refmin, m=map, o=actual['max']))
  317. self.fail(self._formatMessage(msg, stdmsg))
  318. if refmax < actual['max']:
  319. stdmsg = ('The actual maximum ({a}) is greater than the reference'
  320. ' one ({r}) for raster map {m}'
  321. ' (with minimum {o})'.format(
  322. a=actual['max'], r=refmax, m=map, o=actual['min']))
  323. self.fail(self._formatMessage(msg, stdmsg))
  324. # TODO: use precision?
  325. # TODO: write a test for this method with r.in.ascii
  326. # TODO: almost the same as 2D version
  327. def assertRaster3dMinMax(self, map, refmin, refmax, msg=None):
  328. """Test that 3D raster map minimum and maximum are within limits.
  329. Map minimum and maximum is tested against expression::
  330. refmin <= actualmin and refmax >= actualmax
  331. Use keyword arguments syntax for all function parameters.
  332. To check that more statistics have certain values use
  333. `assertRaster3DFitsUnivar()` or `assertRaster3DFitsInfo()`
  334. """
  335. stdout = call_module('r3.info', map=map, flags='r')
  336. actual = text_to_keyvalue(stdout, sep='=')
  337. if refmin > actual['min']:
  338. stdmsg = ('The actual minimum ({a}) is smaller than the reference'
  339. ' one ({r}) for 3D raster map {m}'
  340. ' (with maximum {o})'.format(
  341. a=actual['min'], r=refmin, m=map, o=actual['max']))
  342. self.fail(self._formatMessage(msg, stdmsg))
  343. if refmax < actual['max']:
  344. stdmsg = ('The actual maximum ({a}) is greater than the reference'
  345. ' one ({r}) for 3D raster map {m}'
  346. ' (with minimum {o})'.format(
  347. a=actual['max'], r=refmax, m=map, o=actual['min']))
  348. self.fail(self._formatMessage(msg, stdmsg))
  349. def assertFileExists(self, filename, msg=None,
  350. skip_size_check=False, skip_access_check=False):
  351. """Test the existence of a file.
  352. .. note:
  353. By default this also checks if the file size is greater than 0
  354. since we rarely want a file to be empty. And it also checks
  355. if the file is access for reading.
  356. """
  357. if not os.path.isfile(filename):
  358. stdmsg = 'File %s does not exist' % filename
  359. self.fail(self._formatMessage(msg, stdmsg))
  360. if not skip_size_check and not os.path.getsize(filename):
  361. stdmsg = 'File %s is empty' % filename
  362. self.fail(self._formatMessage(msg, stdmsg))
  363. if not skip_access_check and not os.access(filename, os.R_OK):
  364. stdmsg = 'File %s is not accessible for reading' % filename
  365. self.fail(self._formatMessage(msg, stdmsg))
  366. def assertFileMd5(self, filename, md5, msg=None):
  367. """Test that file MD5 sum is equal to the provided sum.
  368. The typical workflow is that you create a file in a way you
  369. trust (that you obtain the right file). Then you compute MD5
  370. sum of the file. And provide the sum in a test as a string::
  371. self.assertFileMd5('result.txt', md5='807bba4ffa...')
  372. Use `file_md5()` function from this package::
  373. file_md5('original_result.txt')
  374. Or in command line, use ``md5sum`` command if available:
  375. .. code-block:: sh
  376. md5sum some_file.txt
  377. Finaly, you can use Python ``hashlib`` to obtain MD5::
  378. import hashlib
  379. hasher = hashlib.md5()
  380. # expecting the file to fit into memory
  381. hasher.update(open('original_result.txt', 'rb').read())
  382. hasher.hexdigest()
  383. """
  384. self.assertFileExists(filename, msg=msg)
  385. if not file_md5(filename) == md5:
  386. standardMsg = 'File %s does not have the right MD5 sum' % filename
  387. self.fail(self._formatMessage(msg, standardMsg))
  388. def assertFilesEqualMd5(self, filename, reference, msg=None):
  389. """Test that files are the same using MD5 sum.
  390. This functions requires you to provide a file to test and
  391. a reference file. For both, MD5 sum will be computed and compared with
  392. each other.
  393. """
  394. self.assertFileExists(filename, msg=msg)
  395. # nothing for ref, missing ref_filename is an error not a test failure
  396. if not files_equal_md5(filename, reference):
  397. stdmsg = 'Files %s and %s don\'t have the same MD5 sums' % (filename,
  398. reference)
  399. self.fail(self._formatMessage(msg, stdmsg))
  400. def _compute_difference_raster(self, first, second, name_part):
  401. """Compute difference of two rasters (first - second)
  402. The name of the new raster is a long name designed to be as unique as
  403. possible and contains names of two input rasters.
  404. :param first: raster to subtract from
  405. :param second: raster used as decrement
  406. :param name_part: a unique string to be used in the difference name
  407. :returns: name of a new raster
  408. """
  409. diff = ('tmp_' + self.id() + '_compute_difference_raster_'
  410. + name_part + '_' + first + '_minus_' + second)
  411. call_module('r.mapcalc',
  412. stdin='"{d}" = "{f}" - "{s}"'.format(d=diff,
  413. f=first,
  414. s=second))
  415. return diff
  416. # TODO: name of map generation is repeted three times
  417. # TODO: this method is almost the same as the one for 2D
  418. def _compute_difference_raster3d(self, first, second, name_part):
  419. """Compute difference of two rasters (first - second)
  420. The name of the new raster is a long name designed to be as unique as
  421. possible and contains names of two input rasters.
  422. :param first: raster to subtract from
  423. :param second: raster used as decrement
  424. :param name_part: a unique string to be used in the difference name
  425. :returns: name of a new raster
  426. """
  427. diff = ('tmp_' + self.id() + '_compute_difference_raster_'
  428. + name_part + '_' + first + '_minus_' + second)
  429. call_module('r3.mapcalc',
  430. stdin='"{d}" = "{f}" - "{s}"'.format(d=diff,
  431. f=first,
  432. s=second))
  433. return diff
  434. def _compute_vector_xor(self, ainput, alayer, binput, blayer, name_part):
  435. """Compute symmetric difference (xor) of two vectors
  436. :returns: name of a new vector
  437. """
  438. diff = ('tmp_' + self.id() + '_compute_difference_vector_'
  439. + name_part + '_' + ainput + '_' + alayer
  440. + '_minus_' + binput + '_' + blayer)
  441. call_module('v.overlay', operator='xor', ainput=ainput, binput=binput,
  442. alayer=alayer, blayer=blayer,
  443. output=diff, atype='area', btype='area', olayer='')
  444. # trying to avoid long reports full of categories by olayer=''
  445. # olayer Output layer for new category, ainput and binput
  446. # If 0 or not given, the category is not written
  447. return diff
  448. def assertRastersNoDifference(self, actual, reference,
  449. precision, statistics=None, msg=None):
  450. """Test that `actual` raster is not different from `reference` raster
  451. Method behaves in the same way as `assertRasterFitsUnivar()`
  452. but works on difference ``reference - actual``.
  453. If statistics is not given ``dict(min=-precision, max=precision)``
  454. is used.
  455. """
  456. if statistics is None or sorted(statistics.keys()) == ['max', 'min']:
  457. if statistics is None:
  458. statistics = dict(min=-precision, max=precision)
  459. diff = self._compute_difference_raster(reference, actual,
  460. 'assertRastersNoDifference')
  461. try:
  462. self.assertModuleKeyValue('r.info', map=diff, flags='r',
  463. sep='=', precision=precision,
  464. reference=statistics, msg=msg)
  465. finally:
  466. call_module('g.remove', rast=diff)
  467. else:
  468. # general case
  469. # TODO: we are using r.info min max and r.univar min max interchangably
  470. # but they might be different if region is different from map
  471. # not considered as an huge issue since we expect the tested maps
  472. # to match with region, however a documentation should containe a notice
  473. self.assertRastersDifference(actual=actual, reference=reference,
  474. statistics=statistics,
  475. precision=precision, msg=msg)
  476. def assertRastersDifference(self, actual, reference,
  477. statistics, precision, msg=None):
  478. """Test statistical values of difference of reference and actual rasters
  479. For cases when you are interested in no or minimal difference,
  480. use `assertRastersNoDifference()` instead.
  481. This method should not be used to test r.mapcalc or r.univar.
  482. """
  483. diff = self._compute_difference_raster(reference, actual,
  484. 'assertRastersDifference')
  485. try:
  486. self.assertRasterFitsUnivar(raster=diff, reference=statistics,
  487. precision=precision, msg=msg)
  488. finally:
  489. call_module('g.remove', rast=diff)
  490. def assertRasters3dNoDifference(self, actual, reference,
  491. precision, statistics=None, msg=None):
  492. """Test that `actual` raster is not different from `reference` raster
  493. Method behaves in the same way as `assertRasterFitsUnivar()`
  494. but works on difference ``reference - actual``.
  495. If statistics is not given ``dict(min=-precision, max=precision)``
  496. is used.
  497. """
  498. if statistics is None or sorted(statistics.keys()) == ['max', 'min']:
  499. if statistics is None:
  500. statistics = dict(min=-precision, max=precision)
  501. diff = self._compute_difference_raster3d(reference, actual,
  502. 'assertRasters3dNoDifference')
  503. try:
  504. self.assertModuleKeyValue('r3.info', map=diff, flags='r',
  505. sep='=', precision=precision,
  506. reference=statistics, msg=msg)
  507. finally:
  508. call_module('g.remove', rast3d=diff)
  509. else:
  510. # general case
  511. # TODO: we are using r.info min max and r.univar min max interchangably
  512. # but they might be different if region is different from map
  513. # not considered as an huge issue since we expect the tested maps
  514. # to match with region, however a documentation should containe a notice
  515. self.assertRasters3dDifference(actual=actual, reference=reference,
  516. statistics=statistics,
  517. precision=precision, msg=msg)
  518. def assertRasters3dDifference(self, actual, reference,
  519. statistics, precision, msg=None):
  520. """Test statistical values of difference of reference and actual rasters
  521. For cases when you are interested in no or minimal difference,
  522. use `assertRastersNoDifference()` instead.
  523. This method should not be used to test r3.mapcalc or r3.univar.
  524. """
  525. diff = self._compute_difference_raster3d(reference, actual,
  526. 'assertRasters3dDifference')
  527. try:
  528. self.assertRaster3dFitsUnivar(raster=diff, reference=statistics,
  529. precision=precision, msg=msg)
  530. finally:
  531. call_module('g.remove', rast3d=diff)
  532. # TODO: this works only in 2D
  533. # TODO: write tests
  534. def assertVectorIsVectorBuffered(self, actual, reference, precision, msg=None):
  535. """
  536. This method should not be used to test v.buffer, v.overlay or v.select.
  537. """
  538. # TODO: if msg is None: add info specific to this function
  539. layer = '-1'
  540. module = SimpleModule('v.info', flags='t', map=reference)
  541. self.runModule(module)
  542. ref_topo = text_to_keyvalue(module.outputs.stdout, sep='=')
  543. module = SimpleModule('v.info', flags='g', map=reference)
  544. self.runModule(module)
  545. ref_info = text_to_keyvalue(module.outputs.stdout, sep='=')
  546. self.assertVectorFitsTopoInfo(vector=actual, reference=ref_topo,
  547. msg=msg)
  548. self.assertVectorFitsRegionInfo(vector=actual, reference=ref_info,
  549. msg=msg, precision=precision)
  550. remove = []
  551. buffered = reference + '_buffered' # TODO: more unique name
  552. intersection = reference + '_intersection' # TODO: more unique name
  553. self.runModule('v.buffer', input=reference, layer=layer,
  554. output=buffered, distance=precision)
  555. remove.append(buffered)
  556. try:
  557. self.runModule('v.overlay', operator='and', ainput=actual,
  558. binput=reference,
  559. alayer=layer, blayer=layer,
  560. output=intersection, atype='area', btype='area',
  561. olayer='')
  562. remove.append(intersection)
  563. self.assertVectorFitsTopoInfo(vector=intersection, reference=ref_topo,
  564. msg=msg)
  565. self.assertVectorFitsRegionInfo(vector=intersection, reference=ref_info,
  566. msg=msg, precision=precision)
  567. finally:
  568. call_module('g.remove', vect=remove)
  569. # TODO: write tests
  570. def assertVectorsNoAreaDifference(self, actual, reference, precision,
  571. layer=1, msg=None):
  572. """Test statistical values of difference of reference and actual rasters
  573. Works only for areas.
  574. Use keyword arguments syntax for all function parameters.
  575. This method should not be used to test v.overlay or v.select.
  576. """
  577. diff = self._compute_xor_vectors(ainput=reference, binput=actual,
  578. alayer=layer, blayer=layer,
  579. name_part='assertVectorsNoDifference')
  580. try:
  581. module = SimpleModule('v.to.db', map=diff,
  582. flags='pc', separator='=')
  583. self.runModule(module)
  584. # the output of v.to.db -pc sep== should look like:
  585. # ...
  586. # 43=98606087.5818323
  587. # 44=727592.902311112
  588. # total area=2219442027.22035
  589. total_area = module.outputs.stdout.splitlines()[-1].split('=')[-1]
  590. if total_area > precision:
  591. stdmsg = ("Area of difference of vectors <{va}> and <{vr}>"
  592. " should be 0"
  593. " in the given precision ({p}) not {a}").format(
  594. va=actual, vr=reference, p=precision, a=total_area)
  595. self.fail(self._formatMessage(msg, stdmsg))
  596. finally:
  597. call_module('g.remove', vect=diff)
  598. @classmethod
  599. def runModule(cls, module, **kwargs):
  600. """Run PyGRASS module.
  601. Runs the module and raises an exception if the module ends with
  602. non-zero return code. Usually, this is the same as testing the
  603. return code and raising exception but by using this method,
  604. you give testing framework more control over the execution,
  605. error handling and storing of output.
  606. In terms of testing framework, this function causes a common error,
  607. not a test failure.
  608. :raises CalledModuleError: if the module failed
  609. """
  610. module = _module_from_parameters(module, **kwargs)
  611. _check_module_run_parameters(module)
  612. try:
  613. module.run()
  614. except CalledModuleError:
  615. # here exception raised by run() with finish_=True would be
  616. # almost enough but we want some additional info to be included
  617. # in the test report
  618. errors = module.outputs.stderr
  619. # provide diagnostic at least in English locale
  620. # TODO: standardized error code would be handy here
  621. import re
  622. if re.search('Raster map.*not found', errors, flags=re.DOTALL):
  623. errors += "\nSee available raster maps:\n"
  624. errors += call_module('g.list', type='rast')
  625. if re.search('Vector map.*not found', errors, flags=re.DOTALL):
  626. errors += "\nSee available vector maps:\n"
  627. errors += call_module('g.list', type='vect')
  628. # TODO: message format, parameters
  629. raise CalledModuleError(module.popen.returncode, module.name,
  630. module.get_python(),
  631. errors=errors)
  632. # TODO: we can also comapre time to some expected but that's tricky
  633. # maybe we should measure time but the real benchmarks with stdin/stdout
  634. # should be done by some other function
  635. # TODO: this should be the function used for valgrind or profiling or debug
  636. # TODO: it asserts the rc but it does much more, so testModule?
  637. # TODO: do we need special function for testing module failures or just add parameter returncode=0?
  638. # TODO: consider not allowing to call this method more than once
  639. # the original idea was to run this method just once for test method
  640. # but for "integration" tests (script-like tests with more than one module)
  641. # it would be better to be able to use this multiple times
  642. # TODO: enable merging streams?
  643. def assertModule(self, module, msg=None, **kwargs):
  644. """Run PyGRASS module in controlled way and assert non-zero return code.
  645. You should use this method to invoke module you are testing.
  646. By using this method, you give testing framework more control over
  647. the execution, error handling and storing of output.
  648. It will not print module stdout and stderr, instead it will always
  649. store them for further examination. Streams are stored separately.
  650. This method is not suitable for testing error states of the module.
  651. If you want to test behavior which involves non-zero return codes
  652. and examine stderr in test, use `assertModuleFail()` method.
  653. Runs the module and causes test failure if module ends with
  654. non-zero return code.
  655. """
  656. module = _module_from_parameters(module, **kwargs)
  657. _check_module_run_parameters(module)
  658. try:
  659. module.run()
  660. except CalledModuleError:
  661. print module.outputs.stdout
  662. print module.outputs.stderr
  663. # TODO: message format
  664. # TODO: stderr?
  665. stdmsg = ('Running <{m.name}> module ended'
  666. ' with non-zero return code ({m.popen.returncode})\n'
  667. 'Called: {code}\n'
  668. 'See the folowing errors:\n'
  669. '{errors}'.format(
  670. m=module, code=module.get_python(),
  671. errors=module.outputs.stderr
  672. ))
  673. self.fail(self._formatMessage(msg, stdmsg))
  674. print module.outputs.stdout
  675. print module.outputs.stderr
  676. # log these to final report
  677. # TODO: always or only if the calling test method failed?
  678. # in any case, this must be done before self.fail()
  679. # module.outputs['stdout'].value
  680. # module.outputs['stderr'].value
  681. # TODO: should we merge stderr to stdout in this case?
  682. def assertModuleFail(self, module, msg=None, **kwargs):
  683. """Test that module fails with a non-zero return code.
  684. Works like `assertModule()` but expects module to fail.
  685. """
  686. module = _module_from_parameters(module, **kwargs)
  687. _check_module_run_parameters(module)
  688. # note that we cannot use finally because we do not leave except
  689. try:
  690. module.run()
  691. except CalledModuleError:
  692. print module.outputs.stdout
  693. print module.outputs.stderr
  694. pass
  695. else:
  696. print module.outputs.stdout
  697. print module.outputs.stderr
  698. stdmsg = ('Running <%s> ended with zero (successful) return code'
  699. ' when expecting module to fail' % module.get_python())
  700. self.fail(self._formatMessage(msg, stdmsg))
  701. # TODO: add tests and documentation to methods which are using this function
  702. # some test and documentation add to assertModuleKeyValue
  703. def _module_from_parameters(module, **kwargs):
  704. if kwargs:
  705. if not isinstance(module, basestring):
  706. raise ValueError('module can be only string or PyGRASS Module')
  707. if isinstance(module, Module):
  708. raise ValueError('module can be only string if other'
  709. ' parameters are given')
  710. # allow to pass all parameters in one dictionary called parameters
  711. if kwargs.keys() == ['parameters']:
  712. kwargs = kwargs['parameters']
  713. module = SimpleModule(module, **kwargs)
  714. return module
  715. def _check_module_run_parameters(module):
  716. # in this case module already run and we would start it again
  717. if module.run_:
  718. raise ValueError('Do not run the module manually, set run_=False')
  719. if not module.finish_:
  720. raise ValueError('This function will always finish module run,'
  721. ' set finish_=None or finish_=True.')
  722. # we expect most of the usages with stdout=PIPE
  723. # TODO: in any case capture PIPE always?
  724. if module.stdout_ is None:
  725. module.stdout_ = subprocess.PIPE
  726. elif module.stdout_ != subprocess.PIPE:
  727. raise ValueError('stdout_ can be only PIPE or None')
  728. if module.stderr_ is None:
  729. module.stderr_ = subprocess.PIPE
  730. elif module.stderr_ != subprocess.PIPE:
  731. raise ValueError('stderr_ can be only PIPE or None')
  732. # because we want to capture it