merge
[cython.git] / runtests.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import re
6 import gc
7 import codecs
8 import shutil
9 import unittest
10 import doctest
11 import operator
12 import tempfile
13 try:
14     from StringIO import StringIO
15 except ImportError:
16     from io import StringIO
17
18 try:
19     import cPickle as pickle
20 except ImportError:
21     import pickle
22
23
24 WITH_CYTHON = True
25
26 from distutils.dist import Distribution
27 from distutils.core import Extension
28 from distutils.command.build_ext import build_ext as _build_ext
29 distutils_distro = Distribution()
30
31 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr']
32 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
33
34 # Lists external modules, and a matcher matching tests
35 # which should be excluded if the module is not present.
36 EXT_DEP_MODULES = {
37     'numpy' : re.compile('.*\.numpy_.*').match,
38     'pstats' : re.compile('.*\.pstats_.*').match
39 }
40
41 def get_numpy_include_dirs():
42     import numpy
43     return [numpy.get_include()]
44
45 EXT_DEP_INCLUDES = [
46     # test name matcher , callable returning list
47     (re.compile('numpy_.*').match, get_numpy_include_dirs),
48 ]
49
50 VER_DEP_MODULES = {
51     (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
52                                           ]),
53     (3,): (operator.ge, lambda x: x in ['run.non_future_division',
54                                         'compile.extsetslice',
55                                         'compile.extdelslice']),
56 }
57
58 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
59 CFLAGS = os.getenv('CFLAGS', '').split()
60
61 class build_ext(_build_ext):
62     def build_extension(self, ext):
63         if ext.language == 'c++':
64             try:
65                 try: # Py2.7+ & Py3.2+ 
66                     compiler_obj = self.compiler_obj
67                 except AttributeError:
68                     compiler_obj = self.compiler
69                 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
70             except Exception:
71                 pass
72         _build_ext.build_extension(self, ext)
73
74 class ErrorWriter(object):
75     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
76     def __init__(self):
77         self.output = []
78         self.write = self.output.append
79
80     def _collect(self, collect_errors, collect_warnings):
81         s = ''.join(self.output)
82         result = []
83         for line in s.split('\n'):
84             match = self.match_error(line)
85             if match:
86                 is_warning, line, column, message = match.groups()
87                 if (is_warning and collect_warnings) or \
88                         (not is_warning and collect_errors):
89                     result.append( (int(line), int(column), message.strip()) )
90         result.sort()
91         return [ "%d:%d: %s" % values for values in result ]
92
93     def geterrors(self):
94         return self._collect(True, False)
95
96     def getwarnings(self):
97         return self._collect(False, True)
98
99     def getall(self):
100         return self._collect(True, True)
101
102 class TestBuilder(object):
103     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
104                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
105                  languages, test_bugs, fork):
106         self.rootdir = rootdir
107         self.workdir = workdir
108         self.selectors = selectors
109         self.exclude_selectors = exclude_selectors
110         self.annotate = annotate
111         self.cleanup_workdir = cleanup_workdir
112         self.cleanup_sharedlibs = cleanup_sharedlibs
113         self.with_pyregr = with_pyregr
114         self.cython_only = cython_only
115         self.languages = languages
116         self.test_bugs = test_bugs
117         self.fork = fork
118
119     def build_suite(self):
120         suite = unittest.TestSuite()
121         test_dirs = TEST_DIRS
122         filenames = os.listdir(self.rootdir)
123         filenames.sort()
124         for filename in filenames:
125             if not WITH_CYTHON and filename == "errors":
126                 # we won't get any errors without running Cython
127                 continue
128             path = os.path.join(self.rootdir, filename)
129             if os.path.isdir(path) and filename in test_dirs:
130                 if filename == 'pyregr' and not self.with_pyregr:
131                     continue
132                 suite.addTest(
133                     self.handle_directory(path, filename))
134         if sys.platform not in ['win32'] and sys.version_info[0] < 3:
135             # Non-Windows makefile, can't run Cython under Py3.
136             if [1 for selector in self.selectors if selector("embedded")]:
137                 suite.addTest(unittest.makeSuite(EmbedTest))
138         return suite
139
140     def handle_directory(self, path, context):
141         workdir = os.path.join(self.workdir, context)
142         if not os.path.exists(workdir):
143             os.makedirs(workdir)
144
145         expect_errors = (context == 'errors')
146         suite = unittest.TestSuite()
147         filenames = os.listdir(path)
148         filenames.sort()
149         for filename in filenames:
150             if not (filename.endswith(".pyx") or filename.endswith(".py")):
151                 continue
152             if filename.startswith('.'): continue # certain emacs backup files
153             if context == 'pyregr' and not filename.startswith('test_'):
154                 continue
155             module = os.path.splitext(filename)[0]
156             fqmodule = "%s.%s" % (context, module)
157             if not [ 1 for match in self.selectors
158                      if match(fqmodule) ]:
159                 continue
160             if self.exclude_selectors:
161                 if [1 for match in self.exclude_selectors if match(fqmodule)]:
162                     continue
163             if context in TEST_RUN_DIRS:
164                 if module.startswith("test_"):
165                     test_class = CythonUnitTestCase
166                 else:
167                     test_class = CythonRunTestCase
168             else:
169                 test_class = CythonCompileTestCase
170             for test in self.build_tests(test_class, path, workdir,
171                                          module, expect_errors):
172                 suite.addTest(test)
173         return suite
174
175     def build_tests(self, test_class, path, workdir, module, expect_errors):
176         if expect_errors:
177             languages = self.languages[:1]
178         else:
179             languages = self.languages
180         if 'cpp' in module and 'c' in languages:
181             languages = list(languages)
182             languages.remove('c')
183         tests = [ self.build_test(test_class, path, workdir, module,
184                                   language, expect_errors)
185                   for language in languages ]
186         return tests
187
188     def build_test(self, test_class, path, workdir, module,
189                    language, expect_errors):
190         workdir = os.path.join(workdir, language)
191         if not os.path.exists(workdir):
192             os.makedirs(workdir)
193         return test_class(path, workdir, module,
194                           language=language,
195                           expect_errors=expect_errors,
196                           annotate=self.annotate,
197                           cleanup_workdir=self.cleanup_workdir,
198                           cleanup_sharedlibs=self.cleanup_sharedlibs,
199                           cython_only=self.cython_only,
200                           fork=self.fork)
201
202 class CythonCompileTestCase(unittest.TestCase):
203     def __init__(self, test_directory, workdir, module, language='c',
204                  expect_errors=False, annotate=False, cleanup_workdir=True,
205                  cleanup_sharedlibs=True, cython_only=False, fork=True):
206         self.test_directory = test_directory
207         self.workdir = workdir
208         self.module = module
209         self.language = language
210         self.expect_errors = expect_errors
211         self.annotate = annotate
212         self.cleanup_workdir = cleanup_workdir
213         self.cleanup_sharedlibs = cleanup_sharedlibs
214         self.cython_only = cython_only
215         self.fork = fork
216         unittest.TestCase.__init__(self)
217
218     def shortDescription(self):
219         return "compiling (%s) %s" % (self.language, self.module)
220
221     def setUp(self):
222         if self.workdir not in sys.path:
223             sys.path.insert(0, self.workdir)
224
225     def tearDown(self):
226         try:
227             sys.path.remove(self.workdir)
228         except ValueError:
229             pass
230         try:
231             del sys.modules[self.module]
232         except KeyError:
233             pass
234         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
235         cleanup_lib_files = self.cleanup_sharedlibs
236         if os.path.exists(self.workdir):
237             for rmfile in os.listdir(self.workdir):
238                 if not cleanup_c_files:
239                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
240                         continue
241                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
242                     continue
243                 if self.annotate and rmfile.endswith(".html"):
244                     continue
245                 try:
246                     rmfile = os.path.join(self.workdir, rmfile)
247                     if os.path.isdir(rmfile):
248                         shutil.rmtree(rmfile, ignore_errors=True)
249                     else:
250                         os.remove(rmfile)
251                 except IOError:
252                     pass
253         else:
254             os.makedirs(self.workdir)
255
256     def runTest(self):
257         self.runCompileTest()
258
259     def runCompileTest(self):
260         self.compile(self.test_directory, self.module, self.workdir,
261                      self.test_directory, self.expect_errors, self.annotate)
262
263     def find_module_source_file(self, source_file):
264         if not os.path.exists(source_file):
265             source_file = source_file[:-1]
266         return source_file
267
268     def build_target_filename(self, module_name):
269         target = '%s.%s' % (module_name, self.language)
270         return target
271
272     def find_source_files(self, test_directory, module_name):
273         is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
274         return [self.build_target_filename(module_name)] + [
275             os.path.join(test_directory, filename)
276             for filename in os.listdir(test_directory)
277             if is_related(filename) and os.path.isfile(os.path.join(test_directory, filename)) ]
278
279     def split_source_and_output(self, test_directory, module, workdir):
280         source_file = os.path.join(test_directory, module) + '.pyx'
281         source_and_output = codecs.open(
282             self.find_module_source_file(source_file), 'rU', 'ISO-8859-1')
283         out = codecs.open(os.path.join(workdir, module + '.pyx'),
284                           'w', 'ISO-8859-1')
285         for line in source_and_output:
286             last_line = line
287             if line.startswith("_ERRORS"):
288                 out.close()
289                 out = ErrorWriter()
290             else:
291                 out.write(line)
292         try:
293             geterrors = out.geterrors
294         except AttributeError:
295             return []
296         else:
297             return geterrors()
298
299     def run_cython(self, test_directory, module, targetdir, incdir, annotate):
300         include_dirs = INCLUDE_DIRS[:]
301         if incdir:
302             include_dirs.append(incdir)
303         source = self.find_module_source_file(
304             os.path.join(test_directory, module + '.pyx'))
305         target = os.path.join(targetdir, self.build_target_filename(module))
306         options = CompilationOptions(
307             pyrex_default_options,
308             include_path = include_dirs,
309             output_file = target,
310             annotate = annotate,
311             use_listing_file = False,
312             cplus = self.language == 'cpp',
313             generate_pxi = False,
314             evaluate_tree_assertions = True,
315             )
316         cython_compile(source, options=options,
317                        full_module_name=module)
318
319     def run_distutils(self, test_directory, module, workdir, incdir):
320         cwd = os.getcwd()
321         os.chdir(workdir)
322         try:
323             build_extension = build_ext(distutils_distro)
324             build_extension.include_dirs = INCLUDE_DIRS[:]
325             if incdir:
326                 build_extension.include_dirs.append(incdir)
327             build_extension.finalize_options()
328             ext_include_dirs = []
329             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
330                 if match(module):
331                     ext_include_dirs += get_additional_include_dirs()
332             extension = Extension(
333                 module,
334                 sources = self.find_source_files(test_directory, module),
335                 include_dirs = ext_include_dirs,
336                 extra_compile_args = CFLAGS,
337                 )
338             if self.language == 'cpp':
339                 extension.language = 'c++'
340             build_extension.extensions = [extension]
341             build_extension.build_temp = workdir
342             build_extension.build_lib  = workdir
343             build_extension.run()
344         finally:
345             os.chdir(cwd)
346
347     def compile(self, test_directory, module, workdir, incdir,
348                 expect_errors, annotate):
349         expected_errors = errors = ()
350         if expect_errors:
351             expected_errors = self.split_source_and_output(
352                 test_directory, module, workdir)
353             test_directory = workdir
354
355         if WITH_CYTHON:
356             old_stderr = sys.stderr
357             try:
358                 sys.stderr = ErrorWriter()
359                 self.run_cython(test_directory, module, workdir, incdir, annotate)
360                 errors = sys.stderr.geterrors()
361             finally:
362                 sys.stderr = old_stderr
363
364         if errors or expected_errors:
365             try:
366                 for expected, error in zip(expected_errors, errors):
367                     self.assertEquals(expected, error)
368                 if len(errors) < len(expected_errors):
369                     expected_error = expected_errors[len(errors)]
370                     self.assertEquals(expected_error, None)
371                 elif len(errors) > len(expected_errors):
372                     unexpected_error = errors[len(expected_errors)]
373                     self.assertEquals(None, unexpected_error)
374             except AssertionError:
375                 print("\n=== Expected errors: ===")
376                 print('\n'.join(expected_errors))
377                 print("\n\n=== Got errors: ===")
378                 print('\n'.join(errors))
379                 print('\n')
380                 raise
381         else:
382             if not self.cython_only:
383                 self.run_distutils(test_directory, module, workdir, incdir)
384
385 class CythonRunTestCase(CythonCompileTestCase):
386     def shortDescription(self):
387         return "compiling (%s) and running %s" % (self.language, self.module)
388
389     def run(self, result=None):
390         if result is None:
391             result = self.defaultTestResult()
392         result.startTest(self)
393         try:
394             self.setUp()
395             self.runCompileTest()
396             if not self.cython_only:
397                 self.run_doctests(self.module, result)
398         except Exception:
399             result.addError(self, sys.exc_info())
400             result.stopTest(self)
401         try:
402             self.tearDown()
403         except Exception:
404             pass
405
406     def run_doctests(self, module_name, result):
407         if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
408             doctest.DocTestSuite(module_name).run(result)
409             gc.collect()
410             return
411
412         # fork to make sure we do not keep the tested module loaded
413         result_handle, result_file = tempfile.mkstemp()
414         os.close(result_handle)
415         child_id = os.fork()
416         if not child_id:
417             result_code = 0
418             try:
419                 try:
420                     tests = None
421                     try:
422                         partial_result = PartialTestResult(result)
423                         tests = doctest.DocTestSuite(module_name)
424                         tests.run(partial_result)
425                         gc.collect()
426                     except Exception:
427                         if tests is None:
428                             # importing failed, try to fake a test class
429                             tests = _FakeClass(
430                                 failureException=None,
431                                 shortDescription = self.shortDescription,
432                                 **{module_name: None})
433                         partial_result.addError(tests, sys.exc_info())
434                         result_code = 1
435                     output = open(result_file, 'wb')
436                     pickle.dump(partial_result.data(), output)
437                 except:
438                     import traceback
439                     traceback.print_exc()
440             finally:
441                 try: output.close()
442                 except: pass
443                 os._exit(result_code)
444
445         try:
446             cid, result_code = os.waitpid(child_id, 0)
447             if result_code in (0,1):
448                 input = open(result_file, 'rb')
449                 try:
450                     PartialTestResult.join_results(result, pickle.load(input))
451                 finally:
452                     input.close()
453             if result_code:
454                 raise Exception("Tests in module '%s' exited with status %d" %
455                                 (module_name, result_code >> 8))
456         finally:
457             try: os.unlink(result_file)
458             except: pass
459
460
461 is_private_field = re.compile('^_[^_]').match
462
463 class _FakeClass(object):
464     def __init__(self, **kwargs):
465         self._shortDescription = kwargs.get('module_name')
466         self.__dict__.update(kwargs)
467     def shortDescription(self):
468         return self._shortDescription
469
470 try: # Py2.7+ and Py3.2+
471     from unittest.runner import _TextTestResult
472 except ImportError:
473     from unittest import _TextTestResult
474
475 class PartialTestResult(_TextTestResult):
476     def __init__(self, base_result):
477         _TextTestResult.__init__(
478             self, self._StringIO(), True,
479             base_result.dots + base_result.showAll*2)
480
481     def strip_error_results(self, results):
482         for test_case, error in results:
483             for attr_name in filter(is_private_field, dir(test_case)):
484                 if attr_name == '_dt_test':
485                     test_case._dt_test = _FakeClass(
486                         name=test_case._dt_test.name)
487                 else:
488                     setattr(test_case, attr_name, None)
489
490     def data(self):
491         self.strip_error_results(self.failures)
492         self.strip_error_results(self.errors)
493         return (self.failures, self.errors, self.testsRun,
494                 self.stream.getvalue())
495
496     def join_results(result, data):
497         """Static method for merging the result back into the main
498         result object.
499         """
500         errors, failures, tests_run, output = data
501         if output:
502             result.stream.write(output)
503         result.errors.extend(errors)
504         result.failures.extend(failures)
505         result.testsRun += tests_run
506
507     join_results = staticmethod(join_results)
508
509     class _StringIO(StringIO):
510         def writeln(self, line):
511             self.write("%s\n" % line)
512
513
514 class CythonUnitTestCase(CythonCompileTestCase):
515     def shortDescription(self):
516         return "compiling (%s) tests in %s" % (self.language, self.module)
517
518     def run(self, result=None):
519         if result is None:
520             result = self.defaultTestResult()
521         result.startTest(self)
522         try:
523             self.setUp()
524             self.runCompileTest()
525             unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
526         except Exception:
527             result.addError(self, sys.exc_info())
528             result.stopTest(self)
529         try:
530             self.tearDown()
531         except Exception:
532             pass
533
534 def collect_unittests(path, module_prefix, suite, selectors):
535     def file_matches(filename):
536         return filename.startswith("Test") and filename.endswith(".py")
537
538     def package_matches(dirname):
539         return dirname == "Tests"
540
541     loader = unittest.TestLoader()
542
543     skipped_dirs = []
544
545     for dirpath, dirnames, filenames in os.walk(path):
546         if dirpath != path and "__init__.py" not in filenames:
547             skipped_dirs.append(dirpath + os.path.sep)
548             continue
549         skip = False
550         for dir in skipped_dirs:
551             if dirpath.startswith(dir):
552                 skip = True
553         if skip:
554             continue
555         parentname = os.path.split(dirpath)[-1]
556         if package_matches(parentname):
557             for f in filenames:
558                 if file_matches(f):
559                     filepath = os.path.join(dirpath, f)[:-len(".py")]
560                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
561                     if not [ 1 for match in selectors if match(modulename) ]:
562                         continue
563                     module = __import__(modulename)
564                     for x in modulename.split('.')[1:]:
565                         module = getattr(module, x)
566                     suite.addTests([loader.loadTestsFromModule(module)])
567
568 def collect_doctests(path, module_prefix, suite, selectors):
569     def package_matches(dirname):
570         return dirname not in ("Mac", "Distutils", "Plex")
571     def file_matches(filename):
572         return (filename.endswith(".py") and not ('~' in filename
573                 or '#' in filename or filename.startswith('.')))
574     import doctest, types
575     for dirpath, dirnames, filenames in os.walk(path):
576         parentname = os.path.split(dirpath)[-1]
577         if package_matches(parentname):
578             for f in filenames:
579                 if file_matches(f):
580                     if not f.endswith('.py'): continue
581                     filepath = os.path.join(dirpath, f)[:-len(".py")]
582                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
583                     if not [ 1 for match in selectors if match(modulename) ]:
584                         continue
585                     module = __import__(modulename)
586                     for x in modulename.split('.')[1:]:
587                         module = getattr(module, x)
588                     if hasattr(module, "__doc__") or hasattr(module, "__test__"):
589                         try:
590                             suite.addTest(doctest.DocTestSuite(module))
591                         except ValueError: # no tests
592                             pass
593
594 # TODO: Support cython_freeze needed here as well.
595 # TODO: Windows support.
596
597 class EmbedTest(unittest.TestCase):
598     
599     working_dir = "Demos/embed"
600     
601     def setUp(self):
602         self.old_dir = os.getcwd()
603         os.chdir(self.working_dir)
604         os.system("make clean > /dev/null")
605     
606     def tearDown(self):
607         try:
608             os.system("make clean > /dev/null")
609         except:
610             pass
611         os.chdir(self.old_dir)
612         
613     def test_embed(self):
614         self.assert_(os.system("make test > make.output") == 0)
615
616 class MissingDependencyExcluder:
617     def __init__(self, deps):
618         # deps: { module name : matcher func }
619         self.exclude_matchers = []
620         for mod, matcher in deps.items():
621             try:
622                 __import__(mod)
623             except ImportError:
624                 self.exclude_matchers.append(matcher)
625         self.tests_missing_deps = []
626     def __call__(self, testname):
627         for matcher in self.exclude_matchers:
628             if matcher(testname):
629                 self.tests_missing_deps.append(testname)
630                 return True
631         return False
632
633 class VersionDependencyExcluder:
634     def __init__(self, deps):
635         # deps: { version : matcher func }
636         from sys import version_info
637         self.exclude_matchers = []
638         for ver, (compare, matcher) in deps.items():
639             if compare(version_info, ver):
640                 self.exclude_matchers.append(matcher)
641         self.tests_missing_deps = []
642     def __call__(self, testname):
643         for matcher in self.exclude_matchers:
644             if matcher(testname):
645                 self.tests_missing_deps.append(testname)
646                 return True
647         return False
648
649 class FileListExcluder:
650
651     def __init__(self, list_file):
652         self.excludes = {}
653         for line in open(list_file).readlines():
654             line = line.strip()
655             if line and line[0] != '#':
656                 self.excludes[line.split()[0]] = True
657                 
658     def __call__(self, testname):
659         return testname in self.excludes or testname.split('.')[-1] in self.excludes
660
661 if __name__ == '__main__':
662     from optparse import OptionParser
663     parser = OptionParser()
664     parser.add_option("--no-cleanup", dest="cleanup_workdir",
665                       action="store_false", default=True,
666                       help="do not delete the generated C files (allows passing --no-cython on next run)")
667     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
668                       action="store_false", default=True,
669                       help="do not delete the generated shared libary files (allows manual module experimentation)")
670     parser.add_option("--no-cython", dest="with_cython",
671                       action="store_false", default=True,
672                       help="do not run the Cython compiler, only the C compiler")
673     parser.add_option("--no-c", dest="use_c",
674                       action="store_false", default=True,
675                       help="do not test C compilation")
676     parser.add_option("--no-cpp", dest="use_cpp",
677                       action="store_false", default=True,
678                       help="do not test C++ compilation")
679     parser.add_option("--no-unit", dest="unittests",
680                       action="store_false", default=True,
681                       help="do not run the unit tests")
682     parser.add_option("--no-doctest", dest="doctests",
683                       action="store_false", default=True,
684                       help="do not run the doctests")
685     parser.add_option("--no-file", dest="filetests",
686                       action="store_false", default=True,
687                       help="do not run the file based tests")
688     parser.add_option("--no-pyregr", dest="pyregr",
689                       action="store_false", default=True,
690                       help="do not run the regression tests of CPython in tests/pyregr/")    
691     parser.add_option("--cython-only", dest="cython_only",
692                       action="store_true", default=False,
693                       help="only compile pyx to c, do not run C compiler or run the tests")
694     parser.add_option("--no-refnanny", dest="with_refnanny",
695                       action="store_false", default=True,
696                       help="do not regression test reference counting")
697     parser.add_option("--no-fork", dest="fork",
698                       action="store_false", default=True,
699                       help="do not fork to run tests")
700     parser.add_option("--sys-pyregr", dest="system_pyregr",
701                       action="store_true", default=False,
702                       help="run the regression tests of the CPython installation")
703     parser.add_option("-x", "--exclude", dest="exclude",
704                       action="append", metavar="PATTERN",
705                       help="exclude tests matching the PATTERN")
706     parser.add_option("-C", "--coverage", dest="coverage",
707                       action="store_true", default=False,
708                       help="collect source coverage data for the Compiler")
709     parser.add_option("-A", "--annotate", dest="annotate_source",
710                       action="store_true", default=True,
711                       help="generate annotated HTML versions of the test source files")
712     parser.add_option("--no-annotate", dest="annotate_source",
713                       action="store_false",
714                       help="do not generate annotated HTML versions of the test source files")
715     parser.add_option("-v", "--verbose", dest="verbosity",
716                       action="count", default=0,
717                       help="display test progress, pass twice to print test names")
718     parser.add_option("-T", "--ticket", dest="tickets",
719                       action="append",
720                       help="a bug ticket number to run the respective test in 'tests/bugs'")
721
722     options, cmd_args = parser.parse_args()
723
724     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
725     ROOTDIR = os.path.join(DISTDIR, 'tests')
726     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
727
728     if sys.version_info >= (3,1):
729         options.doctests    = False
730         options.unittests   = False
731         options.pyregr      = False
732         if options.with_cython:
733             # need to convert Cython sources first
734             import lib2to3.refactor
735             from distutils.util import copydir_run_2to3
736             fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
737                        if fix.split('fix_')[-1] not in ('next',)
738                        ]
739             cy3_dir = os.path.join(WORKDIR, 'Cy3')
740             if not os.path.exists(cy3_dir):
741                 os.makedirs(cy3_dir)
742             import distutils.log as dlog
743             dlog.set_threshold(dlog.DEBUG)
744             copydir_run_2to3(DISTDIR, cy3_dir, fixer_names=fixers,
745                              template = '''
746                              global-exclude *
747                              graft Cython
748                              recursive-exclude Cython *
749                              recursive-include Cython *.py *.pyx *.pxd
750                              ''')
751             sys.path.insert(0, cy3_dir)
752     elif sys.version_info[0] >= 3:
753         # make sure we do not import (or run) Cython itself (unless
754         # 2to3 was already run)
755         cy3_dir = os.path.join(WORKDIR, 'Cy3')
756         if os.path.isdir(cy3_dir):
757             sys.path.insert(0, cy3_dir)
758         else:
759             options.with_cython = False
760         options.doctests    = False
761         options.unittests   = False
762         options.pyregr      = False
763
764     if options.coverage:
765         import coverage
766         coverage.erase()
767         coverage.start()
768
769     WITH_CYTHON = options.with_cython
770
771     if WITH_CYTHON:
772         from Cython.Compiler.Main import \
773             CompilationOptions, \
774             default_options as pyrex_default_options, \
775             compile as cython_compile
776         from Cython.Compiler import Errors
777         Errors.LEVEL = 0 # show all warnings
778         from Cython.Compiler import Options
779         Options.generate_cleanup_code = 3   # complete cleanup code
780         from Cython.Compiler import DebugFlags
781         DebugFlags.debug_temp_code_comments = 1
782
783     # RUN ALL TESTS!
784     UNITTEST_MODULE = "Cython"
785     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
786     if WITH_CYTHON:
787         if os.path.exists(WORKDIR):
788             for path in os.listdir(WORKDIR):
789                 if path in ("support", "Cy3"): continue
790                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
791     if not os.path.exists(WORKDIR):
792         os.makedirs(WORKDIR)
793
794     if WITH_CYTHON:
795         from Cython.Compiler.Version import version
796         sys.stderr.write("Running tests against Cython %s\n" % version)
797     else:
798         sys.stderr.write("Running tests without Cython.\n")
799     sys.stderr.write("Python %s\n" % sys.version)
800     sys.stderr.write("\n")
801
802     if options.with_refnanny:
803         from pyximport.pyxbuild import pyx_to_dll
804         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
805                              build_in_temp=True,
806                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
807         sys.path.insert(0, os.path.split(libpath)[0])
808         CFLAGS.append("-DCYTHON_REFNANNY=1")
809
810     test_bugs = False
811     if options.tickets:
812         for ticket_number in options.tickets:
813             test_bugs = True
814             cmd_args.append('.*T%s$' % ticket_number)
815     if not test_bugs:
816         for selector in cmd_args:
817             if selector.startswith('bugs'):
818                 test_bugs = True
819
820     import re
821     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
822     if not selectors:
823         selectors = [ lambda x:True ]
824
825     # Chech which external modules are not present and exclude tests
826     # which depends on them (by prefix)
827
828     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
829     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
830     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
831
832     if options.exclude:
833         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
834     
835     if not test_bugs:
836         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
837     
838     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
839         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
840
841     languages = []
842     if options.use_c:
843         languages.append('c')
844     if options.use_cpp:
845         languages.append('cpp')
846
847     test_suite = unittest.TestSuite()
848
849     if options.unittests:
850         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
851
852     if options.doctests:
853         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
854
855     if options.filetests and languages:
856         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
857                                 options.annotate_source, options.cleanup_workdir,
858                                 options.cleanup_sharedlibs, options.pyregr,
859                                 options.cython_only, languages, test_bugs,
860                                 options.fork)
861         test_suite.addTest(filetests.build_suite())
862
863     if options.system_pyregr and languages:
864         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
865                                 options.annotate_source, options.cleanup_workdir,
866                                 options.cleanup_sharedlibs, True,
867                                 options.cython_only, languages, test_bugs,
868                                 options.fork)
869         test_suite.addTest(
870             filetests.handle_directory(
871                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
872                 'pyregr'))
873
874     result = unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
875
876     if options.coverage:
877         coverage.stop()
878         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
879         modules = [ module for name, module in sys.modules.items()
880                     if module is not None and
881                     name.startswith('Cython.Compiler.') and 
882                     name[len('Cython.Compiler.'):] not in ignored_modules ]
883         coverage.report(modules, show_missing=0)
884
885     if missing_dep_excluder.tests_missing_deps:
886         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
887         for test in missing_dep_excluder.tests_missing_deps:
888             sys.stderr.write("   %s\n" % test)
889
890     if options.with_refnanny:
891         import refnanny
892         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
893
894     sys.exit(not result.wasSuccessful())