case.py 26 KB

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