case.py 55 KB

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