case.py 60 KB

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