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