invoker.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # -*- coding: utf-8 -*-
  2. """GRASS Python testing framework test files invoker (runner)
  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 sys
  11. import shutil
  12. import subprocess
  13. from .checkers import text_to_keyvalue
  14. from .loader import GrassTestLoader, discover_modules
  15. from .reporters import (GrassTestFilesMultiReporter,
  16. GrassTestFilesTextReporter, GrassTestFilesHtmlReporter,
  17. TestsuiteDirReporter, GrassTestFilesKeyValueReporter,
  18. get_svn_path_authors,
  19. NoopFileAnonymizer, keyvalue_to_text)
  20. from .utils import silent_rmtree, ensure_dir
  21. try:
  22. from string import maketrans
  23. except ImportError:
  24. maketrans = str.maketrans
  25. # needed for write_gisrc
  26. # TODO: it would be good to find some way of writing rc without the need to
  27. # have GRASS proprly set (anything from grass.script requires translations to
  28. # be set, i.e. the GRASS environment properly set)
  29. import grass.script.setup as gsetup
  30. import collections
  31. # TODO: this might be more extend then update
  32. def update_keyval_file(filename, module, returncode):
  33. if os.path.exists(filename):
  34. with open(filename, 'r') as keyval_file:
  35. keyval = text_to_keyvalue(keyval_file.read(), sep='=')
  36. else:
  37. keyval = {}
  38. # this is for one file
  39. test_file_authors = get_svn_path_authors(module.abs_file_path)
  40. # in case that SVN is not available use empty authors
  41. if test_file_authors is None:
  42. test_file_authors = ''
  43. # always owerwrite name and status
  44. keyval['name'] = module.name
  45. keyval['tested_dir'] = module.tested_dir
  46. if 'status' not in keyval.keys():
  47. keyval['status'] = 'failed' if returncode else 'passed'
  48. keyval['returncode'] = returncode
  49. keyval['test_file_authors'] = test_file_authors
  50. with open(filename, 'w') as keyval_file:
  51. keyval_file.write(keyvalue_to_text(keyval))
  52. return keyval
  53. class GrassTestFilesInvoker(object):
  54. """A class used to invoke test files and create the main report"""
  55. # TODO: it is not clear what clean_outputs mean, if should be split
  56. # std stream, random outputs, saved results, profiling
  57. # not stdout and stderr if they contain test results
  58. # we can also save only failed tests, or generate only if assert fails
  59. def __init__(self, start_dir,
  60. clean_mapsets=True, clean_outputs=True, clean_before=True,
  61. testsuite_dir='testsuite', file_anonymizer=None):
  62. """
  63. :param bool clean_mapsets: if the mapsets should be removed
  64. :param bool clean_outputs: meaning is unclear: random tests outputs,
  65. saved images from maps, profiling?
  66. :param bool clean_before: if mapsets, outputs, and results
  67. should be removed before the tests start
  68. (advantageous when the previous run left everything behind)
  69. """
  70. self.start_dir = start_dir
  71. self.clean_mapsets = clean_mapsets
  72. self.clean_outputs = clean_outputs
  73. self.clean_before = clean_before
  74. self.testsuite_dir = testsuite_dir # TODO: solve distribution of this constant
  75. # reporter is created for each call of run_in_location()
  76. self.reporter = None
  77. self.testsuite_dirs = None
  78. if file_anonymizer is None:
  79. self._file_anonymizer = NoopFileAnonymizer()
  80. else:
  81. self._file_anonymizer = file_anonymizer
  82. def _create_mapset(self, gisdbase, location, module):
  83. """Create mapset according to information in module.
  84. :param loader.GrassTestPythonModule module:
  85. """
  86. # using path.sep but also / and \ for cases when it is confused
  87. # (namely the case of Unix path on MS Windows)
  88. # replace . to get rid of unclean path
  89. # TODO: clean paths
  90. # note that backslash cannot be at the end of raw string
  91. dir_as_name = module.tested_dir.translate(maketrans(r'/\.', '___'))
  92. mapset = dir_as_name + '_' + module.name
  93. # TODO: use grass module to do this? but we are not in the right gisdbase
  94. mapset_dir = os.path.join(gisdbase, location, mapset)
  95. if self.clean_before:
  96. silent_rmtree(mapset_dir)
  97. os.mkdir(mapset_dir)
  98. # TODO: default region in mapset will be what?
  99. # copy WIND file from PERMANENT
  100. # TODO: this should be a function in grass.script (used also in gis_set.py, PyGRASS also has its way with Mapset)
  101. # TODO: are premisions an issue here?
  102. shutil.copy(os.path.join(gisdbase, location, 'PERMANENT', 'WIND'),
  103. os.path.join(mapset_dir))
  104. return mapset, mapset_dir
  105. def _run_test_module(self, module, results_dir, gisdbase, location):
  106. """Run one test file."""
  107. self.testsuite_dirs[module.tested_dir].append(module.name)
  108. cwd = os.path.join(results_dir, module.tested_dir, module.name)
  109. data_dir = os.path.join(module.file_dir, 'data')
  110. if os.path.exists(data_dir):
  111. # TODO: link dir instead of copy tree and remove link afterwads
  112. # (removing is good because of testsuite dir in samplecode)
  113. # TODO: use different dir name in samplecode and test if it works
  114. shutil.copytree(data_dir, os.path.join(cwd, 'data'),
  115. ignore=shutil.ignore_patterns('*.svn*'))
  116. ensure_dir(os.path.abspath(cwd))
  117. # TODO: put this to constructor and copy here again
  118. env = os.environ.copy()
  119. mapset, mapset_dir = self._create_mapset(gisdbase, location, module)
  120. gisrc = gsetup.write_gisrc(gisdbase, location, mapset)
  121. # here is special setting of environmental variables for running tests
  122. # some of them might be set from outside in the future and if the list
  123. # will be long they should be stored somewhere separately
  124. # use custom gisrc, not current session gisrc
  125. env['GISRC'] = gisrc
  126. # percentage in plain format is 0...10...20... ...100
  127. env['GRASS_MESSAGE_FORMAT'] = 'plain'
  128. stdout_path = os.path.join(cwd, 'stdout.txt')
  129. stderr_path = os.path.join(cwd, 'stderr.txt')
  130. stdout = open(stdout_path, 'w')
  131. stderr = open(stderr_path, 'w')
  132. self.reporter.start_file_test(module)
  133. # TODO: we might clean the directory here before test if non-empty
  134. if module.file_type == 'py':
  135. # ignoring shebang line to use current Python
  136. # and also pass parameters to it
  137. # add also '-Qwarn'?
  138. if sys.version_info.major >= 3:
  139. args = [sys.executable, '-tt', module.abs_file_path]
  140. else:
  141. args = [sys.executable, '-tt', '-3', module.abs_file_path]
  142. p = subprocess.Popen(args, cwd=cwd, env=env,
  143. stdout=stdout, stderr=stderr)
  144. elif module.file_type == 'sh':
  145. # ignoring shebang line to pass parameters to shell
  146. # expecting system to have sh or something compatible
  147. # TODO: add some special checks for MS Windows
  148. # using -x to see commands in stderr
  149. # using -e to terminate fast
  150. # from dash manual:
  151. # -e errexit If not interactive, exit immediately if any
  152. # untested command fails. The exit status of a com‐
  153. # mand is considered to be explicitly tested if the
  154. # command is used to control an if, elif, while, or
  155. # until; or if the command is the left hand operand
  156. # of an '&&' or '||' operator.
  157. p = subprocess.Popen(['sh', '-e', '-x', module.abs_file_path],
  158. cwd=cwd, env=env,
  159. stdout=stdout, stderr=stderr)
  160. else:
  161. p = subprocess.Popen([module.abs_file_path],
  162. cwd=cwd, env=env,
  163. stdout=stdout, stderr=stderr)
  164. returncode = p.wait()
  165. stdout.close()
  166. stderr.close()
  167. self._file_anonymizer.anonymize([stdout_path, stderr_path])
  168. test_summary = update_keyval_file(
  169. os.path.join(os.path.abspath(cwd), 'test_keyvalue_result.txt'),
  170. module=module, returncode=returncode)
  171. self.reporter.end_file_test(module=module, cwd=cwd,
  172. returncode=returncode,
  173. stdout=stdout_path, stderr=stderr_path,
  174. test_summary=test_summary)
  175. # TODO: add some try-except or with for better error handling
  176. os.remove(gisrc)
  177. # TODO: only if clean up
  178. if self.clean_mapsets:
  179. shutil.rmtree(mapset_dir)
  180. def run_in_location(self, gisdbase, location, location_type,
  181. results_dir):
  182. """Run tests in a given location"""
  183. if os.path.abspath(results_dir) == os.path.abspath(self.start_dir):
  184. raise RuntimeError("Results root directory should not be the same"
  185. " as discovery start directory")
  186. self.reporter = GrassTestFilesMultiReporter(
  187. reporters=[
  188. GrassTestFilesTextReporter(stream=sys.stderr),
  189. GrassTestFilesHtmlReporter(
  190. file_anonymizer=self._file_anonymizer,
  191. main_page_name='testfiles.html'),
  192. GrassTestFilesKeyValueReporter(
  193. info=dict(location=location, location_type=location_type))
  194. ])
  195. self.testsuite_dirs = collections.defaultdict(list) # reset list of dirs each time
  196. # TODO: move constants out of loader class or even module
  197. modules = discover_modules(start_dir=self.start_dir,
  198. grass_location=location_type,
  199. file_regexp=r'.*\.(py|sh)$',
  200. skip_dirs=GrassTestLoader.skip_dirs,
  201. testsuite_dir=GrassTestLoader.testsuite_dir,
  202. all_locations_value=GrassTestLoader.all_tests_value,
  203. universal_location_value=GrassTestLoader.universal_tests_value,
  204. import_modules=False)
  205. self.reporter.start(results_dir)
  206. for module in modules:
  207. self._run_test_module(module=module, results_dir=results_dir,
  208. gisdbase=gisdbase, location=location)
  209. self.reporter.finish()
  210. # TODO: move this to some (new?) reporter
  211. # TODO: add basic summary of linked files so that the page is not empty
  212. with open(os.path.join(results_dir, 'index.html'), 'w') as main_index:
  213. main_index.write(
  214. '<html><body>'
  215. '<h1>Tests for &lt;{location}&gt;'
  216. ' using &lt;{type}&gt; type tests</h1>'
  217. '<ul>'
  218. '<li><a href="testsuites.html">Results by testsuites</a>'
  219. ' (testsuite directories)</li>'
  220. '<li><a href="testfiles.html">Results by test files</a></li>'
  221. '<ul>'
  222. '</body></html>'
  223. .format(location=location, type=location_type))
  224. testsuite_dir_reporter = TestsuiteDirReporter(
  225. main_page_name='testsuites.html', testsuite_page_name='index.html',
  226. top_level_testsuite_page_name='testsuite_index.html')
  227. testsuite_dir_reporter.report_for_dirs(root=results_dir,
  228. directories=self.testsuite_dirs)