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