| 1 | n/a | """Loading unittests.""" |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | import os |
|---|
| 4 | n/a | import re |
|---|
| 5 | n/a | import sys |
|---|
| 6 | n/a | import traceback |
|---|
| 7 | n/a | import types |
|---|
| 8 | n/a | import functools |
|---|
| 9 | n/a | import warnings |
|---|
| 10 | n/a | |
|---|
| 11 | n/a | from fnmatch import fnmatch |
|---|
| 12 | n/a | |
|---|
| 13 | n/a | from . import case, suite, util |
|---|
| 14 | n/a | |
|---|
| 15 | n/a | __unittest = True |
|---|
| 16 | n/a | |
|---|
| 17 | n/a | # what about .pyc (etc) |
|---|
| 18 | n/a | # we would need to avoid loading the same tests multiple times |
|---|
| 19 | n/a | # from '.py', *and* '.pyc' |
|---|
| 20 | n/a | VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE) |
|---|
| 21 | n/a | |
|---|
| 22 | n/a | |
|---|
| 23 | n/a | class _FailedTest(case.TestCase): |
|---|
| 24 | n/a | _testMethodName = None |
|---|
| 25 | n/a | |
|---|
| 26 | n/a | def __init__(self, method_name, exception): |
|---|
| 27 | n/a | self._exception = exception |
|---|
| 28 | n/a | super(_FailedTest, self).__init__(method_name) |
|---|
| 29 | n/a | |
|---|
| 30 | n/a | def __getattr__(self, name): |
|---|
| 31 | n/a | if name != self._testMethodName: |
|---|
| 32 | n/a | return super(_FailedTest, self).__getattr__(name) |
|---|
| 33 | n/a | def testFailure(): |
|---|
| 34 | n/a | raise self._exception |
|---|
| 35 | n/a | return testFailure |
|---|
| 36 | n/a | |
|---|
| 37 | n/a | |
|---|
| 38 | n/a | def _make_failed_import_test(name, suiteClass): |
|---|
| 39 | n/a | message = 'Failed to import test module: %s\n%s' % ( |
|---|
| 40 | n/a | name, traceback.format_exc()) |
|---|
| 41 | n/a | return _make_failed_test(name, ImportError(message), suiteClass, message) |
|---|
| 42 | n/a | |
|---|
| 43 | n/a | def _make_failed_load_tests(name, exception, suiteClass): |
|---|
| 44 | n/a | message = 'Failed to call load_tests:\n%s' % (traceback.format_exc(),) |
|---|
| 45 | n/a | return _make_failed_test( |
|---|
| 46 | n/a | name, exception, suiteClass, message) |
|---|
| 47 | n/a | |
|---|
| 48 | n/a | def _make_failed_test(methodname, exception, suiteClass, message): |
|---|
| 49 | n/a | test = _FailedTest(methodname, exception) |
|---|
| 50 | n/a | return suiteClass((test,)), message |
|---|
| 51 | n/a | |
|---|
| 52 | n/a | def _make_skipped_test(methodname, exception, suiteClass): |
|---|
| 53 | n/a | @case.skip(str(exception)) |
|---|
| 54 | n/a | def testSkipped(self): |
|---|
| 55 | n/a | pass |
|---|
| 56 | n/a | attrs = {methodname: testSkipped} |
|---|
| 57 | n/a | TestClass = type("ModuleSkipped", (case.TestCase,), attrs) |
|---|
| 58 | n/a | return suiteClass((TestClass(methodname),)) |
|---|
| 59 | n/a | |
|---|
| 60 | n/a | def _jython_aware_splitext(path): |
|---|
| 61 | n/a | if path.lower().endswith('$py.class'): |
|---|
| 62 | n/a | return path[:-9] |
|---|
| 63 | n/a | return os.path.splitext(path)[0] |
|---|
| 64 | n/a | |
|---|
| 65 | n/a | |
|---|
| 66 | n/a | class TestLoader(object): |
|---|
| 67 | n/a | """ |
|---|
| 68 | n/a | This class is responsible for loading tests according to various criteria |
|---|
| 69 | n/a | and returning them wrapped in a TestSuite |
|---|
| 70 | n/a | """ |
|---|
| 71 | n/a | testMethodPrefix = 'test' |
|---|
| 72 | n/a | sortTestMethodsUsing = staticmethod(util.three_way_cmp) |
|---|
| 73 | n/a | suiteClass = suite.TestSuite |
|---|
| 74 | n/a | _top_level_dir = None |
|---|
| 75 | n/a | |
|---|
| 76 | n/a | def __init__(self): |
|---|
| 77 | n/a | super(TestLoader, self).__init__() |
|---|
| 78 | n/a | self.errors = [] |
|---|
| 79 | n/a | # Tracks packages which we have called into via load_tests, to |
|---|
| 80 | n/a | # avoid infinite re-entrancy. |
|---|
| 81 | n/a | self._loading_packages = set() |
|---|
| 82 | n/a | |
|---|
| 83 | n/a | def loadTestsFromTestCase(self, testCaseClass): |
|---|
| 84 | n/a | """Return a suite of all test cases contained in testCaseClass""" |
|---|
| 85 | n/a | if issubclass(testCaseClass, suite.TestSuite): |
|---|
| 86 | n/a | raise TypeError("Test cases should not be derived from " |
|---|
| 87 | n/a | "TestSuite. Maybe you meant to derive from " |
|---|
| 88 | n/a | "TestCase?") |
|---|
| 89 | n/a | testCaseNames = self.getTestCaseNames(testCaseClass) |
|---|
| 90 | n/a | if not testCaseNames and hasattr(testCaseClass, 'runTest'): |
|---|
| 91 | n/a | testCaseNames = ['runTest'] |
|---|
| 92 | n/a | loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) |
|---|
| 93 | n/a | return loaded_suite |
|---|
| 94 | n/a | |
|---|
| 95 | n/a | # XXX After Python 3.5, remove backward compatibility hacks for |
|---|
| 96 | n/a | # use_load_tests deprecation via *args and **kws. See issue 16662. |
|---|
| 97 | n/a | def loadTestsFromModule(self, module, *args, pattern=None, **kws): |
|---|
| 98 | n/a | """Return a suite of all test cases contained in the given module""" |
|---|
| 99 | n/a | # This method used to take an undocumented and unofficial |
|---|
| 100 | n/a | # use_load_tests argument. For backward compatibility, we still |
|---|
| 101 | n/a | # accept the argument (which can also be the first position) but we |
|---|
| 102 | n/a | # ignore it and issue a deprecation warning if it's present. |
|---|
| 103 | n/a | if len(args) > 0 or 'use_load_tests' in kws: |
|---|
| 104 | n/a | warnings.warn('use_load_tests is deprecated and ignored', |
|---|
| 105 | n/a | DeprecationWarning) |
|---|
| 106 | n/a | kws.pop('use_load_tests', None) |
|---|
| 107 | n/a | if len(args) > 1: |
|---|
| 108 | n/a | # Complain about the number of arguments, but don't forget the |
|---|
| 109 | n/a | # required `module` argument. |
|---|
| 110 | n/a | complaint = len(args) + 1 |
|---|
| 111 | n/a | raise TypeError('loadTestsFromModule() takes 1 positional argument but {} were given'.format(complaint)) |
|---|
| 112 | n/a | if len(kws) != 0: |
|---|
| 113 | n/a | # Since the keyword arguments are unsorted (see PEP 468), just |
|---|
| 114 | n/a | # pick the alphabetically sorted first argument to complain about, |
|---|
| 115 | n/a | # if multiple were given. At least the error message will be |
|---|
| 116 | n/a | # predictable. |
|---|
| 117 | n/a | complaint = sorted(kws)[0] |
|---|
| 118 | n/a | raise TypeError("loadTestsFromModule() got an unexpected keyword argument '{}'".format(complaint)) |
|---|
| 119 | n/a | tests = [] |
|---|
| 120 | n/a | for name in dir(module): |
|---|
| 121 | n/a | obj = getattr(module, name) |
|---|
| 122 | n/a | if isinstance(obj, type) and issubclass(obj, case.TestCase): |
|---|
| 123 | n/a | tests.append(self.loadTestsFromTestCase(obj)) |
|---|
| 124 | n/a | |
|---|
| 125 | n/a | load_tests = getattr(module, 'load_tests', None) |
|---|
| 126 | n/a | tests = self.suiteClass(tests) |
|---|
| 127 | n/a | if load_tests is not None: |
|---|
| 128 | n/a | try: |
|---|
| 129 | n/a | return load_tests(self, tests, pattern) |
|---|
| 130 | n/a | except Exception as e: |
|---|
| 131 | n/a | error_case, error_message = _make_failed_load_tests( |
|---|
| 132 | n/a | module.__name__, e, self.suiteClass) |
|---|
| 133 | n/a | self.errors.append(error_message) |
|---|
| 134 | n/a | return error_case |
|---|
| 135 | n/a | return tests |
|---|
| 136 | n/a | |
|---|
| 137 | n/a | def loadTestsFromName(self, name, module=None): |
|---|
| 138 | n/a | """Return a suite of all test cases given a string specifier. |
|---|
| 139 | n/a | |
|---|
| 140 | n/a | The name may resolve either to a module, a test case class, a |
|---|
| 141 | n/a | test method within a test case class, or a callable object which |
|---|
| 142 | n/a | returns a TestCase or TestSuite instance. |
|---|
| 143 | n/a | |
|---|
| 144 | n/a | The method optionally resolves the names relative to a given module. |
|---|
| 145 | n/a | """ |
|---|
| 146 | n/a | parts = name.split('.') |
|---|
| 147 | n/a | error_case, error_message = None, None |
|---|
| 148 | n/a | if module is None: |
|---|
| 149 | n/a | parts_copy = parts[:] |
|---|
| 150 | n/a | while parts_copy: |
|---|
| 151 | n/a | try: |
|---|
| 152 | n/a | module_name = '.'.join(parts_copy) |
|---|
| 153 | n/a | module = __import__(module_name) |
|---|
| 154 | n/a | break |
|---|
| 155 | n/a | except ImportError: |
|---|
| 156 | n/a | next_attribute = parts_copy.pop() |
|---|
| 157 | n/a | # Last error so we can give it to the user if needed. |
|---|
| 158 | n/a | error_case, error_message = _make_failed_import_test( |
|---|
| 159 | n/a | next_attribute, self.suiteClass) |
|---|
| 160 | n/a | if not parts_copy: |
|---|
| 161 | n/a | # Even the top level import failed: report that error. |
|---|
| 162 | n/a | self.errors.append(error_message) |
|---|
| 163 | n/a | return error_case |
|---|
| 164 | n/a | parts = parts[1:] |
|---|
| 165 | n/a | obj = module |
|---|
| 166 | n/a | for part in parts: |
|---|
| 167 | n/a | try: |
|---|
| 168 | n/a | parent, obj = obj, getattr(obj, part) |
|---|
| 169 | n/a | except AttributeError as e: |
|---|
| 170 | n/a | # We can't traverse some part of the name. |
|---|
| 171 | n/a | if (getattr(obj, '__path__', None) is not None |
|---|
| 172 | n/a | and error_case is not None): |
|---|
| 173 | n/a | # This is a package (no __path__ per importlib docs), and we |
|---|
| 174 | n/a | # encountered an error importing something. We cannot tell |
|---|
| 175 | n/a | # the difference between package.WrongNameTestClass and |
|---|
| 176 | n/a | # package.wrong_module_name so we just report the |
|---|
| 177 | n/a | # ImportError - it is more informative. |
|---|
| 178 | n/a | self.errors.append(error_message) |
|---|
| 179 | n/a | return error_case |
|---|
| 180 | n/a | else: |
|---|
| 181 | n/a | # Otherwise, we signal that an AttributeError has occurred. |
|---|
| 182 | n/a | error_case, error_message = _make_failed_test( |
|---|
| 183 | n/a | part, e, self.suiteClass, |
|---|
| 184 | n/a | 'Failed to access attribute:\n%s' % ( |
|---|
| 185 | n/a | traceback.format_exc(),)) |
|---|
| 186 | n/a | self.errors.append(error_message) |
|---|
| 187 | n/a | return error_case |
|---|
| 188 | n/a | |
|---|
| 189 | n/a | if isinstance(obj, types.ModuleType): |
|---|
| 190 | n/a | return self.loadTestsFromModule(obj) |
|---|
| 191 | n/a | elif isinstance(obj, type) and issubclass(obj, case.TestCase): |
|---|
| 192 | n/a | return self.loadTestsFromTestCase(obj) |
|---|
| 193 | n/a | elif (isinstance(obj, types.FunctionType) and |
|---|
| 194 | n/a | isinstance(parent, type) and |
|---|
| 195 | n/a | issubclass(parent, case.TestCase)): |
|---|
| 196 | n/a | name = parts[-1] |
|---|
| 197 | n/a | inst = parent(name) |
|---|
| 198 | n/a | # static methods follow a different path |
|---|
| 199 | n/a | if not isinstance(getattr(inst, name), types.FunctionType): |
|---|
| 200 | n/a | return self.suiteClass([inst]) |
|---|
| 201 | n/a | elif isinstance(obj, suite.TestSuite): |
|---|
| 202 | n/a | return obj |
|---|
| 203 | n/a | if callable(obj): |
|---|
| 204 | n/a | test = obj() |
|---|
| 205 | n/a | if isinstance(test, suite.TestSuite): |
|---|
| 206 | n/a | return test |
|---|
| 207 | n/a | elif isinstance(test, case.TestCase): |
|---|
| 208 | n/a | return self.suiteClass([test]) |
|---|
| 209 | n/a | else: |
|---|
| 210 | n/a | raise TypeError("calling %s returned %s, not a test" % |
|---|
| 211 | n/a | (obj, test)) |
|---|
| 212 | n/a | else: |
|---|
| 213 | n/a | raise TypeError("don't know how to make test from: %s" % obj) |
|---|
| 214 | n/a | |
|---|
| 215 | n/a | def loadTestsFromNames(self, names, module=None): |
|---|
| 216 | n/a | """Return a suite of all test cases found using the given sequence |
|---|
| 217 | n/a | of string specifiers. See 'loadTestsFromName()'. |
|---|
| 218 | n/a | """ |
|---|
| 219 | n/a | suites = [self.loadTestsFromName(name, module) for name in names] |
|---|
| 220 | n/a | return self.suiteClass(suites) |
|---|
| 221 | n/a | |
|---|
| 222 | n/a | def getTestCaseNames(self, testCaseClass): |
|---|
| 223 | n/a | """Return a sorted sequence of method names found within testCaseClass |
|---|
| 224 | n/a | """ |
|---|
| 225 | n/a | def isTestMethod(attrname, testCaseClass=testCaseClass, |
|---|
| 226 | n/a | prefix=self.testMethodPrefix): |
|---|
| 227 | n/a | return attrname.startswith(prefix) and \ |
|---|
| 228 | n/a | callable(getattr(testCaseClass, attrname)) |
|---|
| 229 | n/a | testFnNames = list(filter(isTestMethod, dir(testCaseClass))) |
|---|
| 230 | n/a | if self.sortTestMethodsUsing: |
|---|
| 231 | n/a | testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing)) |
|---|
| 232 | n/a | return testFnNames |
|---|
| 233 | n/a | |
|---|
| 234 | n/a | def discover(self, start_dir, pattern='test*.py', top_level_dir=None): |
|---|
| 235 | n/a | """Find and return all test modules from the specified start |
|---|
| 236 | n/a | directory, recursing into subdirectories to find them and return all |
|---|
| 237 | n/a | tests found within them. Only test files that match the pattern will |
|---|
| 238 | n/a | be loaded. (Using shell style pattern matching.) |
|---|
| 239 | n/a | |
|---|
| 240 | n/a | All test modules must be importable from the top level of the project. |
|---|
| 241 | n/a | If the start directory is not the top level directory then the top |
|---|
| 242 | n/a | level directory must be specified separately. |
|---|
| 243 | n/a | |
|---|
| 244 | n/a | If a test package name (directory with '__init__.py') matches the |
|---|
| 245 | n/a | pattern then the package will be checked for a 'load_tests' function. If |
|---|
| 246 | n/a | this exists then it will be called with (loader, tests, pattern) unless |
|---|
| 247 | n/a | the package has already had load_tests called from the same discovery |
|---|
| 248 | n/a | invocation, in which case the package module object is not scanned for |
|---|
| 249 | n/a | tests - this ensures that when a package uses discover to further |
|---|
| 250 | n/a | discover child tests that infinite recursion does not happen. |
|---|
| 251 | n/a | |
|---|
| 252 | n/a | If load_tests exists then discovery does *not* recurse into the package, |
|---|
| 253 | n/a | load_tests is responsible for loading all tests in the package. |
|---|
| 254 | n/a | |
|---|
| 255 | n/a | The pattern is deliberately not stored as a loader attribute so that |
|---|
| 256 | n/a | packages can continue discovery themselves. top_level_dir is stored so |
|---|
| 257 | n/a | load_tests does not need to pass this argument in to loader.discover(). |
|---|
| 258 | n/a | |
|---|
| 259 | n/a | Paths are sorted before being imported to ensure reproducible execution |
|---|
| 260 | n/a | order even on filesystems with non-alphabetical ordering like ext3/4. |
|---|
| 261 | n/a | """ |
|---|
| 262 | n/a | set_implicit_top = False |
|---|
| 263 | n/a | if top_level_dir is None and self._top_level_dir is not None: |
|---|
| 264 | n/a | # make top_level_dir optional if called from load_tests in a package |
|---|
| 265 | n/a | top_level_dir = self._top_level_dir |
|---|
| 266 | n/a | elif top_level_dir is None: |
|---|
| 267 | n/a | set_implicit_top = True |
|---|
| 268 | n/a | top_level_dir = start_dir |
|---|
| 269 | n/a | |
|---|
| 270 | n/a | top_level_dir = os.path.abspath(top_level_dir) |
|---|
| 271 | n/a | |
|---|
| 272 | n/a | if not top_level_dir in sys.path: |
|---|
| 273 | n/a | # all test modules must be importable from the top level directory |
|---|
| 274 | n/a | # should we *unconditionally* put the start directory in first |
|---|
| 275 | n/a | # in sys.path to minimise likelihood of conflicts between installed |
|---|
| 276 | n/a | # modules and development versions? |
|---|
| 277 | n/a | sys.path.insert(0, top_level_dir) |
|---|
| 278 | n/a | self._top_level_dir = top_level_dir |
|---|
| 279 | n/a | |
|---|
| 280 | n/a | is_not_importable = False |
|---|
| 281 | n/a | is_namespace = False |
|---|
| 282 | n/a | tests = [] |
|---|
| 283 | n/a | if os.path.isdir(os.path.abspath(start_dir)): |
|---|
| 284 | n/a | start_dir = os.path.abspath(start_dir) |
|---|
| 285 | n/a | if start_dir != top_level_dir: |
|---|
| 286 | n/a | is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py')) |
|---|
| 287 | n/a | else: |
|---|
| 288 | n/a | # support for discovery from dotted module names |
|---|
| 289 | n/a | try: |
|---|
| 290 | n/a | __import__(start_dir) |
|---|
| 291 | n/a | except ImportError: |
|---|
| 292 | n/a | is_not_importable = True |
|---|
| 293 | n/a | else: |
|---|
| 294 | n/a | the_module = sys.modules[start_dir] |
|---|
| 295 | n/a | top_part = start_dir.split('.')[0] |
|---|
| 296 | n/a | try: |
|---|
| 297 | n/a | start_dir = os.path.abspath( |
|---|
| 298 | n/a | os.path.dirname((the_module.__file__))) |
|---|
| 299 | n/a | except AttributeError: |
|---|
| 300 | n/a | # look for namespace packages |
|---|
| 301 | n/a | try: |
|---|
| 302 | n/a | spec = the_module.__spec__ |
|---|
| 303 | n/a | except AttributeError: |
|---|
| 304 | n/a | spec = None |
|---|
| 305 | n/a | |
|---|
| 306 | n/a | if spec and spec.loader is None: |
|---|
| 307 | n/a | if spec.submodule_search_locations is not None: |
|---|
| 308 | n/a | is_namespace = True |
|---|
| 309 | n/a | |
|---|
| 310 | n/a | for path in the_module.__path__: |
|---|
| 311 | n/a | if (not set_implicit_top and |
|---|
| 312 | n/a | not path.startswith(top_level_dir)): |
|---|
| 313 | n/a | continue |
|---|
| 314 | n/a | self._top_level_dir = \ |
|---|
| 315 | n/a | (path.split(the_module.__name__ |
|---|
| 316 | n/a | .replace(".", os.path.sep))[0]) |
|---|
| 317 | n/a | tests.extend(self._find_tests(path, |
|---|
| 318 | n/a | pattern, |
|---|
| 319 | n/a | namespace=True)) |
|---|
| 320 | n/a | elif the_module.__name__ in sys.builtin_module_names: |
|---|
| 321 | n/a | # builtin module |
|---|
| 322 | n/a | raise TypeError('Can not use builtin modules ' |
|---|
| 323 | n/a | 'as dotted module names') from None |
|---|
| 324 | n/a | else: |
|---|
| 325 | n/a | raise TypeError( |
|---|
| 326 | n/a | 'don\'t know how to discover from {!r}' |
|---|
| 327 | n/a | .format(the_module)) from None |
|---|
| 328 | n/a | |
|---|
| 329 | n/a | if set_implicit_top: |
|---|
| 330 | n/a | if not is_namespace: |
|---|
| 331 | n/a | self._top_level_dir = \ |
|---|
| 332 | n/a | self._get_directory_containing_module(top_part) |
|---|
| 333 | n/a | sys.path.remove(top_level_dir) |
|---|
| 334 | n/a | else: |
|---|
| 335 | n/a | sys.path.remove(top_level_dir) |
|---|
| 336 | n/a | |
|---|
| 337 | n/a | if is_not_importable: |
|---|
| 338 | n/a | raise ImportError('Start directory is not importable: %r' % start_dir) |
|---|
| 339 | n/a | |
|---|
| 340 | n/a | if not is_namespace: |
|---|
| 341 | n/a | tests = list(self._find_tests(start_dir, pattern)) |
|---|
| 342 | n/a | return self.suiteClass(tests) |
|---|
| 343 | n/a | |
|---|
| 344 | n/a | def _get_directory_containing_module(self, module_name): |
|---|
| 345 | n/a | module = sys.modules[module_name] |
|---|
| 346 | n/a | full_path = os.path.abspath(module.__file__) |
|---|
| 347 | n/a | |
|---|
| 348 | n/a | if os.path.basename(full_path).lower().startswith('__init__.py'): |
|---|
| 349 | n/a | return os.path.dirname(os.path.dirname(full_path)) |
|---|
| 350 | n/a | else: |
|---|
| 351 | n/a | # here we have been given a module rather than a package - so |
|---|
| 352 | n/a | # all we can do is search the *same* directory the module is in |
|---|
| 353 | n/a | # should an exception be raised instead |
|---|
| 354 | n/a | return os.path.dirname(full_path) |
|---|
| 355 | n/a | |
|---|
| 356 | n/a | def _get_name_from_path(self, path): |
|---|
| 357 | n/a | if path == self._top_level_dir: |
|---|
| 358 | n/a | return '.' |
|---|
| 359 | n/a | path = _jython_aware_splitext(os.path.normpath(path)) |
|---|
| 360 | n/a | |
|---|
| 361 | n/a | _relpath = os.path.relpath(path, self._top_level_dir) |
|---|
| 362 | n/a | assert not os.path.isabs(_relpath), "Path must be within the project" |
|---|
| 363 | n/a | assert not _relpath.startswith('..'), "Path must be within the project" |
|---|
| 364 | n/a | |
|---|
| 365 | n/a | name = _relpath.replace(os.path.sep, '.') |
|---|
| 366 | n/a | return name |
|---|
| 367 | n/a | |
|---|
| 368 | n/a | def _get_module_from_name(self, name): |
|---|
| 369 | n/a | __import__(name) |
|---|
| 370 | n/a | return sys.modules[name] |
|---|
| 371 | n/a | |
|---|
| 372 | n/a | def _match_path(self, path, full_path, pattern): |
|---|
| 373 | n/a | # override this method to use alternative matching strategy |
|---|
| 374 | n/a | return fnmatch(path, pattern) |
|---|
| 375 | n/a | |
|---|
| 376 | n/a | def _find_tests(self, start_dir, pattern, namespace=False): |
|---|
| 377 | n/a | """Used by discovery. Yields test suites it loads.""" |
|---|
| 378 | n/a | # Handle the __init__ in this package |
|---|
| 379 | n/a | name = self._get_name_from_path(start_dir) |
|---|
| 380 | n/a | # name is '.' when start_dir == top_level_dir (and top_level_dir is by |
|---|
| 381 | n/a | # definition not a package). |
|---|
| 382 | n/a | if name != '.' and name not in self._loading_packages: |
|---|
| 383 | n/a | # name is in self._loading_packages while we have called into |
|---|
| 384 | n/a | # loadTestsFromModule with name. |
|---|
| 385 | n/a | tests, should_recurse = self._find_test_path( |
|---|
| 386 | n/a | start_dir, pattern, namespace) |
|---|
| 387 | n/a | if tests is not None: |
|---|
| 388 | n/a | yield tests |
|---|
| 389 | n/a | if not should_recurse: |
|---|
| 390 | n/a | # Either an error occurred, or load_tests was used by the |
|---|
| 391 | n/a | # package. |
|---|
| 392 | n/a | return |
|---|
| 393 | n/a | # Handle the contents. |
|---|
| 394 | n/a | paths = sorted(os.listdir(start_dir)) |
|---|
| 395 | n/a | for path in paths: |
|---|
| 396 | n/a | full_path = os.path.join(start_dir, path) |
|---|
| 397 | n/a | tests, should_recurse = self._find_test_path( |
|---|
| 398 | n/a | full_path, pattern, namespace) |
|---|
| 399 | n/a | if tests is not None: |
|---|
| 400 | n/a | yield tests |
|---|
| 401 | n/a | if should_recurse: |
|---|
| 402 | n/a | # we found a package that didn't use load_tests. |
|---|
| 403 | n/a | name = self._get_name_from_path(full_path) |
|---|
| 404 | n/a | self._loading_packages.add(name) |
|---|
| 405 | n/a | try: |
|---|
| 406 | n/a | yield from self._find_tests(full_path, pattern, namespace) |
|---|
| 407 | n/a | finally: |
|---|
| 408 | n/a | self._loading_packages.discard(name) |
|---|
| 409 | n/a | |
|---|
| 410 | n/a | def _find_test_path(self, full_path, pattern, namespace=False): |
|---|
| 411 | n/a | """Used by discovery. |
|---|
| 412 | n/a | |
|---|
| 413 | n/a | Loads tests from a single file, or a directories' __init__.py when |
|---|
| 414 | n/a | passed the directory. |
|---|
| 415 | n/a | |
|---|
| 416 | n/a | Returns a tuple (None_or_tests_from_file, should_recurse). |
|---|
| 417 | n/a | """ |
|---|
| 418 | n/a | basename = os.path.basename(full_path) |
|---|
| 419 | n/a | if os.path.isfile(full_path): |
|---|
| 420 | n/a | if not VALID_MODULE_NAME.match(basename): |
|---|
| 421 | n/a | # valid Python identifiers only |
|---|
| 422 | n/a | return None, False |
|---|
| 423 | n/a | if not self._match_path(basename, full_path, pattern): |
|---|
| 424 | n/a | return None, False |
|---|
| 425 | n/a | # if the test file matches, load it |
|---|
| 426 | n/a | name = self._get_name_from_path(full_path) |
|---|
| 427 | n/a | try: |
|---|
| 428 | n/a | module = self._get_module_from_name(name) |
|---|
| 429 | n/a | except case.SkipTest as e: |
|---|
| 430 | n/a | return _make_skipped_test(name, e, self.suiteClass), False |
|---|
| 431 | n/a | except: |
|---|
| 432 | n/a | error_case, error_message = \ |
|---|
| 433 | n/a | _make_failed_import_test(name, self.suiteClass) |
|---|
| 434 | n/a | self.errors.append(error_message) |
|---|
| 435 | n/a | return error_case, False |
|---|
| 436 | n/a | else: |
|---|
| 437 | n/a | mod_file = os.path.abspath( |
|---|
| 438 | n/a | getattr(module, '__file__', full_path)) |
|---|
| 439 | n/a | realpath = _jython_aware_splitext( |
|---|
| 440 | n/a | os.path.realpath(mod_file)) |
|---|
| 441 | n/a | fullpath_noext = _jython_aware_splitext( |
|---|
| 442 | n/a | os.path.realpath(full_path)) |
|---|
| 443 | n/a | if realpath.lower() != fullpath_noext.lower(): |
|---|
| 444 | n/a | module_dir = os.path.dirname(realpath) |
|---|
| 445 | n/a | mod_name = _jython_aware_splitext( |
|---|
| 446 | n/a | os.path.basename(full_path)) |
|---|
| 447 | n/a | expected_dir = os.path.dirname(full_path) |
|---|
| 448 | n/a | msg = ("%r module incorrectly imported from %r. Expected " |
|---|
| 449 | n/a | "%r. Is this module globally installed?") |
|---|
| 450 | n/a | raise ImportError( |
|---|
| 451 | n/a | msg % (mod_name, module_dir, expected_dir)) |
|---|
| 452 | n/a | return self.loadTestsFromModule(module, pattern=pattern), False |
|---|
| 453 | n/a | elif os.path.isdir(full_path): |
|---|
| 454 | n/a | if (not namespace and |
|---|
| 455 | n/a | not os.path.isfile(os.path.join(full_path, '__init__.py'))): |
|---|
| 456 | n/a | return None, False |
|---|
| 457 | n/a | |
|---|
| 458 | n/a | load_tests = None |
|---|
| 459 | n/a | tests = None |
|---|
| 460 | n/a | name = self._get_name_from_path(full_path) |
|---|
| 461 | n/a | try: |
|---|
| 462 | n/a | package = self._get_module_from_name(name) |
|---|
| 463 | n/a | except case.SkipTest as e: |
|---|
| 464 | n/a | return _make_skipped_test(name, e, self.suiteClass), False |
|---|
| 465 | n/a | except: |
|---|
| 466 | n/a | error_case, error_message = \ |
|---|
| 467 | n/a | _make_failed_import_test(name, self.suiteClass) |
|---|
| 468 | n/a | self.errors.append(error_message) |
|---|
| 469 | n/a | return error_case, False |
|---|
| 470 | n/a | else: |
|---|
| 471 | n/a | load_tests = getattr(package, 'load_tests', None) |
|---|
| 472 | n/a | # Mark this package as being in load_tests (possibly ;)) |
|---|
| 473 | n/a | self._loading_packages.add(name) |
|---|
| 474 | n/a | try: |
|---|
| 475 | n/a | tests = self.loadTestsFromModule(package, pattern=pattern) |
|---|
| 476 | n/a | if load_tests is not None: |
|---|
| 477 | n/a | # loadTestsFromModule(package) has loaded tests for us. |
|---|
| 478 | n/a | return tests, False |
|---|
| 479 | n/a | return tests, True |
|---|
| 480 | n/a | finally: |
|---|
| 481 | n/a | self._loading_packages.discard(name) |
|---|
| 482 | n/a | else: |
|---|
| 483 | n/a | return None, False |
|---|
| 484 | n/a | |
|---|
| 485 | n/a | |
|---|
| 486 | n/a | defaultTestLoader = TestLoader() |
|---|
| 487 | n/a | |
|---|
| 488 | n/a | |
|---|
| 489 | n/a | def _makeLoader(prefix, sortUsing, suiteClass=None): |
|---|
| 490 | n/a | loader = TestLoader() |
|---|
| 491 | n/a | loader.sortTestMethodsUsing = sortUsing |
|---|
| 492 | n/a | loader.testMethodPrefix = prefix |
|---|
| 493 | n/a | if suiteClass: |
|---|
| 494 | n/a | loader.suiteClass = suiteClass |
|---|
| 495 | n/a | return loader |
|---|
| 496 | n/a | |
|---|
| 497 | n/a | def getTestCaseNames(testCaseClass, prefix, sortUsing=util.three_way_cmp): |
|---|
| 498 | n/a | return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass) |
|---|
| 499 | n/a | |
|---|
| 500 | n/a | def makeSuite(testCaseClass, prefix='test', sortUsing=util.three_way_cmp, |
|---|
| 501 | n/a | suiteClass=suite.TestSuite): |
|---|
| 502 | n/a | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase( |
|---|
| 503 | n/a | testCaseClass) |
|---|
| 504 | n/a | |
|---|
| 505 | n/a | def findTestCases(module, prefix='test', sortUsing=util.three_way_cmp, |
|---|
| 506 | n/a | suiteClass=suite.TestSuite): |
|---|
| 507 | n/a | return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(\ |
|---|
| 508 | n/a | module) |
|---|