loader.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # -*- coding: utf-8 -*-
  2. """GRASS Python testing framework test loading functionality
  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 fnmatch
  11. import unittest
  12. import collections
  13. import re
  14. # TODO: resolve test file versus test module
  15. GrassTestPythonModule = collections.namedtuple('GrassTestPythonModule',
  16. ['name', 'module',
  17. 'file_type',
  18. 'tested_dir',
  19. 'file_dir',
  20. 'abs_file_path'])
  21. # TODO: implement loading without the import
  22. def discover_modules(start_dir, skip_dirs, testsuite_dir,
  23. grass_location,
  24. all_locations_value, universal_location_value,
  25. import_modules, add_failed_imports=True,
  26. file_pattern=None, file_regexp=None):
  27. """Find all test files (modules) in a directory tree.
  28. The function is designed specifically for GRASS testing framework
  29. test layout. It expects some directories to have a "testsuite"
  30. directory where test files (test modules) are present.
  31. Additionally, it also handles loading of test files which specify
  32. in which location they can run.
  33. :param start_dir: directory to start the search
  34. :param file_pattern: pattern of files in a test suite directory
  35. (using Unix shell-style wildcards)
  36. :param skip_dirs: directories not to recurse to (e.g. ``.svn``)
  37. :param testsuite_dir: name of directory where the test files are found,
  38. the function will not recurse to this directory
  39. :param grass_location: string with an accepted location type (category, shortcut)
  40. :param all_locations_value: string used to say that all locations
  41. should be loaded (grass_location can be set to this value)
  42. :param universal_location_value: string marking a test as
  43. location-independent (same as not providing any)
  44. :param import_modules: True if files should be imported as modules,
  45. False if the files should be just searched for the needed values
  46. :returns: a list of GrassTestPythonModule objects
  47. .. todo::
  48. Implement import_modules.
  49. """
  50. modules = []
  51. for root, dirs, files in os.walk(start_dir):
  52. for dir_pattern in skip_dirs:
  53. to_skip = fnmatch.filter(dirs, dir_pattern)
  54. for skip in to_skip:
  55. dirs.remove(skip)
  56. if testsuite_dir in dirs:
  57. dirs.remove(testsuite_dir) # do not recurse to testsuite
  58. full = os.path.join(root, testsuite_dir)
  59. all_files = os.listdir(full)
  60. if file_pattern:
  61. files = fnmatch.filter(all_files, file_pattern)
  62. if file_regexp:
  63. files = [f for f in all_files if re.match(file_regexp, f)]
  64. # get test/module name without .py
  65. # extecting all files to end with .py
  66. # this will not work for invoking bat files but it works fine
  67. # as long as we handle only Python files (and using Python
  68. # interpreter for invoking)
  69. # TODO: warning about no tests in a testsuite
  70. # (in what way?)
  71. for file_name in files:
  72. # TODO: add also import if requested
  73. # (see older versions of this file)
  74. # TODO: check if there is some main in .py
  75. # otherwise we can have successful test just because
  76. # everything was loaded into Python
  77. # TODO: check if there is set -e or exit !0 or ?
  78. # otherwise we can have successful because nothing was reported
  79. abspath = os.path.abspath(full)
  80. abs_file_path = os.path.join(abspath, file_name)
  81. if file_name.endswith('.py'):
  82. if file_name == '__init__.py':
  83. # we always ignore __init__.py
  84. continue
  85. file_type = 'py'
  86. name = file_name[:-3]
  87. elif file_name.endswith('.sh'):
  88. file_type = 'sh'
  89. name = file_name[:-3]
  90. else:
  91. file_type = None # alternative would be '', now equivalent
  92. name = file_name
  93. add = False
  94. try:
  95. if grass_location == all_locations_value:
  96. add = True
  97. else:
  98. try:
  99. locations = ['nc', 'stdmaps', 'all']
  100. except AttributeError:
  101. add = True # test is universal
  102. else:
  103. if universal_location_value in locations:
  104. add = True # cases when it is explicit
  105. if grass_location in locations:
  106. add = True # standard case with given location
  107. if not locations:
  108. add = True # count not specified as universal
  109. except ImportError as e:
  110. if add_failed_imports:
  111. add = True
  112. else:
  113. raise ImportError('Cannot import module named'
  114. ' %s in %s (%s)'
  115. % (name, full, e.message))
  116. # alternative is to create TestClass which will raise
  117. # see unittest.loader
  118. if add:
  119. modules.append(GrassTestPythonModule(
  120. name=name, module=None, tested_dir=root, file_dir=full,
  121. abs_file_path=abs_file_path, file_type=file_type))
  122. # in else with some verbose we could tell about skipped test
  123. return modules
  124. # TODO: find out if this is useful for us in some way
  125. # we are now using only discover_modules directly
  126. class GrassTestLoader(unittest.TestLoader):
  127. """Class handles GRASS-specific loading of test modules."""
  128. skip_dirs = ['.svn', 'dist.*', 'bin.*', 'OBJ.*']
  129. testsuite_dir = 'testsuite'
  130. files_in_testsuite = '*.py'
  131. all_tests_value = 'all'
  132. universal_tests_value = 'universal'
  133. def __init__(self, grass_location):
  134. self.grass_location = grass_location
  135. # TODO: what is the purpose of top_level_dir, can it be useful?
  136. # probably yes, we need to know grass src or dist root
  137. # TODO: not using pattern here
  138. def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
  139. """Load test modules from in GRASS testing framework way."""
  140. modules = discover_modules(start_dir=start_dir,
  141. file_pattern=self.files_in_testsuite,
  142. skip_dirs=self.skip_dirs,
  143. testsuite_dir=self.testsuite_dir,
  144. grass_location=self.grass_location,
  145. all_locations_value=self.all_tests_value,
  146. universal_location_value=self.universal_tests_value,
  147. import_modules=True)
  148. tests = []
  149. for module in modules:
  150. tests.append(self.loadTestsFromModule(module.module))
  151. return self.suiteClass(tests)
  152. if __name__ == '__main__':
  153. GrassTestLoader().discover()