main.py 6.9 KB

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