| 1 |
|
| 2 |
|
| 3 |
. |
| 4 |
. |
| 5 |
|
| 6 |
u"""\ |
| 7 |
Execute a validation suite built in pylib's py.test style. |
| 8 |
|
| 9 |
Usage: pytest [OPTION]... [PATH]... |
| 10 |
|
| 11 |
Options: |
| 12 |
-h Print this help and exit right away. |
| 13 |
-v Produce one line per test, instead of a dot per test. |
| 14 |
-n Do not capture stdout nor stderr. |
| 15 |
-p Profile validation suite (through "lsprof"). |
| 16 |
|
| 17 |
-f PREFIX Use PREFIX instead of "test_" for file names. |
| 18 |
-s FILE Save ordinals of failed tests, one per line. |
| 19 |
-o ORDINALS Only consider tests having these execution ordinals. |
| 20 |
-k PATTERN Only retain tests which names match PATTERN. |
| 21 |
-x PATTERN Exclude tests which names match PATTERN. |
| 22 |
-l LIMIT Stop the validation suite after LIMIT errors. |
| 23 |
|
| 24 |
If -l is not used, the validation will stop after 10 errors. ORDINALS is |
| 25 |
a sequence of comma-separated integers. Options -k, -o and -x may be |
| 26 |
repeated; then a test should match at least one of -k options if any, |
| 27 |
one of -o options is any, and none of -x options. |
| 28 |
|
| 29 |
When PATH names a directory, it is recursively searched to find files |
| 30 |
matching "test_.*\\.py". Otherwise, it should give a ".py" ended file name |
| 31 |
containing tests. If no PATH are given, the current directory is implied. |
| 32 |
|
| 33 |
Test progression is first displayed on standard error. Then, unless |
| 34 |
-s is selected, failed tests are detailed on stdout and, if there is at |
| 35 |
least one such failed test, the return status of this program is non-zero. |
| 36 |
""" |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
__metaclass__ = type |
| 43 |
import inspect, os, sys, time, traceback |
| 44 |
from io import StringIO |
| 45 |
|
| 46 |
if os.name == 'nt': |
| 47 |
os.add_dll_directory(os.environ['SHARED_LIB_DIR']) |
| 48 |
|
| 49 |
|
| 50 |
WIDTH = 79 |
| 51 |
|
| 52 |
class Limit_Reached(Exception): pass |
| 53 |
|
| 54 |
class Main: |
| 55 |
prefix = 'test_' |
| 56 |
pattern = [] |
| 57 |
exclusion = [] |
| 58 |
ordinals = [] |
| 59 |
verbose = False |
| 60 |
profile = False |
| 61 |
limit = 10 |
| 62 |
capture = True |
| 63 |
save = None |
| 64 |
|
| 65 |
|
| 66 |
delayed_setup_module = None |
| 67 |
delayed_setup_class = None |
| 68 |
did_tests_in_module = False |
| 69 |
did_tests_in_class = False |
| 70 |
|
| 71 |
def main(self, *arguments): |
| 72 |
if sys.getdefaultencoding() == 'ascii': |
| 73 |
sys.stdout = Friendly_StreamWriter(sys.stdout) |
| 74 |
sys.stderr = Friendly_StreamWriter(sys.stderr) |
| 75 |
import getopt |
| 76 |
options, arguments = getopt.getopt(arguments, u'f:hk:l:no:ps:vx:') |
| 77 |
for option, value in options: |
| 78 |
if option == u'-f': |
| 79 |
self.prefix = value |
| 80 |
elif option == u'-h': |
| 81 |
sys.stdout.write(__doc__) |
| 82 |
return |
| 83 |
elif option == u'-k': |
| 84 |
self.pattern.append(value) |
| 85 |
elif option == u'-l': |
| 86 |
self.limit = int(value) |
| 87 |
elif option == u'-n': |
| 88 |
self.capture = False |
| 89 |
elif option == u'-o': |
| 90 |
self.ordinals += [ |
| 91 |
int(text) for text in value.replace(u',', u' ').split()] |
| 92 |
elif option == u'-p': |
| 93 |
self.profile = True |
| 94 |
elif option == u'-s': |
| 95 |
self.save = value |
| 96 |
elif option == u'-v': |
| 97 |
self.verbose = True |
| 98 |
elif option == u'-x': |
| 99 |
self.exclusion.append(value) |
| 100 |
if not arguments: |
| 101 |
arguments = u'.', |
| 102 |
if self.pattern: |
| 103 |
import re |
| 104 |
self.pattern = re.compile(u'|'.join(self.pattern)) |
| 105 |
else: |
| 106 |
self.pattern = None |
| 107 |
if self.exclusion: |
| 108 |
import re |
| 109 |
self.exclusion = re.compile(u'|'.join(self.exclusion)) |
| 110 |
else: |
| 111 |
self.exclusion = None |
| 112 |
write = sys.stderr.write |
| 113 |
self.failures = [] |
| 114 |
self.total_count = 0 |
| 115 |
self.skip_count = 0 |
| 116 |
start_time = time.time() |
| 117 |
if self.profile: |
| 118 |
try: |
| 119 |
import lsprof |
| 120 |
except ImportError: |
| 121 |
write(u"WARNING: profiler unavailable.\n") |
| 122 |
self.profiler = None |
| 123 |
else: |
| 124 |
self.profiler = lsprof.Profiler() |
| 125 |
else: |
| 126 |
self.profiler = None |
| 127 |
try: |
| 128 |
try: |
| 129 |
for argument in arguments: |
| 130 |
for file_name in self.each_file(argument): |
| 131 |
self.identifier = file_name |
| 132 |
self.column = 0 |
| 133 |
self.counter = 0 |
| 134 |
directory, base = os.path.split(file_name) |
| 135 |
sys.path.insert(0, directory) |
| 136 |
try: |
| 137 |
try: |
| 138 |
module = __import__(base[:-3]) |
| 139 |
except ImportError: |
| 140 |
if self.save: |
| 141 |
self.failures.append(self.total_count + 1) |
| 142 |
else: |
| 143 |
tracing = StringIO() |
| 144 |
traceback.print_exc(file=tracing) |
| 145 |
self.failures.append( |
| 146 |
(self.total_count + 1, file_name, |
| 147 |
None, None, |
| 148 |
None, None, |
| 149 |
tracing.getvalue())) |
| 150 |
else: |
| 151 |
self.handle_module(file_name, module) |
| 152 |
finally: |
| 153 |
del sys.path[0] |
| 154 |
if self.counter and not self.verbose: |
| 155 |
text = u'(%d)' % self.counter |
| 156 |
if self.column + 1 + len(text) >= WIDTH: |
| 157 |
write(u'\n%5d ' % self.counter) |
| 158 |
else: |
| 159 |
text = u' ' + text |
| 160 |
write(text + u'\n') |
| 161 |
except Exit as exception: |
| 162 |
if not self.verbose: |
| 163 |
write(u'\n') |
| 164 |
write(u'\n* %s *\n' % str(exception)) |
| 165 |
except Limit_Reached: |
| 166 |
if not self.verbose: |
| 167 |
write(u'\n') |
| 168 |
if not self.save: |
| 169 |
if len(self.failures) == 1: |
| 170 |
write(u'\n* One error already! *\n') |
| 171 |
else: |
| 172 |
write(u'\n* %d errors already! *\n' % self.limit) |
| 173 |
finally: |
| 174 |
if self.profiler is not None: |
| 175 |
stats = lsprof.Stats(self.profiler.getstats()) |
| 176 |
stats.sort(u'inlinetime') |
| 177 |
write(u'\n') |
| 178 |
stats.pprint(15) |
| 179 |
if self.failures: |
| 180 |
if len(self.failures) == 1: |
| 181 |
text = u"one FAILED test" |
| 182 |
else: |
| 183 |
text = u"%d FAILED tests" % len(self.failures) |
| 184 |
first = False |
| 185 |
else: |
| 186 |
text = u'' |
| 187 |
first = True |
| 188 |
good_count = (self.total_count - self.skip_count |
| 189 |
- len(self.failures)) |
| 190 |
if good_count: |
| 191 |
if first: |
| 192 |
if good_count == 1: |
| 193 |
text += u"one good test" |
| 194 |
else: |
| 195 |
text += u"%d good tests" % good_count |
| 196 |
first = False |
| 197 |
else: |
| 198 |
if good_count == 1: |
| 199 |
text += u", one good" |
| 200 |
else: |
| 201 |
text += u", %d good" % good_count |
| 202 |
if self.skip_count: |
| 203 |
if first: |
| 204 |
if self.skip_count == 1: |
| 205 |
text += u"one skipped test" |
| 206 |
else: |
| 207 |
text += u"%d skipped tests" % self.skip_count |
| 208 |
first = False |
| 209 |
else: |
| 210 |
if self.skip_count == 1: |
| 211 |
text += u", one skipped" |
| 212 |
else: |
| 213 |
text += u", %d skipped" % self.skip_count |
| 214 |
if first: |
| 215 |
text = u"No test" |
| 216 |
summary = (u"\nSummary: %s in %.2f seconds.\n" |
| 217 |
% (text, time.time() - start_time)) |
| 218 |
write(summary) |
| 219 |
if self.save: |
| 220 |
write = open(self.save, u'w').write |
| 221 |
for ordinal in self.failures: |
| 222 |
write(u'%d\n' % ordinal) |
| 223 |
else: |
| 224 |
write = sys.stdout.write |
| 225 |
for (ordinal, prefix, function, arguments, stdout, stderr, |
| 226 |
tracing) in self.failures: |
| 227 |
write(u'\n' + u'=' * WIDTH + u'\n') |
| 228 |
write(u'%d. %s\n' % (ordinal, prefix)) |
| 229 |
if function and function.__name__ != os.path.basename(prefix): |
| 230 |
write(u" Function %s\n" % function.__name__) |
| 231 |
if arguments: |
| 232 |
for counter, argument in enumerate(arguments): |
| 233 |
write(u" Arg %d = %r\n" % (counter + 1, argument)) |
| 234 |
for buffer, titre in ((stdout, u'STDOUT'), (stderr, u'STDERR')): |
| 235 |
if buffer: |
| 236 |
write(u'\n' + titre + u' >>>\n') |
| 237 |
write(buffer) |
| 238 |
if not buffer.endswith(u'\n'): |
| 239 |
write(u'\n') |
| 240 |
write(u'-' * WIDTH + u'\n') |
| 241 |
write(tracing) |
| 242 |
if self.failures: |
| 243 |
write(summary) |
| 244 |
sys.exit(1) |
| 245 |
|
| 246 |
def each_file(self, path): |
| 247 |
if os.path.isdir(path): |
| 248 |
stack = [path] |
| 249 |
while stack: |
| 250 |
directory = stack.pop(0) |
| 251 |
for base in sorted(os.listdir(directory)): |
| 252 |
file_name = os.path.join(directory, base) |
| 253 |
if base.startswith(self.prefix) and base.endswith(u'.py'): |
| 254 |
yield file_name |
| 255 |
elif os.path.isdir(file_name): |
| 256 |
stack.append(file_name) |
| 257 |
else: |
| 258 |
if not path.endswith(u'.py'): |
| 259 |
sys.exit("%s: Should have a `.py' suffix." % path) |
| 260 |
yield path |
| 261 |
|
| 262 |
def handle_module(self, prefix, module): |
| 263 |
collection = [] |
| 264 |
for name, objet in inspect.getmembers(module): |
| 265 |
if name.startswith(u'Test') and inspect.isclass(objet): |
| 266 |
if getattr(object, u'disabled', False): |
| 267 |
continue |
| 268 |
minimum = None |
| 269 |
for _, func in inspect.getmembers(objet, inspect.isfunction): |
| 270 |
number = func.__code__.co_firstlineno |
| 271 |
if minimum is None or number < minimum: |
| 272 |
minimum = number |
| 273 |
if minimum is not None: |
| 274 |
collection.append((minimum, name, objet, False)) |
| 275 |
elif name.startswith(u'test_') and inspect.isfunction(objet): |
| 276 |
code = objet.__code__ |
| 277 |
collection.append((code.co_firstlineno, name, objet, |
| 278 |
bool(code.co_flags & 32))) |
| 279 |
if not collection: |
| 280 |
return |
| 281 |
self.delayed_setup_module = None |
| 282 |
self.did_tests_in_module = False |
| 283 |
if hasattr(module, u'setup_module'): |
| 284 |
self.delayed_setup_module = module.setup_module, module |
| 285 |
for _, name, objet, generator in sorted(collection): |
| 286 |
self.delayed_setup_class = None |
| 287 |
self.did_tests_in_class = False |
| 288 |
if inspect.isclass(objet): |
| 289 |
if not getattr(object, u'disabled', False): |
| 290 |
self.handle_class(prefix + u'/' + name, objet) |
| 291 |
else: |
| 292 |
self.handle_function(prefix + u'/' + name, objet, |
| 293 |
generator, None) |
| 294 |
if self.did_tests_in_module and hasattr(module, u'teardown_module'): |
| 295 |
module.teardown_module(module) |
| 296 |
|
| 297 |
def handle_class(self, prefix, classe): |
| 298 |
collection = [] |
| 299 |
for name, func in inspect.getmembers(classe, inspect.isfunction): |
| 300 |
if name.startswith(u'test_'): |
| 301 |
code = func.__code__ |
| 302 |
collection.append((code.co_firstlineno, name, func, |
| 303 |
bool(code.co_flags & inspect.CO_GENERATOR))) |
| 304 |
if not collection: |
| 305 |
return |
| 306 |
|
| 307 |
instance = classe() |
| 308 |
if hasattr(instance, u'setup_class'): |
| 309 |
self.delayed_setup_module = instance.setup_class, classe |
| 310 |
for _, name, method, generator in sorted(collection): |
| 311 |
self.handle_function(prefix + u'/' + name, getattr(instance, name), |
| 312 |
generator, instance) |
| 313 |
if self.did_tests_in_class and hasattr(instance, u'teardown_class'): |
| 314 |
instance.teardown_class(classe) |
| 315 |
|
| 316 |
def handle_function(self, prefix, function, generator, instance): |
| 317 |
collection = [] |
| 318 |
if generator: |
| 319 |
|
| 320 |
try: |
| 321 |
for counter, arguments in enumerate(function()): |
| 322 |
collection.append((prefix + u'/' + str(counter + 1), |
| 323 |
arguments[0], arguments[1:])) |
| 324 |
except Skipped: |
| 325 |
return |
| 326 |
else: |
| 327 |
collection.append((prefix, function, ())) |
| 328 |
for prefix, function, arguments in collection: |
| 329 |
self.launch_test(prefix, function, arguments, instance) |
| 330 |
|
| 331 |
def launch_test(self, prefix, function, arguments, instance): |
| 332 |
|
| 333 |
if (self.exclusion is not None and self.exclusion.search(prefix) |
| 334 |
or self.pattern is not None and not self.pattern.search(prefix) |
| 335 |
or self.ordinals and self.total_count + 1 not in self.ordinals): |
| 336 |
self.mark_progression(prefix, None) |
| 337 |
return |
| 338 |
|
| 339 |
if self.delayed_setup_module is not None: |
| 340 |
self.delayed_setup_module[0](self.delayed_setup_module[1]) |
| 341 |
self.delayed_setup_module = None |
| 342 |
if self.delayed_setup_class is not None: |
| 343 |
self.delayed_setup_class[0](self.delayed_setup_class[1]) |
| 344 |
self.delayed_setup_class = None |
| 345 |
if instance is not None and hasattr(instance, u'setup_method'): |
| 346 |
instance.setup_method(function) |
| 347 |
if self.capture: |
| 348 |
saved_stdout = sys.stdout |
| 349 |
saved_stderr = sys.stderr |
| 350 |
stdout = sys.stdout = StringIO() |
| 351 |
stderr = sys.stderr = StringIO() |
| 352 |
self.activate_profiling() |
| 353 |
try: |
| 354 |
try: |
| 355 |
function(*arguments) |
| 356 |
except Exit: |
| 357 |
success = False |
| 358 |
raise |
| 359 |
except Failed: |
| 360 |
success = False |
| 361 |
except Skipped: |
| 362 |
success = None |
| 363 |
except KeyboardInterrupt: |
| 364 |
success = None |
| 365 |
raise Exit("Interruption!") |
| 366 |
except: |
| 367 |
success = False |
| 368 |
else: |
| 369 |
success = True |
| 370 |
finally: |
| 371 |
self.deactivate_profiling() |
| 372 |
if self.capture: |
| 373 |
sys.stdout = saved_stdout |
| 374 |
sys.stderr = saved_stderr |
| 375 |
stdout = stdout.getvalue() |
| 376 |
stderr = stderr.getvalue() |
| 377 |
else: |
| 378 |
stdout = None |
| 379 |
stderr = None |
| 380 |
self.mark_progression(prefix, success) |
| 381 |
if success is False: |
| 382 |
if self.save: |
| 383 |
self.failures.append(self.total_count) |
| 384 |
else: |
| 385 |
tracing = StringIO() |
| 386 |
traceback.print_exc(file=tracing) |
| 387 |
self.failures.append( |
| 388 |
(self.total_count, prefix, function, arguments, |
| 389 |
stdout, stderr, tracing.getvalue())) |
| 390 |
if instance is not None and hasattr(instance, u'teardown_method'): |
| 391 |
instance.teardown_method(function) |
| 392 |
self.did_tests_in_class = True |
| 393 |
self.did_tests_in_module = True |
| 394 |
if success is not None and len(self.failures) == self.limit: |
| 395 |
raise Limit_Reached |
| 396 |
|
| 397 |
def mark_progression(self, prefix, success): |
| 398 |
self.total_count += 1 |
| 399 |
if self.verbose: |
| 400 |
if success is None: |
| 401 |
self.skip_count += 1 |
| 402 |
mark = u"skipped" |
| 403 |
elif success: |
| 404 |
mark = u"ok" |
| 405 |
else: |
| 406 |
mark = u"FAILED" |
| 407 |
sys.stderr.write(u'%5d. [%s] %s\n' % (self.total_count, prefix, mark)) |
| 408 |
else: |
| 409 |
if success is None: |
| 410 |
self.skip_count += 1 |
| 411 |
mark = u's' |
| 412 |
elif success: |
| 413 |
mark = u'.' |
| 414 |
else: |
| 415 |
mark = 'E' |
| 416 |
if self.column == WIDTH: |
| 417 |
sys.stderr.write(u'\n') |
| 418 |
self.column = 0 |
| 419 |
if not self.column: |
| 420 |
if self.counter: |
| 421 |
text = u'%5d ' % (self.counter + 1) |
| 422 |
else: |
| 423 |
text = self.identifier + u' ' |
| 424 |
sys.stderr.write(text) |
| 425 |
self.column = len(text) |
| 426 |
sys.stderr.write(mark) |
| 427 |
sys.stderr.flush() |
| 428 |
self.column += 1 |
| 429 |
self.counter += 1 |
| 430 |
sys.stderr.flush() |
| 431 |
|
| 432 |
def activate_profiling(self): |
| 433 |
if self.profiler is not None: |
| 434 |
self.profiler.enable(subcalls=True, builtins=True) |
| 435 |
|
| 436 |
def deactivate_profiling(self): |
| 437 |
if self.profiler is not None: |
| 438 |
self.profiler.disable() |
| 439 |
|
| 440 |
class Friendly_StreamWriter: |
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
def __init__(self, stream): |
| 445 |
import codecs, locale |
| 446 |
writer = codecs.getwriter(locale.getpreferredencoding()) |
| 447 |
self.stream = writer(stream, 'backslashreplace') |
| 448 |
|
| 449 |
def flush(self): |
| 450 |
self.stream.flush() |
| 451 |
|
| 452 |
def write(self, text): |
| 453 |
if not isinstance(text, unicode): |
| 454 |
text = text.encode('UTF-8') |
| 455 |
self.stream.write(text) |
| 456 |
|
| 457 |
def writelines(self, lines): |
| 458 |
for line in lines: |
| 459 |
self.write(line) |
| 460 |
|
| 461 |
run = Main() |
| 462 |
main = run.main |
| 463 |
|
| 464 |
class Exit(Exception): pass |
| 465 |
|
| 466 |
class Failed(Exception): pass |
| 467 |
|
| 468 |
class NotRaised(Exception): pass |
| 469 |
|
| 470 |
class Skipped(Exception): pass |
| 471 |
|
| 472 |
class py: |
| 473 |
|
| 474 |
class test: |
| 475 |
|
| 476 |
@staticmethod |
| 477 |
def exit(message="Unknown reason"): |
| 478 |
raise Exit(message) |
| 479 |
|
| 480 |
@staticmethod |
| 481 |
def fail(message="Unknown reason"): |
| 482 |
raise Failed(message) |
| 483 |
|
| 484 |
@staticmethod |
| 485 |
def skip(message="Unknown reason"): |
| 486 |
raise Skipped(message) |
| 487 |
|
| 488 |
@staticmethod |
| 489 |
def raises(expected, *args, **kws): |
| 490 |
try: |
| 491 |
if isinstance(args[0], unicode) and not kws: |
| 492 |
eval(args[0]) |
| 493 |
else: |
| 494 |
args[0](*args[1:], **kws) |
| 495 |
except expected: |
| 496 |
return |
| 497 |
else: |
| 498 |
raise NotRaised(u"Exception did not happen.") |
| 499 |
|
| 500 |
if __name__ == u'__main__': |
| 501 |
main(*sys.argv[1:]) |