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