case.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.gunittest.case
  3. @brief GRASS Python testing framework test case
  4. (C) 2014 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. @author Vaclav Petras
  9. """
  10. import os
  11. import subprocess
  12. import unittest
  13. from unittest.util import safe_repr
  14. from grass.pygrass.modules import Module
  15. from grass.exceptions import CalledModuleError
  16. from .gmodules import call_module
  17. from .checkers import (check_text_ellipsis,
  18. text_to_keyvalue, keyvalue_equals, diff_keyvalue,
  19. file_md5, files_equal_md5)
  20. class TestCase(unittest.TestCase):
  21. # we dissable R0904 for all TestCase classes because their purpose is to
  22. # provide a lot of assert methods
  23. # pylint: disable=R0904
  24. """
  25. Always use keyword arguments for all parameters other than first two. For
  26. the first two, it is recommended to use keyword arguments but not required.
  27. """
  28. longMessage = True # to get both standard and custom message
  29. maxDiff = None # we can afford long diffs
  30. _temp_region = None # to control the temporary region
  31. def __init__(self, methodName):
  32. super(TestCase, self).__init__(methodName)
  33. def _formatMessage(self, msg, standardMsg):
  34. """Honor the longMessage attribute when generating failure messages.
  35. If longMessage is False this means:
  36. * Use only an explicit message if it is provided
  37. * Otherwise use the standard message for the assert
  38. If longMessage is True:
  39. * Use the standard message
  40. * If an explicit message is provided, return string with both messages
  41. Based on Python unittest _formatMessage, formatting changed.
  42. """
  43. if not self.longMessage:
  44. return msg or standardMsg
  45. if msg is None:
  46. return standardMsg
  47. try:
  48. # don't switch to '{}' formatting in Python 2.X
  49. # it changes the way unicode input is handled
  50. return '%s \n%s' % (msg, standardMsg)
  51. except UnicodeDecodeError:
  52. return '%s \n%s' % (safe_repr(msg), safe_repr(standardMsg))
  53. @classmethod
  54. def use_temp_region(cls):
  55. """Use temporary region instead of the standard one for this process.
  56. If you use this method, you have to call it in `setUpClass()`
  57. and call `del_temp_region()` in `tearDownClass()`. By this you
  58. ensure that each test method will have its own region and will
  59. not influence other classes.
  60. ::
  61. @classmethod
  62. def setUpClass(self):
  63. self.use_temp_region()
  64. @classmethod
  65. def tearDownClass(self):
  66. self.del_temp_region()
  67. You can also call the methods in `setUp()` and `tearDown()` if
  68. you are using them.
  69. Copies the current region to a temporary region with
  70. ``g.region save=``, then sets ``WIND_OVERRIDE`` to refer
  71. to that region.
  72. """
  73. # we use just the class name since we rely on the invokation system
  74. # where each test file is separate process and nothing runs
  75. # in parallel inside
  76. name = "tmp.%s" % (cls.__name__)
  77. call_module("g.region", save=name, overwrite=True)
  78. os.environ['WIND_OVERRIDE'] = name
  79. cls._temp_region = name
  80. @classmethod
  81. def del_temp_region(cls):
  82. """Remove the temporary region.
  83. Unsets ``WIND_OVERRIDE`` and removes any region named by it.
  84. """
  85. assert cls._temp_region
  86. name = os.environ.pop('WIND_OVERRIDE')
  87. if name != cls._temp_region:
  88. # be strict about usage of region
  89. raise RuntimeError("Inconsistent use of"
  90. " TestCase.use_temp_region, WIND_OVERRIDE"
  91. " or temporary region in general\n"
  92. "Region to which should be now deleted ({n})"
  93. " by TestCase class"
  94. "does not corresond to currently set"
  95. " WIND_OVERRIDE ({c})",
  96. n=cls._temp_region, c=name)
  97. call_module("g.remove", quiet=True, region=name)
  98. # TODO: we don't know if user calls this
  99. # so perhaps some decorator which would use with statemet
  100. # but we have zero chance of infuencing another test class
  101. # since we use class-specific name for temporary region
  102. def assertLooksLike(self, actual, reference, msg=None):
  103. """Test that ``actual`` text is the same as ``referece`` with ellipses.
  104. See :func:`check_text_ellipsis` for details of behavior.
  105. """
  106. self.assertTrue(isinstance(actual, basestring), (
  107. 'actual argument is not a string'))
  108. self.assertTrue(isinstance(reference, basestring), (
  109. 'reference argument is not a string'))
  110. if not check_text_ellipsis(actual=actual, reference=reference):
  111. # TODO: add support for multiline (first line general, others with details)
  112. standardMsg = '"%s" does not correspond with "%s"' % (actual,
  113. reference)
  114. self.fail(self._formatMessage(msg, standardMsg))
  115. # TODO: decide if precision is mandatory
  116. # (note that we don't need precision for strings and usually for integers)
  117. # TODO: auto-determine precision based on the map type
  118. # TODO: we can have also more general function without the subset reference
  119. # TODO: change name to Module
  120. def assertCommandKeyValue(self, module, reference, sep,
  121. precision, msg=None, **parameters):
  122. """Test that output of a module is the same as provided subset.
  123. ::
  124. self.assertCommandKeyValue('r.info', map='elevation', flags='gr',
  125. reference=dict(min=55.58, max=156.33),
  126. precision=0.01, sep='=')
  127. ::
  128. module = SimpleModule('r.info', map='elevation', flags='gr')
  129. self.assertCommandKeyValue(module,
  130. reference=dict(min=55.58, max=156.33),
  131. precision=0.01, sep='=')
  132. The output of the module should be key-value pairs (shell script style)
  133. which is typically obtained using ``-g`` flag.
  134. """
  135. if isinstance(reference, basestring):
  136. reference = text_to_keyvalue(reference, sep=sep, skip_empty=True)
  137. module = _module_from_parameters(module, **parameters)
  138. self.runModule(module)
  139. raster_univar = text_to_keyvalue(module.outputs.stdout,
  140. sep=sep, skip_empty=True)
  141. if not keyvalue_equals(dict_a=reference, dict_b=raster_univar,
  142. a_is_subset=True, precision=precision):
  143. unused, missing, mismatch = diff_keyvalue(dict_a=reference,
  144. dict_b=raster_univar,
  145. a_is_subset=True,
  146. precision=precision)
  147. if missing:
  148. raise ValueError("%s output does not contain"
  149. " the following keys"
  150. " provided in reference"
  151. ": %s\n" % (module, ", ".join(missing)))
  152. if mismatch:
  153. stdMsg = "%s difference:\n" % module
  154. stdMsg += "mismatch values"
  155. stdMsg += "(key, reference, actual): %s\n" % mismatch
  156. stdMsg += 'command: %s %s' % (module, parameters)
  157. else:
  158. # we can probably remove this once we have more tests
  159. # of keyvalue_equals and diff_keyvalue against each other
  160. raise RuntimeError("keyvalue_equals() showed difference but"
  161. " diff_keyvalue() did not. This can be"
  162. " a bug in one of them or in the caller"
  163. " (assertCommandKeyValue())")
  164. self.fail(self._formatMessage(msg, stdMsg))
  165. def assertRasterFitsUnivar(self, raster, reference,
  166. precision=None, msg=None):
  167. r"""Test that raster map has the values obtained by r.univar module.
  168. The function does not require all values from r.univar.
  169. Only the provided values are tested.
  170. Typical example is checking minimum, maximum and number of NULL cells
  171. in the map::
  172. values = 'null_cells=0\nmin=55.5787925720215\nmax=156.329864501953'
  173. self.assertRasterFitsUnivar(map='elevation', reference=values)
  174. Use keyword arguments syntax for all function parameters.
  175. Does not -e (extended statistics) flag, use `assertCommandKeyValue()`
  176. for the full interface of arbitrary module.
  177. """
  178. self.assertCommandKeyValue(module='r.univar',
  179. map=raster,
  180. separator='=',
  181. flags='g',
  182. reference=reference, msg=msg, sep='=',
  183. precision=precision)
  184. def assertRasterFitsInfo(self, raster, reference,
  185. precision=None, msg=None):
  186. r"""Test that raster map has the values obtained by v.univar module.
  187. The function does not require all values from v.univar.
  188. Only the provided values are tested.
  189. Typical example is checking minimum, maximum and type of the map::
  190. minmax = 'min=0\nmax=1451\ndatatype=FCELL'
  191. self.assertRasterFitsInfo(map='elevation', reference=values)
  192. Use keyword arguments syntax for all function parameters.
  193. This function supports values obtained -r (range) and
  194. -e (extended metadata) flags.
  195. """
  196. self.assertCommandKeyValue(module='r.info',
  197. map=raster, flags='gre',
  198. reference=reference, msg=msg, sep='=',
  199. precision=precision)
  200. def assertVectorFitsUnivar(self, map, column, reference, msg=None,
  201. layer=None, type=None, where=None,
  202. precision=None):
  203. r"""Test that vector map has the values obtained by v.univar module.
  204. The function does not require all values from v.univar.
  205. Only the provided values are tested.
  206. Typical example is checking minimum and maximum of a column::
  207. minmax = 'min=0\nmax=1451'
  208. self.assertVectorFitsUnivar(map='bridges', column='WIDTH',
  209. reference=minmax)
  210. Use keyword arguments syntax for all function parameters.
  211. Does not support -d (geometry distances) flag, -e (extended statistics)
  212. flag and few other, use `assertCommandKeyValue` for the full interface
  213. of arbitrary module.
  214. """
  215. parameters = dict(map=map, column=column, flags='g')
  216. if layer:
  217. parameters.update(layer=layer)
  218. if type:
  219. parameters.update(type=type)
  220. if where:
  221. parameters.update(where=where)
  222. self.assertCommandKeyValue(module='v.univar',
  223. reference=reference, msg=msg, sep='=',
  224. precision=precision,
  225. **parameters)
  226. # TODO: use precision?
  227. # TODO: write a test for this method with r.in.ascii
  228. def assertRasterMinMax(self, map, refmin, refmax, msg=None):
  229. """Test that raster map minimum and maximum are within limits.
  230. Map minimum and maximum is tested against expression::
  231. refmin <= actualmin and refmax >= actualmax
  232. Use keyword arguments syntax for all function parameters.
  233. To check that more statistics have certain values use
  234. `assertRasterFitsUnivar()` or `assertRasterFitsInfo()`
  235. """
  236. stdout = call_module('r.info', map=map, flags='r')
  237. actual = text_to_keyvalue(stdout, sep='=')
  238. if refmin > actual['min']:
  239. stdmsg = ('The actual minimum ({a}) is smaller than the reference'
  240. ' one ({r}) for raster map {m}'
  241. ' (with maximum {o})'.format(
  242. a=actual['min'], r=refmin, m=map, o=actual['max']))
  243. self.fail(self._formatMessage(msg, stdmsg))
  244. if refmax < actual['max']:
  245. stdmsg = ('The actual maximum ({a}) is greater than the reference'
  246. ' one ({r}) for raster map {m}'
  247. ' (with minimum {o})'.format(
  248. a=actual['max'], r=refmax, m=map, o=actual['min']))
  249. self.fail(self._formatMessage(msg, stdmsg))
  250. def assertFileExists(self, filename, msg=None,
  251. skip_size_check=False, skip_access_check=False):
  252. """Test the existence of a file.
  253. .. note:
  254. By default this also checks if the file size is greater than 0
  255. since we rarely want a file to be empty. And it also checks
  256. if the file is access for reading.
  257. """
  258. if not os.path.isfile(filename):
  259. stdmsg = 'File %s does not exist' % filename
  260. self.fail(self._formatMessage(msg, stdmsg))
  261. if not skip_size_check and not os.path.getsize(filename):
  262. stdmsg = 'File %s is empty' % filename
  263. self.fail(self._formatMessage(msg, stdmsg))
  264. if not skip_access_check and not os.access(filename, os.R_OK):
  265. stdmsg = 'File %s is not accessible for reading' % filename
  266. self.fail(self._formatMessage(msg, stdmsg))
  267. def assertFileMd5(self, filename, md5, msg=None):
  268. """Test that file MD5 sum is equal to the provided sum.
  269. The typical workflow is that you create a file in a way you
  270. trust (that you obtain the right file). Then you compute MD5
  271. sum of the file. And provide the sum in a test as a string::
  272. self.assertFileMd5('result.txt', md5='807bba4ffa...')
  273. Use `file_md5()` function from this package::
  274. file_md5('original_result.txt')
  275. Or in command line, use ``md5sum`` command if available:
  276. .. code-block:: sh
  277. md5sum some_file.txt
  278. Finaly, you can use Python ``hashlib`` to obtain MD5::
  279. import hashlib
  280. hasher = hashlib.md5()
  281. # expecting the file to fit into memory
  282. hasher.update(open('original_result.txt', 'rb').read())
  283. hasher.hexdigest()
  284. """
  285. self.assertFileExists(filename, msg=msg)
  286. if not file_md5(filename) == md5:
  287. standardMsg = 'File %s does not have the right MD5 sum' % filename
  288. self.fail(self._formatMessage(msg, standardMsg))
  289. def assertFilesEqualMd5(self, filename, reference, msg=None):
  290. """Test that files are the same using MD5 sum.
  291. This functions requires you to provide a file to test and
  292. a reference file. For both, MD5 sum will be computed and compared with
  293. each other.
  294. """
  295. self.assertFileExists(filename, msg=msg)
  296. # nothing for ref, missing ref_filename is an error not a test failure
  297. if not files_equal_md5(filename, reference):
  298. stdmsg = 'Files %s and %s don\'t have the same MD5 sums' % (filename,
  299. reference)
  300. self.fail(self._formatMessage(msg, stdmsg))
  301. def _compute_difference_raster(self, first, second, name_part):
  302. """Compute difference of two rasters (first - second)
  303. The name of the new raster is a long name designed to be as unique as
  304. possible and contains names of two input rasters.
  305. :param first: raster to subtract from
  306. :param second: raster used as decrement
  307. :param name_part: a unique string to be used in the difference name
  308. :returns: name of a new raster
  309. """
  310. diff = ('tmp_' + self.id() + '_compute_difference_raster_'
  311. + name_part + '_' + first + '_minus_' + second)
  312. call_module('r.mapcalc',
  313. stdin='"{d}" = "{f}" - "{s}"'.format(d=diff,
  314. f=first,
  315. s=second))
  316. return diff
  317. def assertRastersNoDifference(self, actual, reference,
  318. precision, statistics=None, msg=None):
  319. """Test that `actual` raster is not different from `reference` raster
  320. Method behaves in the same way as `assertRasterFitsUnivar()`
  321. but works on difference ``reference - actual``.
  322. If statistics is not given ``dict(min=-precision, max=precision)``
  323. is used.
  324. """
  325. if statistics is None or sorted(statistics.keys()) == ['max', 'min']:
  326. if statistics is None:
  327. statistics = dict(min=-precision, max=precision)
  328. diff = self._compute_difference_raster(reference, actual,
  329. 'assertRastersNoDifference')
  330. try:
  331. self.assertCommandKeyValue('r.info', map=diff, flags='r',
  332. sep='=', precision=precision,
  333. reference=statistics, msg=msg)
  334. finally:
  335. call_module('g.remove', rast=diff)
  336. # general case
  337. self.assertRastersDifference(actual=actual, reference=reference,
  338. statistics=statistics,
  339. precision=precision, msg=msg)
  340. def assertRastersDifference(self, actual, reference,
  341. statistics, precision, msg=None):
  342. """Test statistical values of difference of reference and actual rasters
  343. For cases when you are interested in no or minimal difference,
  344. use `assertRastersNoDifference()` instead.
  345. This method should not be used to test r.mapcalc or r.univar.
  346. """
  347. diff = self._compute_difference_raster(reference, actual,
  348. 'assertRastersDifference')
  349. try:
  350. self.assertRasterFitsUnivar(raster=diff, reference=statistics,
  351. precision=precision, msg=msg)
  352. finally:
  353. call_module('g.remove', rast=diff)
  354. @classmethod
  355. def runModule(cls, module, **kwargs):
  356. """Run PyGRASS module.
  357. Runs the module and raises an exception if the module ends with
  358. non-zero return code. Usually, this is the same as testing the
  359. return code and raising exception but by using this method,
  360. you give testing framework more control over the execution,
  361. error handling and storing of output.
  362. In terms of testing framework, this function causes a common error,
  363. not a test failure.
  364. :raises CalledModuleError: if the module failed
  365. """
  366. module = _module_from_parameters(module, **kwargs)
  367. if module.run_:
  368. raise ValueError('Do not run the module manually, set run_=False')
  369. if not module.finish_:
  370. raise ValueError('This function will always finish module run,'
  371. ' set finish_=None or finish_=True.')
  372. # we expect most of the usages with stdout=PIPE
  373. # TODO: in any case capture PIPE always?
  374. if module.stdout_ is None:
  375. module.stdout_ = subprocess.PIPE
  376. elif module.stdout_ != subprocess.PIPE:
  377. raise ValueError('stdout_ can be only PIPE or None')
  378. if module.stderr_ is None:
  379. module.stderr_ = subprocess.PIPE
  380. elif module.stderr_ != subprocess.PIPE:
  381. raise ValueError('stderr_ can be only PIPE or None')
  382. # because we want to capture it
  383. module.run()
  384. if module.popen.returncode:
  385. errors = module.outputs['stderr'].value
  386. # provide diagnostic at least in English locale
  387. # TODO: standardized error code would be handy here
  388. import re
  389. if re.search('Raster map.*not found', errors, flags=re.DOTALL):
  390. errors += "\nSee available raster maps:\n"
  391. errors += call_module('g.list', type='rast')
  392. if re.search('Vector map.*not found', errors, flags=re.DOTALL):
  393. errors += "\nSee available vector maps:\n"
  394. errors += call_module('g.list', type='vect')
  395. # TODO: message format, parameters
  396. raise CalledModuleError(module.popen.returncode, module.name,
  397. module.get_python(),
  398. errors=errors)
  399. # TODO: we can also comapre time to some expected but that's tricky
  400. # maybe we should measure time but the real benchmarks with stdin/stdout
  401. # should be done by some other function
  402. # TODO: this should be the function used for valgrind or profiling or debug
  403. # TODO: it asserts the rc but it does much more, so testModule?
  404. # TODO: do we need special function for testing module failures or just add parameter returncode=0?
  405. # TODO: consider not allowing to call this method more than once
  406. # the original idea was to run this method just once for test method
  407. # but for "integration" tests (script-like tests with more than one module)
  408. # it would be better to be able to use this multiple times
  409. # TODO: enable merging streams?
  410. def assertModule(self, module, msg=None, **kwargs):
  411. """Run PyGRASS module in controlled way and assert non-zero return code.
  412. You should use this method to invoke module you are testing.
  413. By using this method, you give testing framework more control over
  414. the execution, error handling and storing of output.
  415. It will not print module stdout and stderr, instead it will always
  416. store them for further examination. Streams are stored separately.
  417. This method is not suitable for testing error states of the module.
  418. If you want to test behavior which involves non-zero return codes
  419. and examine stderr in test, use `assertModuleFail()` method.
  420. Runs the module and causes test failure if module ends with
  421. non-zero return code.
  422. """
  423. module = _module_from_parameters(module, **kwargs)
  424. # TODO: merge stderr to stdout? if caller gives PIPE, for sure not
  425. if module.run_:
  426. raise ValueError('Do not run the module manually, set run_=False')
  427. if not module.finish_:
  428. raise ValueError('This function will always finish module run,'
  429. ' set finish_=None or finish_=True.')
  430. if module.stdout_ is None:
  431. module.stdout_ = subprocess.PIPE
  432. elif module.stdout_ != subprocess.PIPE:
  433. raise ValueError('stdout_ can be only PIPE or None')
  434. # because we want to capture it
  435. if module.stderr_ is None:
  436. module.stderr_ = subprocess.PIPE
  437. elif module.stderr_ != subprocess.PIPE:
  438. raise ValueError('stderr_ can be only PIPE or None')
  439. # because we want to capture it
  440. module.run()
  441. print module.outputs['stdout'].value
  442. print module.outputs['stderr'].value
  443. if module.popen.returncode:
  444. # TODO: message format
  445. # TODO: stderr?
  446. stdmsg = ('Running <{m.name}> module ended'
  447. ' with non-zero return code ({m.popen.returncode})\n'
  448. 'Called: {code}\n'
  449. 'See the folowing errors:\n'
  450. '{errors}'.format(
  451. m=module, code=module.get_python(),
  452. errors=module.outputs["stderr"].value
  453. ))
  454. self.fail(self._formatMessage(msg, stdmsg))
  455. # log these to final report
  456. # TODO: always or only if the calling test method failed?
  457. # in any case, this must be done before self.fail()
  458. # module.outputs['stdout'].value
  459. # module.outputs['stderr'].value
  460. # TODO: should we merge stderr to stdout in this case?
  461. def assertModuleFail(self, module, msg=None, **kwargs):
  462. """Test that module fails with a non-zero return code.
  463. Works like `assertModule()` but expects module to fail.
  464. """
  465. module = _module_from_parameters(module, **kwargs)
  466. if module.run_:
  467. raise ValueError('Do not run the module manually, set run_=False')
  468. if not module.finish_:
  469. raise ValueError('This function will always finish module run,'
  470. ' set finish_=None or finish_=True.')
  471. if module.stdout_ is None:
  472. module.stdout_ = subprocess.PIPE
  473. elif module.stdout_ != subprocess.PIPE:
  474. raise ValueError('stdout_ can be only PIPE or None')
  475. # because we want to capture it
  476. if module.stderr_ is None:
  477. module.stderr_ = subprocess.PIPE
  478. elif module.stderr_ != subprocess.PIPE:
  479. raise ValueError('stderr_ can be only PIPE or None')
  480. # because we want to capture it
  481. module.run()
  482. print module.outputs['stdout'].value
  483. print module.outputs['stderr'].value
  484. if not module.popen.returncode:
  485. stdmsg = ('Running <%s> ended with zero (successful) return code'
  486. ' when expecting module to fail' % module.get_python())
  487. self.fail(self._formatMessage(msg, stdmsg))
  488. # TODO: add tests and documentation to methods which are using this function
  489. # some test and documentation add to assertCommandKeyValue
  490. def _module_from_parameters(module, **kwargs):
  491. if kwargs:
  492. if not isinstance(module, basestring):
  493. raise ValueError('module can be only string or PyGRASS Module')
  494. if isinstance(module, Module):
  495. raise ValueError('module can be only string if other'
  496. ' parameters are given')
  497. # allow to pass all parameters in one dictionary called parameters
  498. if kwargs.keys() == ['parameters']:
  499. kwargs = kwargs['parameters']
  500. module = Module(module, run_=False, **kwargs)
  501. return module