case.py 58 KB

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