Debian Codegraph @

tools/runtests.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Copyright (c) 2006, 2007, 2008, 2009, 2010 SymPy Development Team
2 # Copyright (c) 2010 Nicolas Pourcelot
3 """
4 This is our testing framework.
5
6 Goals:
7
8 * it should be compatible with py.test and operate very similarly (or
9 identically)
10 * doesn't require any external dependencies
11 * preferably all the functionality should be in this file only
12 * no magic, just import the test file and execute the test functions, that's it
13 * portable
14
15 """
16
17 from runpy import run_path
18 import os
19 import sys
20 import inspect
21 import traceback
22 import pdb
23 from fnmatch import fnmatch
24 from timeit import default_timer as clock
25 import doctest as pdoctest # avoid clashing with our doctest() function
26 from doctest import DocTestFinder
27 import re as pre
28
29 ROOT_PATH = '..' # WxGeometrie path
30
31 def sys_normcase(f):
32 if sys_case_insensitive:
33 return f.lower()
34 return f
35
36 def convert_to_native_paths(lst):
37 """
38 Converts a list of '/' separated paths into a list of
39 native (os.sep separated) paths and converts to lowercase
40 if the system is case insensitive.
41 """
42 newlst = []
43 for i, rv in enumerate(lst):
44 rv = os.path.join(*rv.split("/"))
45 # on windows the slash after the colon is dropped
46 if sys.platform == "win32":
47 pos = rv.find(':')
48 if pos != -1:
49 if rv[pos+1] != '\\':
50 rv = rv[:pos+1] + '\\' + rv[pos+1:]
51 newlst.append(sys_normcase(rv))
52 return newlst
53
54 def get_root_dir():
55 """
56 Returns the root directory and set the global value
57 indicating whether the system is case sensitive or not.
58 """
59 global sys_case_insensitive
60
61 this_file = os.path.abspath(__file__)
62 root_dir = os.path.join(os.path.dirname(this_file), ROOT_PATH)
63 root_dir = os.path.normpath(root_dir)
64 sys_case_insensitive = (os.path.isdir(root_dir) and
65 os.path.isdir(root_dir.lower()) and
66 os.path.isdir(root_dir.upper()))
67 return sys_normcase(root_dir)
68
69
70
71 def isgeneratorfunction(object):
72 """
73 Return true if the object is a user-defined generator function.
74
75 Generator function objects provides same attributes as functions.
76
77 See isfunction.__doc__ for attributes listing.
78
79 Adapted from Python 2.6.
80 """
81 CO_GENERATOR = 0x20
82 if (inspect.isfunction(object) or inspect.ismethod(object)) and \
83 object.__code__.co_flags & CO_GENERATOR:
84 return True
85 return False
86
87 def setup_pprint():
88 from sympy import pprint_use_unicode, init_printing
89
90 # force pprint to be in ascii mode in doctests
91 pprint_use_unicode(False)
92
93 # hook our nice, hash-stable strprinter
94 init_printing(pretty_print=False)
95
96 def test(*paths, **kwargs):
97 """
98 Run all tests in test_*.py files which match any of the given
99 strings in `paths` or all tests if paths=[].
100
101 Notes:
102 o if sort=False, tests are run in random order (not default).
103 o paths can be entered in native system format or in unix,
104 forward-slash format.
105
106 Examples:
107
108 >> import sympy
109
110 Run all tests:
111 >> sympy.test()
112
113 Run one file:
114 >> sympy.test("sympy/core/tests/test_basic.py")
115 >> sympy.test("_basic")
116
117 Run all tests in sympy/functions/ and some particular file:
118 >> sympy.test("sympy/core/tests/test_basic.py", "sympy/functions")
119
120 Run all tests in sympy/core and sympy/utilities:
121 >> sympy.test("/core", "/util")
122 """
123 verbose = kwargs.get("verbose", False)
124 tb = kwargs.get("tb", "short")
125 kw = kwargs.get("kw", "")
126 blacklist = kwargs.get("blacklist", [])
127 blacklist = convert_to_native_paths(blacklist)
128 post_mortem = kwargs.get("pdb", False)
129 colors = kwargs.get("colors", True)
130 sort = kwargs.get("sort", True)
131 r = PyTestReporter(verbose, tb, colors)
132 t = SymPyTests(r, kw, post_mortem)
133
134 test_files = t.get_test_files('.')
135 not_blacklisted = [f for f in test_files
136 if not any(b in f for b in blacklist)]
137 if len(paths) == 0:
138 t._testfiles.extend(not_blacklisted)
139 else:
140 paths = convert_to_native_paths(paths)
141 matched = []
142 for f in not_blacklisted:
143 basename = os.path.basename(f)
144 for p in paths:
145 if p in f or fnmatch(basename, p):
146 matched.append(f)
147 break
148 t._testfiles.extend(matched)
149
150 return t.test(sort=sort)
151
152 def doctest(*paths, **kwargs):
153 """
154 Runs doctests in all *py files in the sympy directory which match
155 any of the given strings in `paths` or all tests if paths=[].
156
157 Note:
158 o paths can be entered in native system format or in unix,
159 forward-slash format.
160 o files that are on the blacklist can be tested by providing
161 their path; they are only excluded if no paths are given.
162
163 Examples:
164
165 >> import sympy
166
167 Run all tests:
168 >> sympy.doctest()
169
170 Run one file:
171 >> sympy.doctest("sympy/core/basic.py")
172 >> sympy.doctest("polynomial.txt")
173
174 Run all tests in sympy/functions/ and some particular file:
175 >> sympy.doctest("/functions", "basic.py")
176
177 Run any file having polynomial in its name, doc/src/modules/polynomial.txt,
178 sympy\functions\special\polynomials.py, and sympy\polys\polynomial.py:
179 >> sympy.doctest("polynomial")
180 """
181 normal = kwargs.get("normal", False)
182 verbose = kwargs.get("verbose", False)
183 blacklist = kwargs.get("blacklist", [])
184 blacklist.extend([
185 "sympy/thirdparty/pyglet", # segfaults
186 "doc/src/modules/mpmath", # needs to be fixed upstream
187 "sympy/mpmath", # needs to be fixed upstream
188 "doc/src/modules/plotting.txt", # generates live plots
189 "sympy/plotting", # generates live plots
190 "sympy/utilities/compilef.py", # needs tcc
191 "sympy/utilities/autowrap.py", # needs installed compiler
192 "sympy/galgebra/GA.py", # needs numpy
193 "sympy/galgebra/latex_ex.py", # needs numpy
194 "sympy/conftest.py", # needs py.test
195 "sympy/utilities/benchmarking.py", # needs py.test
196 "doc/src/modules/polys", # very time consuming
197 ])
198 blacklist = convert_to_native_paths(blacklist)
199
200 r = PyTestReporter(verbose)
201 t = SymPyDocTests(r, normal)
202
203 test_files = t.get_test_files('wxgeometrie')
204 # print test_files, 'voila!'
205 # exit()
206 not_blacklisted = [f for f in test_files
207 if not any(b in f for b in blacklist)]
208 if len(paths) == 0:
209 t._testfiles.extend(not_blacklisted)
210 else:
211 # take only what was requested...but not blacklisted items
212 # and allow for partial match anywhere or fnmatch of name
213 paths = convert_to_native_paths(paths)
214 matched = []
215 for f in not_blacklisted:
216 basename = os.path.basename(f)
217 for p in paths:
218 if p in f or fnmatch(basename, p):
219 matched.append(f)
220 break
221 t._testfiles.extend(matched)
222
223 # run the tests and record the result for this *py portion of the tests
224 if t._testfiles:
225 failed = not t.test()
226 else:
227 failed = False
228
229 # test *txt files only if we are running python newer than 2.4
230 if sys.version_info[:2] > (2,4):
231
232 # N.B.
233 # --------------------------------------------------------------------
234 # Here we test *.txt files at or below doc/src. Code from these must
235 # be self supporting in terms of imports since there is no importing
236 # of necessary modules by doctest.testfile. If you try to pass *.py
237 # files through this they might fail because they will lack the needed
238 # imports and smarter parsing that can be done with source code.
239 #
240 test_files = t.get_test_files('doc/src', '*.txt', init_only=False)
241 test_files.sort()
242
243 not_blacklisted = [f for f in test_files
244 if not any(b in f for b in blacklist)]
245
246 if len(paths) == 0:
247 matched = not_blacklisted
248 else:
249 # Take only what was requested as long as it's not on the blacklist.
250 # Paths were already made native in *py tests so don't repeat here.
251 # There's no chance of having a *py file slip through since we
252 # only have *txt files in test_files.
253 matched = []
254 for f in not_blacklisted:
255 basename = os.path.basename(f)
256 for p in paths:
257 if p in f or fnmatch(basename, p):
258 matched.append(f)
259 break
260
261 setup_pprint()
262 first_report = True
263 for txt_file in matched:
264 if not os.path.isfile(txt_file):
265 continue
266 old_displayhook = sys.displayhook
267 try:
268 out = pdoctest.testfile(txt_file, module_relative=False,
269 optionflags=pdoctest.ELLIPSIS | \
270 pdoctest.NORMALIZE_WHITESPACE)
271 finally:
272 # make sure we return to the original displayhook in case some
273 # doctest has changed that
274 sys.displayhook = old_displayhook
275
276 txtfailed, tested = out
277 if tested:
278 failed = txtfailed or failed
279 if first_report:
280 first_report = False
281 msg = 'txt doctests start'
282 lhead = '='*((80 - len(msg))//2 - 1)
283 rhead = '='*(79 - len(msg) - len(lhead) - 1)
284 print(' '.join([lhead, msg, rhead]))
285 print()
286 # use as the id, everything past the first 'sympy'
287 file_id = txt_file[txt_file.find('sympy') + len('sympy') + 1:]
288 print(file_id, end=' ') # get at least the name out so it is know who is being tested
289 wid = 80 - len(file_id) - 1 #update width
290 test_file = '[%s]' % (tested)
291 report = '[%s]' % (txtfailed or 'OK')
292 print(''.join([test_file,' '*(wid-len(test_file)-len(report)), report]))
293
294 # the doctests for *py will have printed this message already if there was
295 # a failure, so now only print it if there was intervening reporting by
296 # testing the *txt as evidenced by first_report no longer being True.
297 if not first_report and failed:
298 print()
299 print("DO *NOT* COMMIT!")
300 return not failed
301
302 class SymPyTests(object):
303
304 def __init__(self, reporter, kw="", post_mortem=False):
305 self._post_mortem = post_mortem
306 self._kw = kw
307 self._count = 0
308 self._root_dir = root_dir
309 self._reporter = reporter
310 self._reporter.root_dir(self._root_dir)
311 self._testfiles = []
312
313 def test(self, sort=False):
314 """
315 Runs the tests returning True if all tests pass, otherwise False.
316
317 If sort=False run tests in random order.
318 """
319 if sort:
320 self._testfiles.sort()
321 else:
322 from random import shuffle
323 shuffle(self._testfiles)
324 self._reporter.start()
325 for f in self._testfiles:
326 try:
327 self.test_file(f)
328 except KeyboardInterrupt:
329 print(" interrupted by user")
330 break
331 return self._reporter.finish()
332
333 def test_file(self, filename):
334 name = "test%d" % self._count
335 name = os.path.splitext(os.path.basename(filename))[0]
336 self._count += 1
337 gl = {'__file__':filename}
338 try:
339 gl = run_path(filename, gl)
340 except (ImportError, SyntaxError):
341 self._reporter.import_error(filename, sys.exc_info())
342 return
343 pytestfile = ""
344 if "XFAIL" in gl:
345 pytestfile = inspect.getsourcefile(gl["XFAIL"])
346 disabled = gl.get("disabled", False)
347 if disabled:
348 funcs = []
349 else:
350 # we need to filter only those functions that begin with 'test_'
351 # that are defined in the testing file or in the file where
352 # is defined the XFAIL decorator
353 funcs = [gl[f] for f in gl if f.startswith("test_") and
354 (inspect.isfunction(gl[f])
355 or inspect.ismethod(gl[f])) and
356 (inspect.getsourcefile(gl[f]) == filename or
357 inspect.getsourcefile(gl[f]) == pytestfile)]
358 # Sorting of XFAILed functions isn't fixed yet :-(
359 funcs.sort(key=lambda x: inspect.getsourcelines(x)[1])
360 i = 0
361 while i is not len(funcs):
362 if isgeneratorfunction(funcs[i]):
363 # some tests can be generators, that return the actual
364 # test functions. We unpack it below:
365 f = funcs.pop(i)
366 for fg in f():
367 func = fg[0]
368 args = fg[1:]
369 fgw = lambda: func(*args)
370 funcs.insert(i, fgw)
371 i += 1
372 else:
373 i += 1
374 # drop functions that are not selected with the keyword expression:
375 funcs = [x for x in funcs if self.matches(x)]
376
377 if not funcs:
378 return
379 self._reporter.entering_filename(filename, len(funcs))
380 for f in funcs:
381 self._reporter.entering_test(f)
382 try:
383 f()
384 except KeyboardInterrupt:
385 raise
386 except:
387 t, v, tr = sys.exc_info()
388 if t is AssertionError:
389 self._reporter.test_fail((t, v, tr))
390 if self._post_mortem:
391 pdb.post_mortem(tr)
392 elif t.__name__ == "Skipped":
393 self._reporter.test_skip()
394 elif t.__name__ == "XFail":
395 self._reporter.test_xfail()
396 elif t.__name__ == "XPass":
397 self._reporter.test_xpass(v)
398 else:
399 self._reporter.test_exception((t, v, tr))
400 if self._post_mortem:
401 pdb.post_mortem(tr)
402 else:
403 self._reporter.test_pass()
404 self._reporter.leaving_filename()
405
406 def matches(self, x):
407 """
408 Does the keyword expression self._kw match "x"? Returns True/False.
409
410 Always returns True if self._kw is "".
411 """
412 if self._kw == "":
413 return True
414 return x.__name__.find(self._kw) != -1
415
416 def get_test_files(self, dir, pat = 'test_*.py'):
417 """
418 Returns the list of test_*.py (default) files at or below directory
419 `dir` relative to the sympy home directory.
420 """
421 dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
422
423 g = []
424 for path, folders, files in os.walk(dir):
425 g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)])
426
427 return [sys_normcase(gi) for gi in g]
428
429 class SymPyDocTests(object):
430
431 def __init__(self, reporter, normal):
432 self._count = 0
433 self._root_dir = root_dir
434 self._reporter = reporter
435 self._reporter.root_dir(self._root_dir)
436 self._normal = normal
437
438 self._testfiles = []
439
440 def test(self):
441 """
442 Runs the tests and returns True if all tests pass, otherwise False.
443 """
444 self._reporter.start()
445 for f in self._testfiles:
446 try:
447 self.test_file(f)
448 except KeyboardInterrupt:
449 print(" interrupted by user")
450 break
451 return self._reporter.finish()
452
453 def test_file(self, filename):
454
455 import unittest
456 from io import StringIO
457
458 rel_name = filename[len(self._root_dir)+1:]
459 module = rel_name.replace(os.sep, '.')[:-3]
460 setup_pprint()
461 try:
462 module = pdoctest._normalize_module(module)
463 tests = SymPyDocTestFinder().find(module)
464 except:
465 self._reporter.import_error(filename, sys.exc_info())
466 return
467
468 tests = [test for test in tests if len(test.examples) > 0]
469 # By default (except for python 2.4 in which it was broken) tests
470 # are sorted by alphabetical order by function name. We sort by line number
471 # so one can edit the file sequentially from bottom to top...HOWEVER
472 # if there are decorated functions, their line numbers will be too large
473 # and for now one must just search for these by text and function name.
474 tests.sort(key=lambda x: -x.lineno)
475
476 if not tests:
477 return
478 self._reporter.entering_filename(filename, len(tests))
479 for test in tests:
480 assert len(test.examples) != 0
481 runner = pdoctest.DocTestRunner(optionflags=pdoctest.ELLIPSIS | \
482 pdoctest.NORMALIZE_WHITESPACE)
483 old = sys.stdout
484 new = StringIO()
485 sys.stdout = new
486 # If the testing is normal, the doctests get importing magic to
487 # provide the global namespace. If not normal (the default) then
488 # then must run on their own; all imports must be explicit within
489 # a function's docstring. Once imported that import will be
490 # available to the rest of the tests in a given function's
491 # docstring (unless clear_globs=True below).
492 if not self._normal:
493 test.globs = {}
494 # if this is uncommented then all the test would get is what
495 # comes by default with a "from sympy import *"
496 #exec('from sympy import *') in test.globs
497 try:
498 f, t = runner.run(test, out=new.write, clear_globs=False)
499 finally:
500 sys.stdout = old
501 if f > 0:
502 self._reporter.doctest_fail(test.name, new.getvalue())
503 else:
504 self._reporter.test_pass()
505 self._reporter.leaving_filename()
506
507 def get_test_files(self, dir, pat='*.py', init_only=True):
508 """
509 Returns the list of *py files (default) from which docstrings
510 will be tested which are at or below directory `dir`. By default,
511 only those that have an __init__.py in their parent directory
512 and do not start with `test_` will be included.
513 """
514 def importable(x):
515 """
516 Checks if given pathname x is an importable module by checking for
517 __init__.py file.
518
519 Returns True/False.
520
521 Currently we only test if the __init__.py file exists in the
522 directory with the file "x" (in theory we should also test all the
523 parent dirs).
524 """
525 init_py = os.path.join(os.path.dirname(x), "__init__.py")
526 return os.path.exists(init_py)
527
528 dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
529
530 g = []
531 for path, folders, files in os.walk(dir):
532 g.extend([os.path.join(path, f) for f in files
533 if not f.startswith('test_') and fnmatch(f, pat)])
534 if init_only:
535 # skip files that are not importable (i.e. missing __init__.py)
536 g = [x for x in g if importable(x)]
537
538 return [sys_normcase(gi) for gi in g]
539
540 class SymPyDocTestFinder(DocTestFinder):
541 """
542 A class used to extract the DocTests that are relevant to a given
543 object, from its docstring and the docstrings of its contained
544 objects. Doctests can currently be extracted from the following
545 object types: modules, functions, classes, methods, staticmethods,
546 classmethods, and properties.
547
548 Modified from doctest's version by looking harder for code in the
549 case that it looks like the the code comes from a different module.
550 In the case of decorated functions (e.g. @vectorize) they appear
551 to come from a different module (e.g. multidemensional) even though
552 their code is not there.
553 """
554
555 def _find(self, tests, obj, name, module, source_lines, globs, seen):
556 """
557 Find tests for the given object and any contained objects, and
558 add them to `tests`.
559 """
560 if self._verbose:
561 print('Finding tests in %s' % name)
562
563 # If we've already processed this object, then ignore it.
564 if id(obj) in seen:
565 return
566 seen[id(obj)] = 1
567
568 # Find a test for this object, and add it to the list of tests.
569 test = self._get_test(obj, name, module, globs, source_lines)
570 if test is not None:
571 tests.append(test)
572
573 # Look for tests in a module's contained objects.
574 if inspect.ismodule(obj) and self._recurse:
575 for rawname, val in obj.__dict__.items():
576 # Recurse to functions & classes.
577 if inspect.isfunction(val) or inspect.isclass(val):
578 in_module = self._from_module(module, val)
579 if not in_module:
580 # double check in case this function is decorated
581 # and just appears to come from a different module.
582 pat = r'\s*(def|class)\s+%s\s*\(' % rawname
583 PAT = pre.compile(pat)
584 in_module = any(PAT.match(line) for line in source_lines)
585 if in_module:
586 try:
587 valname = '%s.%s' % (name, rawname)
588 self._find(tests, val, valname, module, source_lines, globs, seen)
589 except:
590 pass
591
592 # Look for tests in a module's __test__ dictionary.
593 if inspect.ismodule(obj) and self._recurse:
594 for valname, val in getattr(obj, '__test__', {}).items():
595 if not isinstance(valname, str):
596 raise ValueError("SymPyDocTestFinder.find: __test__ keys "
597 "must be strings: %r" %
598 (type(valname),))
599 if not (inspect.isfunction(val) or inspect.isclass(val) or
600 inspect.ismethod(val) or inspect.ismodule(val) or
601 isinstance(val, str)):
602 raise ValueError("SymPyDocTestFinder.find: __test__ values "
603 "must be strings, functions, methods, "
604 "classes, or modules: %r" %
605 (type(val),))
606 valname = '%s.__test__.%s' % (name, valname)
607 self._find(tests, val, valname, module, source_lines,
608 globs, seen)
609
610 # Look for tests in a class's contained objects.
611 if inspect.isclass(obj) and self._recurse:
612 for valname, val in obj.__dict__.items():
613 # Special handling for staticmethod/classmethod.
614 if isinstance(val, staticmethod):
615 val = getattr(obj, valname)
616 if isinstance(val, classmethod):
617 val = getattr(obj, valname).__func__
618
619 # Recurse to methods, properties, and nested classes.
620 if (inspect.isfunction(val) or
621 inspect.isclass(val) or
622 isinstance(val, property)):
623 in_module = self._from_module(module, val)
624 if not in_module:
625 # "double check" again
626 pat = r'\s*(def|class)\s+%s\s*\(' % valname
627 PAT = pre.compile(pat)
628 in_module = any(PAT.match(line) for line in source_lines)
629 if in_module:
630 valname = '%s.%s' % (name, valname)
631 self._find(tests, val, valname, module, source_lines,
632 globs, seen)
633
634 def _get_test(self, obj, name, module, globs, source_lines):
635 """
636 Return a DocTest for the given object, if it defines a docstring;
637 otherwise, return None.
638 """
639 # Extract the object's docstring. If it doesn't have one,
640 # then return None (no test for this object).
641 if isinstance(obj, str):
642 docstring = obj
643 else:
644 try:
645 if obj.__doc__ is None:
646 docstring = ''
647 else:
648 docstring = obj.__doc__
649 if not isinstance(docstring, str):
650 docstring = str(docstring)
651 except (TypeError, AttributeError):
652 docstring = ''
653
654 # Find the docstring's location in the file.
655 lineno = self._find_lineno(obj, source_lines)
656
657 if lineno is None:
658 # if None, then it wasn't really in this source
659 return None
660
661 # Don't bother if the docstring is empty.
662 if self._exclude_empty and not docstring:
663 return None
664
665 # Return a DocTest for this object.
666 if module is None:
667 filename = None
668 else:
669 filename = getattr(module, '__file__', module.__name__)
670 if filename[-4:] in (".pyc", ".pyo"):
671 filename = filename[:-1]
672 return self._parser.get_doctest(docstring, globs, name,
673 filename, lineno)
674
675 class Reporter(object):
676 """
677 Parent class for all reporters.
678 """
679 pass
680
681 class PyTestReporter(Reporter):
682 """
683 Py.test like reporter. Should produce output identical to py.test.
684 """
685
686 def __init__(self, verbose=False, tb="short", colors=True):
687 self._verbose = verbose
688 self._tb_style = tb
689 self._colors = colors
690 self._xfailed = 0
691 self._xpassed = []
692 self._failed = []
693 self._failed_doctest = []
694 self._passed = 0
695 self._skipped = 0
696 self._exceptions = []
697
698 # this tracks the x-position of the cursor (useful for positioning
699 # things on the screen), without the need for any readline library:
700 self._write_pos = 0
701 self._line_wrap = False
702
703 def root_dir(self, dir):
704 self._root_dir = dir
705
706 def write(self, text, color="", align="left", width=80):
707 """
708 Prints a text on the screen.
709
710 It uses sys.stdout.write(), so no readline library is necessary.
711
712 color ... choose from the colors below, "" means default color
713 align ... left/right, left is a normal print, right is aligned on the
714 right hand side of the screen, filled with " " if necessary
715 width ... the screen width
716 """
717 color_templates = (
718 ("Black" , "0;30"),
719 ("Red" , "0;31"),
720 ("Green" , "0;32"),
721 ("Brown" , "0;33"),
722 ("Blue" , "0;34"),
723 ("Purple" , "0;35"),
724 ("Cyan" , "0;36"),
725 ("LightGray" , "0;37"),
726 ("DarkGray" , "1;30"),
727 ("LightRed" , "1;31"),
728 ("LightGreen" , "1;32"),
729 ("Yellow" , "1;33"),
730 ("LightBlue" , "1;34"),
731 ("LightPurple" , "1;35"),
732 ("LightCyan" , "1;36"),
733 ("White" , "1;37"), )
734
735 colors = {}
736
737 for name, value in color_templates:
738 colors[name] = value
739 c_normal = '\033[0m'
740 c_color = '\033[%sm'
741
742 if align == "right":
743 if self._write_pos+len(text) > width:
744 # we don't fit on the current line, create a new line
745 self.write("\n")
746 self.write(" "*(width-self._write_pos-len(text)))
747
748 if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
749 # the stdout is not a terminal, this for example happens if the
750 # output is piped to less, e.g. "bin/test | less". In this case,
751 # the terminal control sequences would be printed verbatim, so
752 # don't use any colors.
753 color = ""
754 if sys.platform == "win32":
755 # Windows consoles don't support ANSI escape sequences
756 color = ""
757
758 if self._line_wrap:
759 if text[0] != "\n":
760 sys.stdout.write("\n")
761
762 if color == "":
763 sys.stdout.write(text)
764 else:
765 sys.stdout.write("%s%s%s" % (c_color % colors[color], text, c_normal))
766 sys.stdout.flush()
767 l = text.rfind("\n")
768 if l == -1:
769 self._write_pos += len(text)
770 else:
771 self._write_pos = len(text)-l-1
772 self._line_wrap = self._write_pos >= width
773 self._write_pos %= width
774
775 def write_center(self, text, delim="="):
776 width = 80
777 if text != "":
778 text = " %s " % text
779 idx = (width-len(text)) // 2
780 t = delim*idx + text + delim*(width-idx-len(text))
781 self.write(t+"\n")
782
783 def write_exception(self, e, val, tb):
784 t = traceback.extract_tb(tb)
785 # remove the first item, as that is always runtests.py
786 t = t[1:]
787 t = traceback.format_list(t)
788 self.write("".join(t))
789 t = traceback.format_exception_only(e, val)
790 self.write("".join(t))
791
792 def start(self):
793 self.write_center("test process starts")
794 executable = sys.executable
795 v = tuple(sys.version_info)
796 python_version = "%s.%s.%s-%s-%s" % v
797 self.write("executable: %s (%s)\n\n" % (executable, python_version))
798 self._t_start = clock()
799
800 def finish(self):
801 self._t_end = clock()
802 self.write("\n")
803 global text, linelen
804 text = "tests finished: %d passed, " % self._passed
805 linelen = len(text)
806 def add_text(mytext):
807 global text, linelen
808 """Break new text if too long."""
809 if linelen + len(mytext) > 80:
810 text += '\n'
811 linelen = 0
812 text += mytext
813 linelen += len(mytext)
814
815 if len(self._failed) > 0:
816 add_text("%d failed, " % len(self._failed))
817 if len(self._failed_doctest) > 0:
818 add_text("%d failed, " % len(self._failed_doctest))
819 if self._skipped > 0:
820 add_text("%d skipped, " % self._skipped)
821 if self._xfailed > 0:
822 add_text("%d expected to fail, " % self._xfailed)
823 if len(self._xpassed) > 0:
824 add_text("%d expected to fail but passed, " % len(self._xpassed))
825 if len(self._exceptions) > 0:
826 add_text("%d exceptions, " % len(self._exceptions))
827 add_text("in %.2f seconds" % (self._t_end - self._t_start))
828
829
830 if len(self._xpassed) > 0:
831 self.write_center("xpassed tests", "_")
832 for e in self._xpassed:
833 self.write("%s:%s\n" % (e[0], e[1]))
834 self.write("\n")
835
836 if self._tb_style != "no" and len(self._exceptions) > 0:
837 #self.write_center("These tests raised an exception", "_")
838 for e in self._exceptions:
839 filename, f, (t, val, tb) = e
840 self.write_center("", "_")
841 if f is None:
842 s = "%s" % filename
843 else:
844 s = "%s:%s" % (filename, f.__name__)
845 self.write_center(s, "_")
846 self.write_exception(t, val, tb)
847 self.write("\n")
848
849 if self._tb_style != "no" and len(self._failed) > 0:
850 #self.write_center("Failed", "_")
851 for e in self._failed:
852 filename, f, (t, val, tb) = e
853 self.write_center("", "_")
854 self.write_center("%s:%s" % (filename, f.__name__), "_")
855 self.write_exception(t, val, tb)
856 self.write("\n")
857
858 if self._tb_style != "no" and len(self._failed_doctest) > 0:
859 #self.write_center("Failed", "_")
860 for e in self._failed_doctest:
861 filename, msg = e
862 self.write_center("", "_")
863 self.write_center("%s" % filename, "_")
864 self.write(msg)
865 self.write("\n")
866
867 self.write_center(text)
868 ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \
869 len(self._failed_doctest) == 0
870 if not ok:
871 self.write("DO *NOT* COMMIT!\n")
872 return ok
873
874 def entering_filename(self, filename, n):
875 rel_name = filename[len(self._root_dir)+1:]
876 self._active_file = rel_name
877 self._active_file_error = False
878 self.write(rel_name)
879 self.write("[%d] " % n)
880
881 def leaving_filename(self):
882 if self._colors:
883 self.write(" ")
884 if self._active_file_error:
885 self.write("[FAIL]", "Red", align="right")
886 else:
887 self.write("[OK]", "Green", align="right")
888 self.write("\n")
889 if self._verbose:
890 self.write("\n")
891
892 def entering_test(self, f):
893 self._active_f = f
894 if self._verbose:
895 self.write("\n"+f.__name__+" ")
896
897 def test_xfail(self):
898 self._xfailed += 1
899 self.write("f")
900
901 def test_xpass(self, fname):
902 self._xpassed.append((self._active_file, fname))
903 self.write("X")
904
905 def test_fail(self, exc_info):
906 self._failed.append((self._active_file, self._active_f, exc_info))
907 self.write("F")
908 self._active_file_error = True
909
910 def doctest_fail(self, name, error_msg):
911 # the first line contains "******", remove it:
912 error_msg = "\n".join(error_msg.split("\n")[1:])
913 self._failed_doctest.append((name, error_msg))
914 self.write("F")
915 self._active_file_error = True
916
917 def test_pass(self):
918 self._passed += 1
919 if self._verbose:
920 self.write("ok")
921 else:
922 self.write(".")
923
924 def test_skip(self):
925 self._skipped += 1
926 self.write("s")
927
928 def test_exception(self, exc_info):
929 self._exceptions.append((self._active_file, self._active_f, exc_info))
930 self.write("E")
931 self._active_file_error = True
932
933 def import_error(self, filename, exc_info):
934 self._exceptions.append((filename, None, exc_info))
935 rel_name = filename[len(self._root_dir)+1:]
936 self.write(rel_name)
937 self.write("[?] Failed to import")
938 if self._colors:
939 self.write(" ")
940 self.write("[FAIL]", "Red", align="right")
941 self.write("\n")
942
943 root_dir = get_root_dir()