case.py 49 KB

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