loader.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.gunittest.loader
  3. @brief GRASS Python testing framework test loading functionality
  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 fnmatch
  13. import unittest
  14. import collections
  15. import importlib
  16. # TODO: resolve test file versus test module
  17. GrassTestPythonModule = collections.namedtuple('GrassTestPythonModule',
  18. ['name', 'module',
  19. 'tested_dir',
  20. 'file_dir',
  21. 'abs_file_path'])
  22. # TODO: implement loading without the import
  23. def discover_modules(start_dir, file_pattern, skip_dirs, testsuite_dir,
  24. grass_location,
  25. all_locations_value, universal_location_value,
  26. import_modules, add_failed_imports=True):
  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. files = fnmatch.filter(os.listdir(full), file_pattern)
  60. # get test/module name without .py
  61. # extecting all files to end with .py
  62. # this will not work for invoking bat files but it works fine
  63. # as long as we handle only Python files (and using Python
  64. # interpreter for invoking)
  65. # we always ignore __init__.py
  66. module_names = [f[:-3] for f in files if not f == '__init__.py']
  67. # TODO: warning (in what way?) about no tests in testsuite
  68. for name in module_names:
  69. # TODO: rewrite to use import_module and search the file if not
  70. # TODO: do it without importing
  71. # TODO: check if there is some main
  72. # otherwise we can have successful test just because
  73. # everything was loaded into Python
  74. abspath = os.path.abspath(full)
  75. sys.path.insert(0, abspath)
  76. add = False
  77. try:
  78. m = importlib.import_module(name)
  79. # TODO: now we are always importing but also always setting module to None
  80. if grass_location == all_locations_value:
  81. add = True
  82. else:
  83. try:
  84. locations = m.LOCATIONS
  85. except AttributeError:
  86. add = True # test is universal
  87. else:
  88. if universal_location_value in locations:
  89. add = True # cases when it is explicit
  90. if grass_location in locations:
  91. add = True # standard case with given location
  92. except ImportError as e:
  93. if add_failed_imports:
  94. add = True
  95. else:
  96. raise ImportError('Cannot import module named'
  97. ' %s in %s (%s)'
  98. % (name, full, e.message))
  99. # alternative is to create TestClass which will raise
  100. # see unittest.loader
  101. if add:
  102. modules.append(GrassTestPythonModule(
  103. name=name, module=None, tested_dir=root, file_dir=full,
  104. abs_file_path=os.path.join(abspath, name + '.py')))
  105. # in else with some verbose we could tell about skiped test
  106. return modules
  107. # TODO: find out if this is useful for us in some way
  108. # we are now using only discover_modules directly
  109. class GrassTestLoader(unittest.TestLoader):
  110. """Class handles GRASS-specific loading of test modules."""
  111. skip_dirs = ['.svn', 'dist.*', 'bin.*', 'OBJ.*']
  112. testsuite_dir = 'testsuite'
  113. files_in_testsuite = '*.py'
  114. all_tests_value = 'all'
  115. universal_tests_value = 'universal'
  116. def __init__(self, grass_location):
  117. self.grass_location = grass_location
  118. # TODO: what is the purpose of top_level_dir, can it be useful?
  119. # probably yes, we need to know grass src or dist root
  120. # TODO: not using pattern here
  121. def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
  122. """Load test modules from in GRASS testing framework way."""
  123. modules = discover_modules(start_dir=start_dir,
  124. file_pattern=self.files_in_testsuite,
  125. skip_dirs=self.skip_dirs,
  126. testsuite_dir=self.testsuite_dir,
  127. grass_location=self.grass_location,
  128. all_locations_value=self.all_tests_value,
  129. universal_location_value=self.universal_tests_value,
  130. import_modules=True)
  131. tests = []
  132. for module in modules:
  133. tests.append(self.loadTestsFromModule(module.module))
  134. return self.suiteClass(tests)
  135. if __name__ == '__main__':
  136. GrassTestLoader().discover()