case.py 48 KB

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