Debian Codegraph @

src/python/grpcio_tests/tests/_loader.py

raw
1 # Copyright 2015 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from __future__ import absolute_import
16
17 import importlib
18 import os
19 import pkgutil
20 import re
21 import sys
22 import unittest
23
24 import coverage
25
26 TEST_MODULE_REGEX = r'^.*_test$'
27
28
29 # Determines the path og a given path relative to the first matching
30 # path on sys.path. Useful for determining what a directory's module
31 # path will be.
32 def _relativize_to_sys_path(path):
33 for sys_path in sys.path:
34 if path.startswith(sys_path):
35 relative = path[len(sys_path):]
36 if not relative:
37 return ""
38 if relative.startswith(os.path.sep):
39 relative = relative[len(os.path.sep):]
40 if not relative.endswith(os.path.sep):
41 relative += os.path.sep
42 return relative
43 raise AssertionError("Failed to relativize {} to sys.path.".format(path))
44
45
46 def _relative_path_to_module_prefix(path):
47 return path.replace(os.path.sep, ".")
48
49
50 class Loader(object):
51 """Test loader for setuptools test suite support.
52
53 Attributes:
54 suite (unittest.TestSuite): All tests collected by the loader.
55 loader (unittest.TestLoader): Standard Python unittest loader to be ran per
56 module discovered.
57 module_matcher (re.RegexObject): A regular expression object to match
58 against module names and determine whether or not the discovered module
59 contributes to the test suite.
60 """
61
62 def __init__(self):
63 self.suite = unittest.TestSuite()
64 self.loader = unittest.TestLoader()
65 self.module_matcher = re.compile(TEST_MODULE_REGEX)
66
67 def loadTestsFromNames(self, names, module=None):
68 """Function mirroring TestLoader::loadTestsFromNames, as expected by
69 setuptools.setup argument `test_loader`."""
70 # ensure that we capture decorators and definitions (else our coverage
71 # measure unnecessarily suffers)
72 coverage_context = coverage.Coverage(data_suffix=True)
73 coverage_context.start()
74 imported_modules = tuple(
75 importlib.import_module(name) for name in names)
76 for imported_module in imported_modules:
77 self.visit_module(imported_module)
78 for imported_module in imported_modules:
79 try:
80 package_paths = imported_module.__path__
81 except AttributeError:
82 continue
83 self.walk_packages(package_paths)
84 coverage_context.stop()
85 coverage_context.save()
86 return self.suite
87
88 def walk_packages(self, package_paths):
89 """Walks over the packages, dispatching `visit_module` calls.
90
91 Args:
92 package_paths (list): A list of paths over which to walk through modules
93 along.
94 """
95 for path in package_paths:
96 self._walk_package(path)
97
98 def _walk_package(self, package_path):
99 prefix = _relative_path_to_module_prefix(
100 _relativize_to_sys_path(package_path))
101 for importer, module_name, is_package in (pkgutil.walk_packages(
102 [package_path], prefix)):
103 found_module = importer.find_module(module_name)
104 module = None
105 if module_name in sys.modules:
106 module = sys.modules[module_name]
107 else:
108 module = found_module.load_module(module_name)
109 self.visit_module(module)
110
111 def visit_module(self, module):
112 """Visits the module, adding discovered tests to the test suite.
113
114 Args:
115 module (module): Module to match against self.module_matcher; if matched
116 it has its tests loaded via self.loader into self.suite.
117 """
118 if self.module_matcher.match(module.__name__):
119 module_suite = self.loader.loadTestsFromModule(module)
120 self.suite.addTest(module_suite)
121
122
123 def iterate_suite_cases(suite):
124 """Generator over all unittest.TestCases in a unittest.TestSuite.
125
126 Args:
127 suite (unittest.TestSuite): Suite to iterate over in the generator.
128
129 Returns:
130 generator: A generator over all unittest.TestCases in `suite`.
131 """
132 for item in suite:
133 if isinstance(item, unittest.TestSuite):
134 for child_item in iterate_suite_cases(item):
135 yield child_item
136 elif isinstance(item, unittest.TestCase):
137 yield item
138 else:
139 raise ValueError('unexpected suite item of type {}'.format(
140 type(item)))