case.py 48 KB

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