case.py 57 KB

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