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