main.py 7.0 KB

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