case.py 48 KB

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