main.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. """
  2. GRASS Python testing framework module for running from command line
  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 argparse
  12. import configparser
  13. from pathlib import Path
  14. from unittest.main import TestProgram
  15. from .loader import GrassTestLoader
  16. from .runner import GrassTestRunner, MultiTestResult, TextTestResult, KeyValueTestResult
  17. from .invoker import GrassTestFilesInvoker
  18. from .utils import silent_rmtree
  19. from .reporters import FileAnonymizer
  20. import grass.script.core as gcore
  21. class GrassTestProgram(TestProgram):
  22. """A class to be used by individual test files (wrapped in the function)"""
  23. def __init__(
  24. self,
  25. exit_at_end,
  26. grass_location,
  27. clean_outputs=True,
  28. unittest_argv=None,
  29. module=None,
  30. verbosity=1,
  31. failfast=None,
  32. catchbreak=None,
  33. ):
  34. """Prepares the tests in GRASS way and then runs the tests.
  35. :param bool clean_outputs: if outputs in mapset and in ?
  36. """
  37. self.test = None
  38. self.grass_location = grass_location
  39. # it is unclear what the exact behavior is in unittest
  40. # buffer stdout and stderr during tests
  41. buffer_stdout_stderr = False
  42. grass_loader = GrassTestLoader(grass_location=self.grass_location)
  43. text_result = TextTestResult(
  44. stream=sys.stderr, descriptions=True, verbosity=verbosity
  45. )
  46. keyval_file = open("test_keyvalue_result.txt", "w")
  47. keyval_result = KeyValueTestResult(stream=keyval_file)
  48. result = MultiTestResult(results=[text_result, keyval_result])
  49. grass_runner = GrassTestRunner(
  50. verbosity=verbosity,
  51. failfast=failfast,
  52. buffer=buffer_stdout_stderr,
  53. result=result,
  54. )
  55. super(GrassTestProgram, self).__init__(
  56. module=module,
  57. argv=unittest_argv,
  58. testLoader=grass_loader,
  59. testRunner=grass_runner,
  60. exit=exit_at_end,
  61. verbosity=verbosity,
  62. failfast=failfast,
  63. catchbreak=catchbreak,
  64. buffer=buffer_stdout_stderr,
  65. )
  66. keyval_file.close()
  67. def test():
  68. """Run a test of a module."""
  69. # TODO: put the link to to the report only if available
  70. # TODO: how to disable Python code coverage for module and C tests?
  71. # TODO: we probably need to have different test functions for C, Python modules, and Python code
  72. # TODO: combine the results using python -m coverage --help | grep combine
  73. # TODO: function to anonymize/beautify file names (in content and actual filenames)
  74. # TODO: implement coverage but only when requested by invoker and only if
  75. # it makes sense for tests (need to know what is tested)
  76. # doing_coverage = False
  77. # try:
  78. # import coverage
  79. # doing_coverage = True
  80. # cov = coverage.coverage(omit="*testsuite*")
  81. # cov.start()
  82. # except ImportError:
  83. # pass
  84. # TODO: add some message somewhere
  85. # TODO: enable passing omit to exclude also gunittest or nothing
  86. program = GrassTestProgram(
  87. module="__main__", exit_at_end=False, grass_location="all"
  88. )
  89. # TODO: check if we are in the directory where the test file is
  90. # this will ensure that data directory is available when it is requested
  91. # if doing_coverage:
  92. # cov.stop()
  93. # cov.html_report(directory='testcodecoverage')
  94. # TODO: is sys.exit the right thing here
  95. sys.exit(not program.result.wasSuccessful())
  96. def discovery():
  97. """Recursively find all tests in testsuite directories and run them
  98. Everything is imported and runs in this process.
  99. Runs using::
  100. python main.py discovery [start_directory]
  101. """
  102. program = GrassTestProgram(grass_location="nc", exit_at_end=False)
  103. sys.exit(not program.result.wasSuccessful())
  104. CONFIG_FILENAME = ".gunittest.cfg"
  105. def get_config(start_directory):
  106. """Read configuration if available, return empty dict if not"""
  107. config_parser = configparser.ConfigParser()
  108. config_file = Path(start_directory) / CONFIG_FILENAME
  109. if config_file.is_file():
  110. config_parser.read(config_file)
  111. if "gunittest" in config_parser:
  112. return config_parser["gunittest"]
  113. return {}
  114. def main():
  115. parser = argparse.ArgumentParser(
  116. description="Run test files in all testsuite directories starting"
  117. " from the current one"
  118. " (runs on active GRASS session)"
  119. )
  120. parser.add_argument(
  121. "--location",
  122. dest="location",
  123. action="store",
  124. help="Name of location where to perform test",
  125. required=True,
  126. )
  127. parser.add_argument(
  128. "--location-type",
  129. dest="location_type",
  130. action="store",
  131. default="nc",
  132. help="Type of tests which should be run" " (tag corresponding to location)",
  133. )
  134. parser.add_argument(
  135. "--grassdata",
  136. dest="gisdbase",
  137. action="store",
  138. default=None,
  139. help="GRASS data(base) (GISDBASE) directory" " (current GISDBASE by default)",
  140. )
  141. parser.add_argument(
  142. "--output",
  143. dest="output",
  144. action="store",
  145. default="testreport",
  146. help="Output directory",
  147. )
  148. parser.add_argument(
  149. "--min-success",
  150. dest="min_success",
  151. action="store",
  152. default="100",
  153. type=int,
  154. help=(
  155. "Minimum success percentage (lower percentage"
  156. " than this will result in a non-zero return code; values 0-100)"
  157. ),
  158. )
  159. args = parser.parse_args()
  160. gisdbase = args.gisdbase
  161. if gisdbase is None:
  162. # here we already rely on being in GRASS session
  163. gisdbase = gcore.gisenv()["GISDBASE"]
  164. location = args.location
  165. location_type = args.location_type
  166. if not gisdbase:
  167. sys.stderr.write(
  168. "GISDBASE (grassdata directory)" " cannot be empty string\n" % gisdbase
  169. )
  170. sys.exit(1)
  171. if not os.path.exists(gisdbase):
  172. sys.stderr.write(
  173. "GISDBASE (grassdata directory) <%s>" " does not exist\n" % gisdbase
  174. )
  175. sys.exit(1)
  176. if not os.path.exists(os.path.join(gisdbase, location)):
  177. sys.stderr.write(
  178. "GRASS Location <{loc}>"
  179. " does not exist in GRASS Database <{db}>\n".format(
  180. loc=location, db=gisdbase
  181. )
  182. )
  183. sys.exit(1)
  184. results_dir = args.output
  185. silent_rmtree(results_dir) # TODO: too brute force?
  186. start_dir = "."
  187. abs_start_dir = os.path.abspath(start_dir)
  188. config = get_config(start_dir)
  189. invoker = GrassTestFilesInvoker(
  190. start_dir=start_dir,
  191. file_anonymizer=FileAnonymizer(paths_to_remove=[abs_start_dir]),
  192. )
  193. # TODO: remove also results dir from files
  194. # as an enhancemnt
  195. # we can just iterate over all locations available in database
  196. # but the we don't know the right location type (category, label, shortcut)
  197. reporter = invoker.run_in_location(
  198. gisdbase=gisdbase,
  199. location=location,
  200. location_type=location_type,
  201. results_dir=results_dir,
  202. exclude=config.get("exclude", "").split(),
  203. )
  204. if not reporter.test_files:
  205. return "No tests found or executed"
  206. if reporter.file_pass_per >= args.min_success:
  207. return 0
  208. return 1
  209. if __name__ == "__main__":
  210. sys.exit(main())