case.py 56 KB

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