case.py 56 KB

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