| 1 |
#!/usr/bin/env python |
| 2 |
# |
| 3 |
# SchoolTool - common information systems platform for school administration |
| 4 |
# Copyright (c) 2003 Shuttleworth Foundation |
| 5 |
# |
| 6 |
# This program is free software; you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation; either version 2 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# This program is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with this program; if not, write to the Free Software |
| 18 |
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 19 |
# |
| 20 |
""" |
| 21 |
SchoolTool test runner. |
| 22 |
|
| 23 |
Syntax: test.py [options] [pathname-regexp [test-regexp]] |
| 24 |
|
| 25 |
There are two kinds of tests: |
| 26 |
- unit tests (or programmer tests) test the internal workings of various |
| 27 |
components of the system |
| 28 |
- functional tests (acceptance tests, customer tests) test only externally |
| 29 |
visible system behaviour |
| 30 |
|
| 31 |
You can choose to run unit tests (this is the default mode), functional tests |
| 32 |
(by giving a -f option to test.py) or both (by giving both -u and -f options). |
| 33 |
|
| 34 |
Test cases are located in the directory tree starting at the location of this |
| 35 |
script, in subdirectories named 'tests' for unit tests and 'ftests' for |
| 36 |
functional tests, in Python modules named 'test*.py'. They are then filtered |
| 37 |
according to pathname and test regexes. Alternatively, packages may just have |
| 38 |
'tests.py' and 'ftests.py' instead of subpackages 'tests' and 'ftests' |
| 39 |
respectively. |
| 40 |
|
| 41 |
A leading "!" in a regexp is stripped and negates the regexp. Pathname |
| 42 |
regexp is applied to the whole path (package/package/module.py). Test regexp |
| 43 |
is applied to a full test id (package.package.module.class.test_method). |
| 44 |
|
| 45 |
Options: |
| 46 |
-h print this help message |
| 47 |
-v verbose (print dots for each test run) |
| 48 |
-vv very verbose (print test names) |
| 49 |
-q quiet (do not print anything on success) |
| 50 |
-w enable warnings about omitted test cases |
| 51 |
-p show progress bar (can be combined with -v or -vv) |
| 52 |
-u select unit tests (default) |
| 53 |
-f select functional tests |
| 54 |
--level n select only tests at level n or lower |
| 55 |
--all-levels select all tests |
| 56 |
--list-files list all selected test files |
| 57 |
--list-tests list all selected test cases |
| 58 |
--list-hooks list all loaded test hooks |
| 59 |
--coverage create code coverage reports |
| 60 |
""" |
| 61 |
# |
| 62 |
# This script borrows ideas from Zope 3's test runner heavily. It is smaller |
| 63 |
# and cleaner though, at the expense of more limited functionality. |
| 64 |
# |
| 65 |
|
| 66 |
import re |
| 67 |
import os |
| 68 |
import sys |
| 69 |
import time |
| 70 |
import types |
| 71 |
import getopt |
| 72 |
import unittest |
| 73 |
import traceback |
| 74 |
|
| 75 |
from unittest import TextTestResult |
| 76 |
|
| 77 |
__metaclass__ = type |
| 78 |
|
| 79 |
def stderr(text): |
| 80 |
sys.stderr.write(text) |
| 81 |
sys.stderr.write("\n") |
| 82 |
|
| 83 |
class Options: |
| 84 |
"""Configurable properties of the test runner.""" |
| 85 |
|
| 86 |
# test location |
| 87 |
basedir = '' # base directory for tests (defaults to |
| 88 |
# basedir of argv[0] + 'src'), must be absolute |
| 89 |
src_in_path = True # add 'src/' to sys.path |
| 90 |
follow_symlinks = True # should symlinks to subdirectories be |
| 91 |
# followed? (hardcoded, may cause loops) |
| 92 |
|
| 93 |
# which tests to run |
| 94 |
unit_tests = False # unit tests (default if both are false) |
| 95 |
functional_tests = False # functional tests |
| 96 |
|
| 97 |
# test filtering |
| 98 |
level = 1 # run only tests at this or lower level |
| 99 |
# (if None, runs all tests) |
| 100 |
pathname_regex = '' # regexp for filtering filenames |
| 101 |
test_regex = '' # regexp for filtering test cases |
| 102 |
|
| 103 |
# actions to take |
| 104 |
list_files = False # --list-files |
| 105 |
list_tests = False # --list-tests |
| 106 |
list_hooks = False # --list-hooks |
| 107 |
run_tests = True # run tests (disabled by --list-foo) |
| 108 |
|
| 109 |
# output verbosity |
| 110 |
verbosity = 0 # verbosity level (-v) |
| 111 |
quiet = 0 # do not print anything on success (-q) |
| 112 |
warn_omitted = False # produce warnings when a test case is |
| 113 |
# not included in a test suite (-w) |
| 114 |
progress = False # show running progress (-p) |
| 115 |
coverage = False # produce coverage reports (--coverage) |
| 116 |
coverdir = 'coverage' # where to put them (currently hardcoded) |
| 117 |
immediate_errors = False # show tracebacks twice (currently hardcoded) |
| 118 |
screen_width = 80 # screen width (autodetected) |
| 119 |
|
| 120 |
|
| 121 |
def compile_matcher(regex): |
| 122 |
"""Returns a function that takes one argument and returns True or False. |
| 123 |
|
| 124 |
Regex is a regular expression. Empty regex matches everything. There |
| 125 |
is one expression: if the regex starts with "!", the meaning of it is |
| 126 |
reversed. |
| 127 |
""" |
| 128 |
if not regex: |
| 129 |
return lambda x: True |
| 130 |
elif regex == '!': |
| 131 |
return lambda x: False |
| 132 |
elif regex.startswith('!'): |
| 133 |
rx = re.compile(regex[1:]) |
| 134 |
return lambda x: rx.search(x) is None |
| 135 |
else: |
| 136 |
rx = re.compile(regex) |
| 137 |
return lambda x: rx.search(x) is not None |
| 138 |
|
| 139 |
|
| 140 |
def walk_with_symlinks(top, func, arg): |
| 141 |
"""Like os.path.walk, but follows symlinks on POSIX systems. |
| 142 |
|
| 143 |
If the symlinks create a loop, this function will never finish. |
| 144 |
""" |
| 145 |
try: |
| 146 |
names = os.listdir(top) |
| 147 |
except os.error: |
| 148 |
return |
| 149 |
func(arg, top, names) |
| 150 |
exceptions = ('.', '..') |
| 151 |
for name in names: |
| 152 |
if name not in exceptions: |
| 153 |
name = os.path.join(top, name) |
| 154 |
if os.path.isdir(name): |
| 155 |
walk_with_symlinks(name, func, arg) |
| 156 |
|
| 157 |
|
| 158 |
def get_test_files(cfg): |
| 159 |
"""Returns a list of test module filenames.""" |
| 160 |
matcher = compile_matcher(cfg.pathname_regex) |
| 161 |
results = [] |
| 162 |
test_names = [] |
| 163 |
if cfg.unit_tests: |
| 164 |
test_names.append('tests') |
| 165 |
if cfg.functional_tests: |
| 166 |
test_names.append('ftests') |
| 167 |
baselen = len(cfg.basedir) + 1 |
| 168 |
def visit(ignored, dir, files): |
| 169 |
if os.path.basename(dir) not in test_names: |
| 170 |
for name in test_names: |
| 171 |
if name + '.py' in files: |
| 172 |
path = os.path.join(dir, name + '.py') |
| 173 |
if matcher(path[baselen:]): |
| 174 |
results.append(path) |
| 175 |
return |
| 176 |
if '__init__.py' not in files: |
| 177 |
stderr("%s is not a package" % dir) |
| 178 |
return |
| 179 |
for file in files: |
| 180 |
if file.startswith('test') and file.endswith('.py'): |
| 181 |
path = os.path.join(dir, file) |
| 182 |
if matcher(path[baselen:]): |
| 183 |
results.append(path) |
| 184 |
if cfg.follow_symlinks: |
| 185 |
walker = walk_with_symlinks |
| 186 |
else: |
| 187 |
walker = os.path.walk |
| 188 |
walker(cfg.basedir, visit, None) |
| 189 |
results.sort() |
| 190 |
return results |
| 191 |
|
| 192 |
|
| 193 |
def import_module(filename, cfg, cov=None): |
| 194 |
"""Imports and returns a module.""" |
| 195 |
filename = os.path.splitext(filename)[0] |
| 196 |
modname = filename[len(cfg.basedir):].replace(os.path.sep, '.') |
| 197 |
if modname.startswith('.'): |
| 198 |
modname = modname[1:] |
| 199 |
if cov is not None: |
| 200 |
cov.start() |
| 201 |
mod = __import__(modname) |
| 202 |
if cov is not None: |
| 203 |
cov.stop() |
| 204 |
components = modname.split('.') |
| 205 |
for comp in components[1:]: |
| 206 |
mod = getattr(mod, comp) |
| 207 |
return mod |
| 208 |
|
| 209 |
|
| 210 |
def filter_testsuite(suite, matcher, level=None): |
| 211 |
"""Returns a flattened list of test cases that match the given matcher.""" |
| 212 |
if not isinstance(suite, unittest.TestSuite): |
| 213 |
raise TypeError('not a TestSuite', suite) |
| 214 |
results = [] |
| 215 |
for test in suite._tests: |
| 216 |
if level is not None and getattr(test, 'level', 0) > level: |
| 217 |
continue |
| 218 |
if isinstance(test, unittest.TestCase): |
| 219 |
testname = test.id() # package.module.class.method |
| 220 |
if matcher(testname): |
| 221 |
results.append(test) |
| 222 |
else: |
| 223 |
filtered = filter_testsuite(test, matcher, level) |
| 224 |
results.extend(filtered) |
| 225 |
return results |
| 226 |
|
| 227 |
|
| 228 |
def get_all_test_cases(module): |
| 229 |
"""Returns a list of all test case classes defined in a given module.""" |
| 230 |
results = [] |
| 231 |
for name in dir(module): |
| 232 |
if not name.startswith('Test'): |
| 233 |
continue |
| 234 |
item = getattr(module, name) |
| 235 |
if (isinstance(item, (type, types.ClassType)) and |
| 236 |
issubclass(item, unittest.TestCase)): |
| 237 |
results.append(item) |
| 238 |
return results |
| 239 |
|
| 240 |
|
| 241 |
def get_test_classes_from_testsuite(suite): |
| 242 |
"""Returns a set of test case classes used in a test suite.""" |
| 243 |
if not isinstance(suite, unittest.TestSuite): |
| 244 |
raise TypeError('not a TestSuite', suite) |
| 245 |
results = set() |
| 246 |
for test in suite._tests: |
| 247 |
if isinstance(test, unittest.TestCase): |
| 248 |
results.add(test.__class__) |
| 249 |
else: |
| 250 |
classes = get_test_classes_from_testsuite(test) |
| 251 |
results.update(classes) |
| 252 |
return results |
| 253 |
|
| 254 |
|
| 255 |
def get_test_cases(test_files, cfg, cov=None): |
| 256 |
"""Returns a list of test cases from a given list of test modules.""" |
| 257 |
matcher = compile_matcher(cfg.test_regex) |
| 258 |
results = [] |
| 259 |
for file in test_files: |
| 260 |
module = import_module(file, cfg, cov=cov) |
| 261 |
if cov is not None: |
| 262 |
cov.start() |
| 263 |
test_suite = module.test_suite() |
| 264 |
if cov is not None: |
| 265 |
cov.stop() |
| 266 |
if test_suite is None: |
| 267 |
continue |
| 268 |
if cfg.warn_omitted: |
| 269 |
all_classes = set(get_all_test_cases(module)) |
| 270 |
classes_in_suite = get_test_classes_from_testsuite(test_suite) |
| 271 |
difference = all_classes - classes_in_suite |
| 272 |
for test_class in difference: |
| 273 |
# surround the warning with blank lines, otherwise it tends |
| 274 |
# to get lost in the noise |
| 275 |
stderr("\n%s: WARNING: %s not in test suite\n" |
| 276 |
% (file, test_class.__name__)) |
| 277 |
if (cfg.level is not None and |
| 278 |
getattr(test_suite, 'level', 0) > cfg.level): |
| 279 |
continue |
| 280 |
filtered = filter_testsuite(test_suite, matcher, cfg.level) |
| 281 |
results.extend(filtered) |
| 282 |
return results |
| 283 |
|
| 284 |
|
| 285 |
def get_test_hooks(test_files, cfg, cov=None): |
| 286 |
"""Returns a list of test hooks from a given list of test modules.""" |
| 287 |
results = [] |
| 288 |
dirs = set(map(os.path.dirname, test_files)) |
| 289 |
for dir in list(dirs): |
| 290 |
if os.path.basename(dir) == 'ftests': |
| 291 |
dirs.add(os.path.join(os.path.dirname(dir), 'tests')) |
| 292 |
dirs = list(dirs) |
| 293 |
dirs.sort() |
| 294 |
for dir in dirs: |
| 295 |
filename = os.path.join(dir, 'checks.py') |
| 296 |
if os.path.exists(filename): |
| 297 |
module = import_module(filename, cfg, tracer=tracer) |
| 298 |
if cov is not None: |
| 299 |
cov.start() |
| 300 |
hooks = module.test_hooks() |
| 301 |
if cov is not None: |
| 302 |
cov.stop() |
| 303 |
results.extend(hooks) |
| 304 |
return results |
| 305 |
|
| 306 |
|
| 307 |
class CustomTestResult(TextTestResult): |
| 308 |
"""Customised TestResult. |
| 309 |
|
| 310 |
It can show a progress bar, and displays tracebacks for errors and failures |
| 311 |
as soon as they happen, in addition to listing them all at the end. |
| 312 |
""" |
| 313 |
|
| 314 |
__super = TextTestResult |
| 315 |
__super_init = __super.__init__ |
| 316 |
__super_startTest = __super.startTest |
| 317 |
__super_stopTest = __super.stopTest |
| 318 |
__super_printErrors = __super.printErrors |
| 319 |
|
| 320 |
def __init__(self, stream, descriptions, verbosity, count, cfg, hooks): |
| 321 |
self.__super_init(stream, descriptions, verbosity) |
| 322 |
self.count = count |
| 323 |
self.cfg = cfg |
| 324 |
self.hooks = hooks |
| 325 |
if cfg.progress: |
| 326 |
self.dots = False |
| 327 |
self._lastWidth = 0 |
| 328 |
self._maxWidth = cfg.screen_width - len("xxxx/xxxx (xxx.x%): ") - 1 |
| 329 |
|
| 330 |
def startTest(self, test): |
| 331 |
if self.cfg.progress: |
| 332 |
# verbosity == 0: 'xxxx/xxxx (xxx.x%)' |
| 333 |
# verbosity == 1: 'xxxx/xxxx (xxx.x%): test name' |
| 334 |
# verbosity >= 2: 'xxxx/xxxx (xxx.x%): test name ... ok' |
| 335 |
n = self.testsRun + 1 |
| 336 |
self.stream.write("\r%4d" % n) |
| 337 |
if self.count: |
| 338 |
self.stream.write("/%d (%5.1f%%)" |
| 339 |
% (self.count, n * 100.0 / self.count)) |
| 340 |
if self.showAll: # self.cfg.verbosity == 1 |
| 341 |
self.stream.write(": ") |
| 342 |
elif self.cfg.verbosity: |
| 343 |
name = self.getShortDescription(test) |
| 344 |
width = len(name) |
| 345 |
if width < self._lastWidth: |
| 346 |
name += " " * (self._lastWidth - width) |
| 347 |
self.stream.write(": %s" % name) |
| 348 |
self._lastWidth = width |
| 349 |
self.stream.flush() |
| 350 |
self.__super_startTest(test) |
| 351 |
for hook in self.hooks: |
| 352 |
hook.startTest(test) |
| 353 |
|
| 354 |
def stopTest(self, test): |
| 355 |
for hook in self.hooks: |
| 356 |
hook.stopTest(test) |
| 357 |
self.__super_stopTest(test) |
| 358 |
|
| 359 |
def getShortDescription(self, test): |
| 360 |
s = self.getDescription(test) |
| 361 |
if len(s) > self._maxWidth: |
| 362 |
# s is 'testname (package.module.class)' |
| 363 |
# try to shorten it to 'testname (...age.module.class)' |
| 364 |
# if it is still too long, shorten it to 'testnam...' |
| 365 |
# limit case is 'testname (...)' |
| 366 |
pos = s.find(" (") |
| 367 |
if pos + len(" (...)") > self._maxWidth: |
| 368 |
s = s[:self._maxWidth - 3] + "..." |
| 369 |
else: |
| 370 |
s = "%s...%s" % (s[:pos + 2], s[pos + 5 - self._maxWidth:]) |
| 371 |
return s |
| 372 |
|
| 373 |
def printErrors(self): |
| 374 |
if self.cfg.progress and not (self.dots or self.showAll): |
| 375 |
self.stream.writeln() |
| 376 |
self.__super_printErrors() |
| 377 |
|
| 378 |
def formatError(self, err): |
| 379 |
return "".join(traceback.format_exception(*err)) |
| 380 |
|
| 381 |
def printTraceback(self, kind, test, err): |
| 382 |
self.stream.writeln() |
| 383 |
self.stream.writeln() |
| 384 |
self.stream.writeln("%s: %s" % (kind, test)) |
| 385 |
self.stream.writeln(self.formatError(err)) |
| 386 |
self.stream.writeln() |
| 387 |
|
| 388 |
def addFailure(self, test, err): |
| 389 |
if self.cfg.immediate_errors: |
| 390 |
self.printTraceback("FAIL", test, err) |
| 391 |
self.failures.append((test, self.formatError(err))) |
| 392 |
|
| 393 |
def addError(self, test, err): |
| 394 |
if self.cfg.immediate_errors: |
| 395 |
self.printTraceback("ERROR", test, err) |
| 396 |
self.errors.append((test, self.formatError(err))) |
| 397 |
|
| 398 |
|
| 399 |
class CustomTestRunner(unittest.TextTestRunner): |
| 400 |
"""Customised TestRunner. |
| 401 |
|
| 402 |
See CustomisedTextResult for a list of extensions. |
| 403 |
""" |
| 404 |
|
| 405 |
__super = unittest.TextTestRunner |
| 406 |
__super_init = __super.__init__ |
| 407 |
__super_run = __super.run |
| 408 |
|
| 409 |
def __init__(self, cfg, hooks=None): |
| 410 |
self.__super_init(verbosity=cfg.verbosity) |
| 411 |
self.cfg = cfg |
| 412 |
if hooks is not None: |
| 413 |
self.hooks = hooks |
| 414 |
else: |
| 415 |
self.hooks = [] |
| 416 |
|
| 417 |
def run(self, test): |
| 418 |
"""Run the given test case or test suite.""" |
| 419 |
self.count = test.countTestCases() |
| 420 |
result = self._makeResult() |
| 421 |
startTime = time.time() |
| 422 |
test(result) |
| 423 |
stopTime = time.time() |
| 424 |
timeTaken = float(stopTime - startTime) |
| 425 |
result.printErrors() |
| 426 |
run = result.testsRun |
| 427 |
if not self.cfg.quiet: |
| 428 |
self.stream.writeln(result.separator2) |
| 429 |
self.stream.writeln("Ran %d test%s in %.3fs" % |
| 430 |
(run, run != 1 and "s" or "", timeTaken)) |
| 431 |
self.stream.writeln() |
| 432 |
if not result.wasSuccessful(): |
| 433 |
self.stream.write("FAILED (") |
| 434 |
failed, errored = list(map(len, (result.failures, result.errors))) |
| 435 |
if failed: |
| 436 |
self.stream.write("failures=%d" % failed) |
| 437 |
if errored: |
| 438 |
if failed: self.stream.write(", ") |
| 439 |
self.stream.write("errors=%d" % errored) |
| 440 |
self.stream.writeln(")") |
| 441 |
elif not self.cfg.quiet: |
| 442 |
self.stream.writeln("OK") |
| 443 |
return result |
| 444 |
|
| 445 |
def _makeResult(self): |
| 446 |
return CustomTestResult(self.stream, self.descriptions, self.verbosity, |
| 447 |
cfg=self.cfg, count=self.count, |
| 448 |
hooks=self.hooks) |
| 449 |
|
| 450 |
|
| 451 |
def main(argv): |
| 452 |
"""Main program.""" |
| 453 |
|
| 454 |
# Environment |
| 455 |
if sys.version_info < (2, 7): |
| 456 |
stderr('%s: need Python 2.7 or later' % argv[0]) |
| 457 |
stderr('your python is %s' % sys.version) |
| 458 |
return 1 |
| 459 |
|
| 460 |
# Defaults |
| 461 |
cfg = Options() |
| 462 |
cfg.basedir = os.path.join(os.path.dirname(argv[0]), 'src') |
| 463 |
cfg.basedir = os.path.abspath(cfg.basedir) |
| 464 |
|
| 465 |
# Figure out terminal size |
| 466 |
try: |
| 467 |
import curses |
| 468 |
except ImportError: |
| 469 |
pass |
| 470 |
else: |
| 471 |
try: |
| 472 |
curses.setupterm() |
| 473 |
cols = curses.tigetnum('cols') |
| 474 |
if cols > 0: |
| 475 |
cfg.screen_width = cols |
| 476 |
except (curses.error, TypeError): |
| 477 |
# tigetnum() is broken in PyPy3 and raises TypeError |
| 478 |
pass |
| 479 |
|
| 480 |
# Option processing |
| 481 |
opts, args = getopt.gnu_getopt(argv[1:], 'hvpqufw', |
| 482 |
['list-files', 'list-tests', 'list-hooks', |
| 483 |
'level=', 'all-levels', 'coverage', 'no-src']) |
| 484 |
for k, v in opts: |
| 485 |
if k == '-h': |
| 486 |
print(__doc__) |
| 487 |
return 0 |
| 488 |
elif k == '-v': |
| 489 |
cfg.verbosity += 1 |
| 490 |
cfg.quiet = False |
| 491 |
elif k == '-p': |
| 492 |
cfg.progress = True |
| 493 |
cfg.quiet = False |
| 494 |
elif k == '-q': |
| 495 |
cfg.verbosity = 0 |
| 496 |
cfg.progress = False |
| 497 |
cfg.quiet = True |
| 498 |
elif k == '-u': |
| 499 |
cfg.unit_tests = True |
| 500 |
elif k == '-f': |
| 501 |
cfg.functional_tests = True |
| 502 |
elif k == '-w': |
| 503 |
cfg.warn_omitted = True |
| 504 |
elif k == '--list-files': |
| 505 |
cfg.list_files = True |
| 506 |
cfg.run_tests = False |
| 507 |
elif k == '--list-tests': |
| 508 |
cfg.list_tests = True |
| 509 |
cfg.run_tests = False |
| 510 |
elif k == '--list-hooks': |
| 511 |
cfg.list_hooks = True |
| 512 |
cfg.run_tests = False |
| 513 |
elif k == '--coverage': |
| 514 |
cfg.coverage = True |
| 515 |
elif k == '--no-src': |
| 516 |
cfg.src_in_path = False |
| 517 |
elif k == '--level': |
| 518 |
try: |
| 519 |
cfg.level = int(v) |
| 520 |
except ValueError: |
| 521 |
stderr('%s: invalid level: %s' % (argv[0], v)) |
| 522 |
stderr('run %s -h for help') |
| 523 |
return 1 |
| 524 |
elif k == '--all-levels': |
| 525 |
cfg.level = None |
| 526 |
else: |
| 527 |
stderr('%s: invalid option: %s' % (argv[0], k)) |
| 528 |
stderr('run %s -h for help') |
| 529 |
return 1 |
| 530 |
if args: |
| 531 |
cfg.pathname_regex = args[0] |
| 532 |
if len(args) > 1: |
| 533 |
cfg.test_regex = args[1] |
| 534 |
if len(args) > 2: |
| 535 |
stderr('%s: too many arguments: %s' % (argv[0], args[2])) |
| 536 |
stderr('run %s -h for help') |
| 537 |
return 1 |
| 538 |
if not cfg.unit_tests and not cfg.functional_tests: |
| 539 |
cfg.unit_tests = True |
| 540 |
|
| 541 |
# Set up the python path |
| 542 |
if cfg.src_in_path: |
| 543 |
sys.path[0] = cfg.basedir |
| 544 |
|
| 545 |
# Set up tracing before we start importing things |
| 546 |
cov = None |
| 547 |
if cfg.run_tests and cfg.coverage: |
| 548 |
from coverage import Coverage |
| 549 |
cov = Coverage(omit=['test.py']) |
| 550 |
|
| 551 |
# Finding and importing |
| 552 |
test_files = get_test_files(cfg) |
| 553 |
|
| 554 |
if cov is not None: |
| 555 |
cov.start() |
| 556 |
if cfg.list_tests or cfg.run_tests: |
| 557 |
test_cases = get_test_cases(test_files, cfg, cov=cov) |
| 558 |
if cfg.list_hooks or cfg.run_tests: |
| 559 |
test_hooks = get_test_hooks(test_files, cfg, cov=cov) |
| 560 |
|
| 561 |
# Configure the logging module |
| 562 |
import logging |
| 563 |
logging.basicConfig() |
| 564 |
logging.root.setLevel(logging.CRITICAL) |
| 565 |
|
| 566 |
# Running |
| 567 |
success = True |
| 568 |
if cfg.list_files: |
| 569 |
baselen = len(cfg.basedir) + 1 |
| 570 |
print("\n".join([fn[baselen:] for fn in test_files])) |
| 571 |
if cfg.list_tests: |
| 572 |
print("\n".join([test.id() for test in test_cases])) |
| 573 |
if cfg.list_hooks: |
| 574 |
print("\n".join([str(hook) for hook in test_hooks])) |
| 575 |
if cfg.run_tests: |
| 576 |
runner = CustomTestRunner(cfg, test_hooks) |
| 577 |
suite = unittest.TestSuite() |
| 578 |
suite.addTests(test_cases) |
| 579 |
if cov is not None: |
| 580 |
cov.start() |
| 581 |
run_result = runner.run(suite) |
| 582 |
if cov is not None: |
| 583 |
cov.stop() |
| 584 |
success = run_result.wasSuccessful() |
| 585 |
del run_result |
| 586 |
|
| 587 |
if cov is not None: |
| 588 |
traced_file_types = ('.py', '.pyx', '.pxi', '.pxd') |
| 589 |
modules = [] |
| 590 |
|
| 591 |
def add_file(_, path, files): |
| 592 |
if 'tests' in os.path.relpath(path, cfg.basedir).split(os.sep): |
| 593 |
return |
| 594 |
for filename in files: |
| 595 |
if filename.endswith(traced_file_types): |
| 596 |
modules.append(os.path.join(path, filename)) |
| 597 |
|
| 598 |
if cfg.follow_symlinks: |
| 599 |
walker = walk_with_symlinks |
| 600 |
else: |
| 601 |
walker = os.path.walk |
| 602 |
walker(os.path.abspath(cfg.basedir), add_file, None) |
| 603 |
|
| 604 |
try: |
| 605 |
cov.xml_report(modules, outfile='coverage.xml') |
| 606 |
if cfg.coverdir: |
| 607 |
cov.html_report(modules, directory=cfg.coverdir) |
| 608 |
finally: |
| 609 |
# test runs can take a while, so at least try to print something |
| 610 |
cov.report() |
| 611 |
|
| 612 |
# That's all |
| 613 |
if success: |
| 614 |
return 0 |
| 615 |
else: |
| 616 |
return 1 |
| 617 |
|
| 618 |
|
| 619 |
if __name__ == '__main__': |
| 620 |
exitcode = main(sys.argv) |
| 621 |
sys.exit(exitcode) |