case.py 49 KB

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