main.py 6.8 KB

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