case.py 56 KB

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