case.py 56 KB

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