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