invoker.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.gunittest.invoker
  3. @brief GRASS Python testing framework test files invoker (runner)
  4. Copyright (C) 2014 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS GIS
  7. for details.
  8. @author Vaclav Petras
  9. """
  10. import os
  11. import sys
  12. import shutil
  13. import string
  14. import subprocess
  15. from unittest.main import TestProgram, USAGE_AS_MAIN
  16. TestProgram.USAGE = USAGE_AS_MAIN
  17. from .checkers import text_to_keyvalue
  18. from .loader import GrassTestLoader, discover_modules
  19. from .reporters import (GrassTestFilesMultiReporter,
  20. GrassTestFilesTextReporter, GrassTestFilesHtmlReporter,
  21. TestsuiteDirReporter, GrassTestFilesKeyValueReporter,
  22. get_svn_path_authors,
  23. NoopFileAnonymizer, keyvalue_to_text)
  24. from .utils import silent_rmtree, ensure_dir
  25. import grass.script.setup as gsetup
  26. import collections
  27. # TODO: this might be more extend then update
  28. def update_keyval_file(filename, module, returncode):
  29. if os.path.exists(filename):
  30. with open(filename, 'r') as keyval_file:
  31. keyval = text_to_keyvalue(keyval_file.read(), sep='=')
  32. else:
  33. keyval = {}
  34. # this is for one file
  35. test_file_authors = get_svn_path_authors(module.abs_file_path)
  36. # in case that SVN is not available use empty authors
  37. if test_file_authors is None:
  38. test_file_authors = ''
  39. # always owerwrite name and status
  40. keyval['name'] = module.name
  41. keyval['tested_dir'] = module.tested_dir
  42. if 'status' not in keyval.keys():
  43. keyval['status'] = 'failed' if returncode else 'passed'
  44. keyval['returncode'] = returncode
  45. keyval['test_file_authors'] = test_file_authors
  46. with open(filename, 'w') as keyval_file:
  47. keyval_file.write(keyvalue_to_text(keyval))
  48. return keyval
  49. class GrassTestFilesInvoker(object):
  50. """A class used to invoke test files and create the main report"""
  51. # TODO: it is not clear what clean_outputs mean, if should be split
  52. # std stream, random outputs, saved results, profiling
  53. # not stdout and stderr if they contain test results
  54. # we can also save only failed tests, or generate only if assert fails
  55. def __init__(self, start_dir,
  56. clean_mapsets=True, clean_outputs=True, clean_before=True,
  57. testsuite_dir='testsuite', file_anonymizer=None):
  58. """
  59. :param bool clean_mapsets: if the mapsets should be removed
  60. :param bool clean_outputs: meaning is unclear: random tests outputs,
  61. saved images from maps, profiling?
  62. :param bool clean_before: if mapsets, outputs, and results
  63. should be removed before the tests start
  64. (advantageous when the previous run left everything behind)
  65. """
  66. self.start_dir = start_dir
  67. self.clean_mapsets = clean_mapsets
  68. self.clean_outputs = clean_outputs
  69. self.clean_before = clean_before
  70. self.testsuite_dir = testsuite_dir # TODO: solve distribution of this constant
  71. # reporter is created for each call of run_in_location()
  72. self.reporter = None
  73. self.testsuite_dirs = None
  74. if file_anonymizer is None:
  75. self._file_anonymizer = NoopFileAnonymizer()
  76. else:
  77. self._file_anonymizer = file_anonymizer
  78. def _create_mapset(self, gisdbase, location, module):
  79. """Create mapset according to informations in module.
  80. :param loader.GrassTestPythonModule module:
  81. """
  82. # using path.sep but also / and \ for cases when it is confused
  83. # (namely the case of Unix path on MS Windows)
  84. # replace . to get rid of unclean path
  85. # TODO: clean paths
  86. # note that backslash cannot be at the end of raw string
  87. dir_as_name = module.tested_dir.translate(string.maketrans(r'/\.', '___'))
  88. mapset = dir_as_name + '_' + module.name
  89. # TODO: use grass module to do this? but we are not in the right gisdbase
  90. mapset_dir = os.path.join(gisdbase, location, mapset)
  91. if self.clean_before:
  92. silent_rmtree(mapset_dir)
  93. os.mkdir(mapset_dir)
  94. # TODO: default region in mapset will be what?
  95. # copy WIND file from PERMANENT
  96. # TODO: this should be a function in grass.script (used also in gis_set.py, PyGRASS also has its way with Mapset)
  97. # TODO: are premisions an issue here?
  98. shutil.copy(os.path.join(gisdbase, location, 'PERMANENT', 'WIND'),
  99. os.path.join(mapset_dir))
  100. return mapset, mapset_dir
  101. def _run_test_module(self, module, results_dir, gisdbase, location):
  102. """Run one test file."""
  103. self.testsuite_dirs[module.tested_dir].append(module.name)
  104. cwd = os.path.join(results_dir, module.tested_dir, module.name)
  105. data_dir = os.path.join(module.file_dir, 'data')
  106. if os.path.exists(data_dir):
  107. # TODO: link dir instead of copy tree and remove link afterwads
  108. # (removing is good because of testsuite dir in samplecode)
  109. # TODO: use different dir name in samplecode and test if it works
  110. shutil.copytree(data_dir, os.path.join(cwd, 'data'),
  111. ignore=shutil.ignore_patterns('*.svn*'))
  112. ensure_dir(os.path.abspath(cwd))
  113. # TODO: put this to constructor and copy here again
  114. env = os.environ.copy()
  115. mapset, mapset_dir = self._create_mapset(gisdbase, location, module)
  116. gisrc = gsetup.write_gisrc(gisdbase, location, mapset)
  117. env['GISRC'] = gisrc
  118. stdout_path = os.path.join(cwd, 'stdout.txt')
  119. stderr_path = os.path.join(cwd, 'stderr.txt')
  120. stdout = open(stdout_path, 'w')
  121. stderr = open(stderr_path, 'w')
  122. self.reporter.start_file_test(module)
  123. # TODO: we might clean the directory here before test if non-empty
  124. # TODO: use some grass function to run?
  125. # add also '-Qwarn'?
  126. p = subprocess.Popen([sys.executable, '-tt', '-3',
  127. module.abs_file_path],
  128. cwd=cwd, env=env,
  129. stdout=stdout, stderr=stderr)
  130. returncode = p.wait()
  131. stdout.close()
  132. stderr.close()
  133. self._file_anonymizer.anonymize([stdout_path, stderr_path])
  134. test_summary = update_keyval_file(
  135. os.path.join(cwd, 'test_keyvalue_result.txt'),
  136. module=module, returncode=returncode)
  137. self.reporter.end_file_test(module=module, cwd=cwd,
  138. returncode=returncode,
  139. stdout=stdout_path, stderr=stderr_path,
  140. test_summary=test_summary)
  141. # TODO: add some try-except or with for better error handling
  142. os.remove(gisrc)
  143. # TODO: only if clean up
  144. if self.clean_mapsets:
  145. shutil.rmtree(mapset_dir)
  146. def run_in_location(self, gisdbase, location, location_shortcut,
  147. results_dir):
  148. """Run tests in a given location"""
  149. if os.path.abspath(results_dir) == os.path.abspath(self.start_dir):
  150. raise RuntimeError("Results root directory should not be the same"
  151. " as discovery start directory")
  152. self.reporter = GrassTestFilesMultiReporter(
  153. reporters=[
  154. GrassTestFilesTextReporter(stream=sys.stderr),
  155. GrassTestFilesHtmlReporter(
  156. file_anonymizer=self._file_anonymizer),
  157. GrassTestFilesKeyValueReporter()
  158. ])
  159. self.testsuite_dirs = collections.defaultdict(list) # reset list of dirs each time
  160. # TODO: move constants out of loader class or even module
  161. modules = discover_modules(start_dir=self.start_dir,
  162. grass_location=location_shortcut,
  163. file_pattern=GrassTestLoader.files_in_testsuite,
  164. skip_dirs=GrassTestLoader.skip_dirs,
  165. testsuite_dir=GrassTestLoader.testsuite_dir,
  166. all_locations_value=GrassTestLoader.all_tests_value,
  167. universal_location_value=GrassTestLoader.universal_tests_value,
  168. import_modules=False)
  169. self.reporter.start(results_dir)
  170. for module in modules:
  171. self._run_test_module(module=module, results_dir=results_dir,
  172. gisdbase=gisdbase, location=location)
  173. testsuite_dir_reporter = TestsuiteDirReporter(
  174. main_page_name='testsuites.html')
  175. testsuite_dir_reporter.report_for_dirs(root=results_dir,
  176. directories=self.testsuite_dirs)
  177. self.reporter.finish()