loader.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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, unused_files in os.walk(start_dir, topdown=True):
  52. dirs.sort()
  53. for dir_pattern in skip_dirs:
  54. to_skip = fnmatch.filter(dirs, dir_pattern)
  55. for skip in to_skip:
  56. dirs.remove(skip)
  57. if testsuite_dir in dirs:
  58. dirs.remove(testsuite_dir) # do not recurse to testsuite
  59. full = os.path.join(root, testsuite_dir)
  60. all_files = os.listdir(full)
  61. if file_pattern:
  62. files = fnmatch.filter(all_files, file_pattern)
  63. if file_regexp:
  64. files = [f for f in all_files if re.match(file_regexp, f)]
  65. files = sorted(files)
  66. # get test/module name without .py
  67. # extpecting all files to end with .py
  68. # this will not work for invoking bat files but it works fine
  69. # as long as we handle only Python files (and using Python
  70. # interpreter for invoking)
  71. # TODO: warning about no tests in a testsuite
  72. # (in what way?)
  73. for file_name in files:
  74. # TODO: add also import if requested
  75. # (see older versions of this file)
  76. # TODO: check if there is some main in .py
  77. # otherwise we can have successful test just because
  78. # everything was loaded into Python
  79. # TODO: check if there is set -e or exit !0 or ?
  80. # otherwise we can have successful because nothing was reported
  81. abspath = os.path.abspath(full)
  82. abs_file_path = os.path.join(abspath, file_name)
  83. if file_name.endswith('.py'):
  84. if file_name == '__init__.py':
  85. # we always ignore __init__.py
  86. continue
  87. file_type = 'py'
  88. name = file_name[:-3]
  89. elif file_name.endswith('.sh'):
  90. file_type = 'sh'
  91. name = file_name[:-3]
  92. else:
  93. file_type = None # alternative would be '', now equivalent
  94. name = file_name
  95. add = False
  96. try:
  97. if grass_location == all_locations_value:
  98. add = True
  99. else:
  100. try:
  101. locations = ['nc', 'stdmaps', 'all']
  102. except AttributeError:
  103. add = True # test is universal
  104. else:
  105. if universal_location_value in locations:
  106. add = True # cases when it is explicit
  107. if grass_location in locations:
  108. add = True # standard case with given location
  109. if not locations:
  110. add = True # count not specified as universal
  111. except ImportError as e:
  112. if add_failed_imports:
  113. add = True
  114. else:
  115. raise ImportError('Cannot import module named'
  116. ' %s in %s (%s)'
  117. % (name, full, e.message))
  118. # alternative is to create TestClass which will raise
  119. # see unittest.loader
  120. if add:
  121. modules.append(GrassTestPythonModule(
  122. name=name, module=None, tested_dir=root, file_dir=full,
  123. abs_file_path=abs_file_path, file_type=file_type))
  124. # in else with some verbose we could tell about skipped test
  125. return modules
  126. # TODO: find out if this is useful for us in some way
  127. # we are now using only discover_modules directly
  128. class GrassTestLoader(unittest.TestLoader):
  129. """Class handles GRASS-specific loading of test modules."""
  130. skip_dirs = ['.svn', 'dist.*', 'bin.*', 'OBJ.*']
  131. testsuite_dir = 'testsuite'
  132. files_in_testsuite = '*.py'
  133. all_tests_value = 'all'
  134. universal_tests_value = 'universal'
  135. def __init__(self, grass_location):
  136. self.grass_location = grass_location
  137. # TODO: what is the purpose of top_level_dir, can it be useful?
  138. # probably yes, we need to know grass src or dist root
  139. # TODO: not using pattern here
  140. def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
  141. """Load test modules from in GRASS testing framework way."""
  142. modules = discover_modules(start_dir=start_dir,
  143. file_pattern=self.files_in_testsuite,
  144. skip_dirs=self.skip_dirs,
  145. testsuite_dir=self.testsuite_dir,
  146. grass_location=self.grass_location,
  147. all_locations_value=self.all_tests_value,
  148. universal_location_value=self.universal_tests_value,
  149. import_modules=True)
  150. tests = []
  151. for module in modules:
  152. tests.append(self.loadTestsFromModule(module.module))
  153. return self.suiteClass(tests)
  154. if __name__ == '__main__':
  155. GrassTestLoader().discover()