Merge https://github.com/cython/cython
[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 import traceback
14 try:
15     from StringIO import StringIO
16 except ImportError:
17     from io import StringIO
18
19 try:
20     import cPickle as pickle
21 except ImportError:
22     import pickle
23
24 try:
25     import threading
26 except ImportError: # No threads, no problems
27     threading = None
28
29
30 WITH_CYTHON = True
31
32 from distutils.dist import Distribution
33 from distutils.core import Extension
34 from distutils.command.build_ext import build_ext as _build_ext
35 distutils_distro = Distribution()
36
37 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
38 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
39
40 # Lists external modules, and a matcher matching tests
41 # which should be excluded if the module is not present.
42 EXT_DEP_MODULES = {
43     'numpy' : re.compile('.*\.numpy_.*').match,
44     'pstats' : re.compile('.*\.pstats_.*').match,
45     'posix' : re.compile('.*\.posix_.*').match,
46 }
47
48 def get_numpy_include_dirs():
49     import numpy
50     return [numpy.get_include()]
51
52 EXT_DEP_INCLUDES = [
53     # test name matcher , callable returning list
54     (re.compile('numpy_.*').match, get_numpy_include_dirs),
55 ]
56
57 VER_DEP_MODULES = {
58     # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
59     # (2,4) : (operator.lt, ...) excludes ... when PyVer < 2.4.x
60     (2,4) : (operator.lt, lambda x: x in ['run.extern_builtins_T258',
61                                           'run.builtin_sorted'
62                                           ]),
63     (2,5) : (operator.lt, lambda x: x in ['run.any',
64                                           'run.all',
65                                           ]),
66     (2,6) : (operator.lt, lambda x: x in ['run.print_function',
67                                           'run.cython3',
68                                           'run.pure_py', # decorators, with statement
69                                           ]),
70     # The next line should start (3,); but this is a dictionary, so
71     # we can only have one (3,) key.  Since 2.7 is supposed to be the
72     # last 2.x release, things would have to change drastically for this
73     # to be unsafe...
74     (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
75     (3,): (operator.ge, lambda x: x in ['run.non_future_division',
76                                         'compile.extsetslice',
77                                         'compile.extdelslice',
78                                         'run.special_methods_T561_py2']),
79 }
80
81 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
82 CFLAGS = os.getenv('CFLAGS', '').split()
83
84 class build_ext(_build_ext):
85     def build_extension(self, ext):
86         if ext.language == 'c++':
87             try:
88                 try: # Py2.7+ & Py3.2+ 
89                     compiler_obj = self.compiler_obj
90                 except AttributeError:
91                     compiler_obj = self.compiler
92                 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
93             except Exception:
94                 pass
95         _build_ext.build_extension(self, ext)
96
97 class ErrorWriter(object):
98     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
99     def __init__(self):
100         self.output = []
101         self.write = self.output.append
102
103     def _collect(self, collect_errors, collect_warnings):
104         s = ''.join(self.output)
105         result = []
106         for line in s.split('\n'):
107             match = self.match_error(line)
108             if match:
109                 is_warning, line, column, message = match.groups()
110                 if (is_warning and collect_warnings) or \
111                         (not is_warning and collect_errors):
112                     result.append( (int(line), int(column), message.strip()) )
113         result.sort()
114         return [ "%d:%d: %s" % values for values in result ]
115
116     def geterrors(self):
117         return self._collect(True, False)
118
119     def getwarnings(self):
120         return self._collect(False, True)
121
122     def getall(self):
123         return self._collect(True, True)
124
125 class TestBuilder(object):
126     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
127                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
128                  languages, test_bugs, fork, language_level):
129         self.rootdir = rootdir
130         self.workdir = workdir
131         self.selectors = selectors
132         self.exclude_selectors = exclude_selectors
133         self.annotate = annotate
134         self.cleanup_workdir = cleanup_workdir
135         self.cleanup_sharedlibs = cleanup_sharedlibs
136         self.with_pyregr = with_pyregr
137         self.cython_only = cython_only
138         self.languages = languages
139         self.test_bugs = test_bugs
140         self.fork = fork
141         self.language_level = language_level
142
143     def build_suite(self):
144         suite = unittest.TestSuite()
145         test_dirs = TEST_DIRS
146         filenames = os.listdir(self.rootdir)
147         filenames.sort()
148         for filename in filenames:
149             if not WITH_CYTHON and filename == "errors":
150                 # we won't get any errors without running Cython
151                 continue
152             path = os.path.join(self.rootdir, filename)
153             if os.path.isdir(path) and filename in test_dirs:
154                 if filename == 'pyregr' and not self.with_pyregr:
155                     continue
156                 suite.addTest(
157                     self.handle_directory(path, filename))
158         if sys.platform not in ['win32'] and sys.version_info[0] < 3:
159             # Non-Windows makefile, can't run Cython under Py3.
160             if [1 for selector in self.selectors if selector("embedded")]:
161                 suite.addTest(unittest.makeSuite(EmbedTest))
162         return suite
163
164     def handle_directory(self, path, context):
165         workdir = os.path.join(self.workdir, context)
166         if not os.path.exists(workdir):
167             os.makedirs(workdir)
168
169         expect_errors = (context == 'errors')
170         suite = unittest.TestSuite()
171         filenames = os.listdir(path)
172         filenames.sort()
173         for filename in filenames:
174             if context == "build" and filename.endswith(".srctree"):
175                 if not [ 1 for match in self.selectors if match(filename) ]:
176                     continue
177                 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
178                 continue
179             if not (filename.endswith(".pyx") or filename.endswith(".py")):
180                 continue
181             if filename.startswith('.'): continue # certain emacs backup files
182             if context == 'pyregr' and not filename.startswith('test_'):
183                 continue
184             module = os.path.splitext(filename)[0]
185             fqmodule = "%s.%s" % (context, module)
186             if not [ 1 for match in self.selectors
187                      if match(fqmodule) ]:
188                 continue
189             if self.exclude_selectors:
190                 if [1 for match in self.exclude_selectors if match(fqmodule)]:
191                     continue
192             if context in TEST_RUN_DIRS:
193                 if module.startswith("test_"):
194                     test_class = CythonUnitTestCase
195                 else:
196                     test_class = CythonRunTestCase
197             else:
198                 test_class = CythonCompileTestCase
199             for test in self.build_tests(test_class, path, workdir,
200                                          module, expect_errors):
201                 suite.addTest(test)
202             if context == 'run' and filename.endswith('.py'):
203                 # additionally test file in real Python
204                 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
205         return suite
206
207     def build_tests(self, test_class, path, workdir, module, expect_errors):
208         if expect_errors:
209             if 'cpp' in module and 'cpp' in self.languages:
210                 languages = ['cpp']
211             else:
212                 languages = self.languages[:1]
213         else:
214             languages = self.languages
215         if 'cpp' in module and 'c' in languages:
216             languages = list(languages)
217             languages.remove('c')
218         tests = [ self.build_test(test_class, path, workdir, module,
219                                   language, expect_errors)
220                   for language in languages ]
221         return tests
222
223     def build_test(self, test_class, path, workdir, module,
224                    language, expect_errors):
225         workdir = os.path.join(workdir, language)
226         if not os.path.exists(workdir):
227             os.makedirs(workdir)
228         return test_class(path, workdir, module,
229                           language=language,
230                           expect_errors=expect_errors,
231                           annotate=self.annotate,
232                           cleanup_workdir=self.cleanup_workdir,
233                           cleanup_sharedlibs=self.cleanup_sharedlibs,
234                           cython_only=self.cython_only,
235                           fork=self.fork,
236                           language_level=self.language_level)
237
238 class CythonCompileTestCase(unittest.TestCase):
239     def __init__(self, test_directory, workdir, module, language='c',
240                  expect_errors=False, annotate=False, cleanup_workdir=True,
241                  cleanup_sharedlibs=True, cython_only=False, fork=True,
242                  language_level=2):
243         self.test_directory = test_directory
244         self.workdir = workdir
245         self.module = module
246         self.language = language
247         self.expect_errors = expect_errors
248         self.annotate = annotate
249         self.cleanup_workdir = cleanup_workdir
250         self.cleanup_sharedlibs = cleanup_sharedlibs
251         self.cython_only = cython_only
252         self.fork = fork
253         self.language_level = language_level
254         unittest.TestCase.__init__(self)
255
256     def shortDescription(self):
257         return "compiling (%s) %s" % (self.language, self.module)
258
259     def setUp(self):
260         if self.workdir not in sys.path:
261             sys.path.insert(0, self.workdir)
262
263     def tearDown(self):
264         try:
265             sys.path.remove(self.workdir)
266         except ValueError:
267             pass
268         try:
269             del sys.modules[self.module]
270         except KeyError:
271             pass
272         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
273         cleanup_lib_files = self.cleanup_sharedlibs
274         if os.path.exists(self.workdir):
275             for rmfile in os.listdir(self.workdir):
276                 if not cleanup_c_files:
277                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
278                         continue
279                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
280                     continue
281                 if self.annotate and rmfile.endswith(".html"):
282                     continue
283                 try:
284                     rmfile = os.path.join(self.workdir, rmfile)
285                     if os.path.isdir(rmfile):
286                         shutil.rmtree(rmfile, ignore_errors=True)
287                     else:
288                         os.remove(rmfile)
289                 except IOError:
290                     pass
291         else:
292             os.makedirs(self.workdir)
293
294     def runTest(self):
295         self.runCompileTest()
296
297     def runCompileTest(self):
298         self.compile(self.test_directory, self.module, self.workdir,
299                      self.test_directory, self.expect_errors, self.annotate)
300
301     def find_module_source_file(self, source_file):
302         if not os.path.exists(source_file):
303             source_file = source_file[:-1]
304         return source_file
305
306     def build_target_filename(self, module_name):
307         target = '%s.%s' % (module_name, self.language)
308         return target
309
310     def copy_related_files(self, test_directory, target_directory, module_name):
311         is_related = re.compile('%s_.*[.].*' % module_name).match
312         for filename in os.listdir(test_directory):
313             if is_related(filename):
314                 shutil.copy(os.path.join(test_directory, filename),
315                             target_directory)
316
317     def find_source_files(self, workdir, module_name):
318         is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
319         return [self.build_target_filename(module_name)] + [
320             filename for filename in os.listdir(workdir)
321             if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
322
323     def split_source_and_output(self, test_directory, module, workdir):
324         source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
325         source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
326         try:
327             out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
328                               'w', 'ISO-8859-1')
329             for line in source_and_output:
330                 last_line = line
331                 if line.startswith("_ERRORS"):
332                     out.close()
333                     out = ErrorWriter()
334                 else:
335                     out.write(line)
336         finally:
337             source_and_output.close()
338         try:
339             geterrors = out.geterrors
340         except AttributeError:
341             out.close()
342             return []
343         else:
344             return geterrors()
345
346     def run_cython(self, test_directory, module, targetdir, incdir, annotate,
347                    extra_compile_options=None):
348         include_dirs = INCLUDE_DIRS[:]
349         if incdir:
350             include_dirs.append(incdir)
351         source = self.find_module_source_file(
352             os.path.join(test_directory, module + '.pyx'))
353         target = os.path.join(targetdir, self.build_target_filename(module))
354         
355         if extra_compile_options is None:
356             extra_compile_options = {}
357         
358         try:
359             CompilationOptions
360         except NameError:
361             from Cython.Compiler.Main import CompilationOptions
362             from Cython.Compiler.Main import compile as cython_compile
363             from Cython.Compiler.Main import default_options
364         
365         options = CompilationOptions(
366             default_options,
367             include_path = include_dirs,
368             output_file = target,
369             annotate = annotate,
370             use_listing_file = False,
371             cplus = self.language == 'cpp',
372             language_level = self.language_level,
373             generate_pxi = False,
374             evaluate_tree_assertions = True,
375             **extra_compile_options
376             )
377         cython_compile(source, options=options,
378                        full_module_name=module)
379
380     def run_distutils(self, test_directory, module, workdir, incdir, 
381                       extra_extension_args=None):
382         cwd = os.getcwd()
383         os.chdir(workdir)
384         try:
385             build_extension = build_ext(distutils_distro)
386             build_extension.include_dirs = INCLUDE_DIRS[:]
387             if incdir:
388                 build_extension.include_dirs.append(incdir)
389             build_extension.finalize_options()
390             ext_include_dirs = []
391             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
392                 if match(module):
393                     ext_include_dirs += get_additional_include_dirs()
394             self.copy_related_files(test_directory, workdir, module)
395             
396             if extra_extension_args is None:
397                 extra_extension_args = {}
398             
399             extension = Extension(
400                 module,
401                 sources = self.find_source_files(workdir, module),
402                 include_dirs = ext_include_dirs,
403                 extra_compile_args = CFLAGS,
404                 **extra_extension_args
405                 )
406             if self.language == 'cpp':
407                 extension.language = 'c++'
408             build_extension.extensions = [extension]
409             build_extension.build_temp = workdir
410             build_extension.build_lib  = workdir
411             build_extension.run()
412         finally:
413             os.chdir(cwd)
414
415     def compile(self, test_directory, module, workdir, incdir,
416                 expect_errors, annotate):
417         expected_errors = errors = ()
418         if expect_errors:
419             expected_errors = self.split_source_and_output(
420                 test_directory, module, workdir)
421             test_directory = workdir
422
423         if WITH_CYTHON:
424             old_stderr = sys.stderr
425             try:
426                 sys.stderr = ErrorWriter()
427                 self.run_cython(test_directory, module, workdir, incdir, annotate)
428                 errors = sys.stderr.geterrors()
429             finally:
430                 sys.stderr = old_stderr
431
432         if errors or expected_errors:
433             try:
434                 for expected, error in zip(expected_errors, errors):
435                     self.assertEquals(expected, error)
436                 if len(errors) < len(expected_errors):
437                     expected_error = expected_errors[len(errors)]
438                     self.assertEquals(expected_error, None)
439                 elif len(errors) > len(expected_errors):
440                     unexpected_error = errors[len(expected_errors)]
441                     self.assertEquals(None, unexpected_error)
442             except AssertionError:
443                 print("\n=== Expected errors: ===")
444                 print('\n'.join(expected_errors))
445                 print("\n\n=== Got errors: ===")
446                 print('\n'.join(errors))
447                 print('\n')
448                 raise
449         else:
450             if not self.cython_only:
451                 self.run_distutils(test_directory, module, workdir, incdir)
452
453 class CythonRunTestCase(CythonCompileTestCase):
454     def shortDescription(self):
455         return "compiling (%s) and running %s" % (self.language, self.module)
456
457     def run(self, result=None):
458         if result is None:
459             result = self.defaultTestResult()
460         result.startTest(self)
461         try:
462             self.setUp()
463             try:
464                 self.runCompileTest()
465                 if not self.cython_only:
466                     self.run_doctests(self.module, result)
467             finally:
468                 check_thread_termination()
469         except Exception:
470             result.addError(self, sys.exc_info())
471             result.stopTest(self)
472         try:
473             self.tearDown()
474         except Exception:
475             pass
476
477     def run_doctests(self, module_name, result):
478         if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
479             doctest.DocTestSuite(module_name).run(result)
480             gc.collect()
481             return
482
483         # fork to make sure we do not keep the tested module loaded
484         result_handle, result_file = tempfile.mkstemp()
485         os.close(result_handle)
486         child_id = os.fork()
487         if not child_id:
488             result_code = 0
489             try:
490                 try:
491                     tests = None
492                     try:
493                         partial_result = PartialTestResult(result)
494                         tests = doctest.DocTestSuite(module_name)
495                         tests.run(partial_result)
496                         gc.collect()
497                     except Exception:
498                         if tests is None:
499                             # importing failed, try to fake a test class
500                             tests = _FakeClass(
501                                 failureException=sys.exc_info()[1],
502                                 _shortDescription=self.shortDescription(),
503                                 module_name=None)
504                         partial_result.addError(tests, sys.exc_info())
505                         result_code = 1
506                     output = open(result_file, 'wb')
507                     pickle.dump(partial_result.data(), output)
508                 except:
509                     traceback.print_exc()
510             finally:
511                 try: output.close()
512                 except: pass
513                 os._exit(result_code)
514
515         try:
516             cid, result_code = os.waitpid(child_id, 0)
517             # os.waitpid returns the child's result code in the
518             # upper byte of result_code, and the signal it was
519             # killed by in the lower byte
520             if result_code & 255:
521                 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
522                                 (module_name, result_code & 255))
523             result_code = result_code >> 8
524             if result_code in (0,1):
525                 input = open(result_file, 'rb')
526                 try:
527                     PartialTestResult.join_results(result, pickle.load(input))
528                 finally:
529                     input.close()
530             if result_code:
531                 raise Exception("Tests in module '%s' exited with status %d" %
532                                 (module_name, result_code))
533         finally:
534             try: os.unlink(result_file)
535             except: pass
536
537 class PureDoctestTestCase(unittest.TestCase):
538     def __init__(self, module_name, module_path):
539         self.module_name = module_name
540         self.module_path = module_path
541         unittest.TestCase.__init__(self, 'run')
542
543     def shortDescription(self):
544         return "running pure doctests in %s" % self.module_name
545
546     def run(self, result=None):
547         if result is None:
548             result = self.defaultTestResult()
549         loaded_module_name = 'pure_doctest__' + self.module_name
550         result.startTest(self)
551         try:
552             self.setUp()
553
554             import imp
555             m = imp.load_source(loaded_module_name, self.module_path)
556             try:
557                 doctest.DocTestSuite(m).run(result)
558             finally:
559                 del m
560                 if loaded_module_name in sys.modules:
561                     del sys.modules[loaded_module_name]
562                 check_thread_termination()
563         except Exception:
564             result.addError(self, sys.exc_info())
565             result.stopTest(self)
566         try:
567             self.tearDown()
568         except Exception:
569             pass
570
571 is_private_field = re.compile('^_[^_]').match
572
573 class _FakeClass(object):
574     def __init__(self, **kwargs):
575         self._shortDescription = kwargs.get('module_name')
576         self.__dict__.update(kwargs)
577     def shortDescription(self):
578         return self._shortDescription
579
580 try: # Py2.7+ and Py3.2+
581     from unittest.runner import _TextTestResult
582 except ImportError:
583     from unittest import _TextTestResult
584
585 class PartialTestResult(_TextTestResult):
586     def __init__(self, base_result):
587         _TextTestResult.__init__(
588             self, self._StringIO(), True,
589             base_result.dots + base_result.showAll*2)
590
591     def strip_error_results(self, results):
592         for test_case, error in results:
593             for attr_name in filter(is_private_field, dir(test_case)):
594                 if attr_name == '_dt_test':
595                     test_case._dt_test = _FakeClass(
596                         name=test_case._dt_test.name)
597                 elif attr_name != '_shortDescription':
598                     setattr(test_case, attr_name, None)
599
600     def data(self):
601         self.strip_error_results(self.failures)
602         self.strip_error_results(self.errors)
603         return (self.failures, self.errors, self.testsRun,
604                 self.stream.getvalue())
605
606     def join_results(result, data):
607         """Static method for merging the result back into the main
608         result object.
609         """
610         failures, errors, tests_run, output = data
611         if output:
612             result.stream.write(output)
613         result.errors.extend(errors)
614         result.failures.extend(failures)
615         result.testsRun += tests_run
616
617     join_results = staticmethod(join_results)
618
619     class _StringIO(StringIO):
620         def writeln(self, line):
621             self.write("%s\n" % line)
622
623
624 class CythonUnitTestCase(CythonCompileTestCase):
625     def shortDescription(self):
626         return "compiling (%s) tests in %s" % (self.language, self.module)
627
628     def run(self, result=None):
629         if result is None:
630             result = self.defaultTestResult()
631         result.startTest(self)
632         try:
633             self.setUp()
634             try:
635                 self.runCompileTest()
636                 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
637             finally:
638                 check_thread_termination()
639         except Exception:
640             result.addError(self, sys.exc_info())
641             result.stopTest(self)
642         try:
643             self.tearDown()
644         except Exception:
645             pass
646
647 # Someone wrapped this in a:
648 # 'try: import gdb; ... except: include_debugger = False' thing, but don't do 
649 # this, it doesn't work as gdb is a builtin module in GDB. The tests themselves
650 # are doing the skipping. If there's a problem with the tests, please file an 
651 # issue.
652 include_debugger = sys.version_info[:2] > (2, 5)
653
654 def collect_unittests(path, module_prefix, suite, selectors):
655     def file_matches(filename):
656         return filename.startswith("Test") and filename.endswith(".py")
657
658     def package_matches(dirname):
659         return dirname == "Tests"
660
661     loader = unittest.TestLoader()
662     
663     if include_debugger:
664         skipped_dirs = []
665     else:
666         cython_dir = os.path.dirname(os.path.abspath(__file__))
667         skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
668
669     for dirpath, dirnames, filenames in os.walk(path):
670         if dirpath != path and "__init__.py" not in filenames:
671             skipped_dirs.append(dirpath + os.path.sep)
672             continue
673         skip = False
674         for dir in skipped_dirs:
675             if dirpath.startswith(dir):
676                 skip = True
677         if skip:
678             continue
679         parentname = os.path.split(dirpath)[-1]
680         if package_matches(parentname):
681             for f in filenames:
682                 if file_matches(f):
683                     filepath = os.path.join(dirpath, f)[:-len(".py")]
684                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
685                     if not [ 1 for match in selectors if match(modulename) ]:
686                         continue
687                     module = __import__(modulename)
688                     for x in modulename.split('.')[1:]:
689                         module = getattr(module, x)
690                     suite.addTests([loader.loadTestsFromModule(module)])
691
692
693
694 def collect_doctests(path, module_prefix, suite, selectors):
695     def package_matches(dirname):
696         if dirname == 'Debugger' and not include_debugger:
697             return False
698         return dirname not in ("Mac", "Distutils", "Plex")
699     def file_matches(filename):
700         filename, ext = os.path.splitext(filename)
701         blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb', 
702                      'TestLibCython']
703         return (ext == '.py' and not
704                 '~' in filename and not
705                 '#' in filename and not
706                 filename.startswith('.') and not
707                 filename in blacklist)
708     import doctest, types
709     for dirpath, dirnames, filenames in os.walk(path):
710         for dir in list(dirnames):
711             if not package_matches(dir):
712                 dirnames.remove(dir)
713         for f in filenames:
714             if file_matches(f):
715                 if not f.endswith('.py'): continue
716                 filepath = os.path.join(dirpath, f)
717                 if os.path.getsize(filepath) == 0: continue
718                 filepath = filepath[:-len(".py")]
719                 modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
720                 if not [ 1 for match in selectors if match(modulename) ]:
721                     continue
722                 module = __import__(modulename)
723                 for x in modulename.split('.')[1:]:
724                     module = getattr(module, x)
725                 if hasattr(module, "__doc__") or hasattr(module, "__test__"):
726                     try:
727                         suite.addTest(doctest.DocTestSuite(module))
728                     except ValueError: # no tests
729                         pass
730
731
732 class EndToEndTest(unittest.TestCase):
733     """
734     This is a test of build/*.srctree files, where srctree defines a full
735     directory structure and its header gives a list of commands to run.
736     """
737     cython_root = os.path.dirname(os.path.abspath(__file__))
738     
739     def __init__(self, treefile, workdir, cleanup_workdir=True):
740         self.treefile = treefile
741         self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
742         self.cleanup_workdir = cleanup_workdir
743         cython_syspath = self.cython_root
744         for path in sys.path[::-1]:
745             if path.startswith(self.cython_root):
746                 # Py3 installation and refnanny build prepend their
747                 # fixed paths to sys.path => prefer that over the
748                 # generic one
749                 cython_syspath = path + os.pathsep + cython_syspath
750         self.cython_syspath = cython_syspath
751         unittest.TestCase.__init__(self)
752
753     def shortDescription(self):
754         return "End-to-end %s" % self.treefile
755
756     def setUp(self):
757         from Cython.TestUtils import unpack_source_tree
758         _, self.commands = unpack_source_tree(
759             os.path.join('tests', 'build', self.treefile), self.workdir)
760         self.old_dir = os.getcwd()
761         os.chdir(self.workdir)
762         if self.workdir not in sys.path:
763             sys.path.insert(0, self.workdir)
764
765     def tearDown(self):
766         if self.cleanup_workdir:
767             shutil.rmtree(self.workdir)
768         os.chdir(self.old_dir)
769     
770     def runTest(self):
771         commands = (self.commands
772             .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
773             .replace("PYTHON", sys.executable))
774         try:
775             old_path = os.environ.get('PYTHONPATH')
776             os.environ['PYTHONPATH'] = self.cython_syspath + os.pathsep + os.path.join(self.cython_syspath, (old_path or ''))
777             for command in commands.split('\n'):
778                 if sys.version_info[:2] >= (2,4):
779                     import subprocess
780                     p = subprocess.Popen(commands,
781                                          stderr=subprocess.PIPE,
782                                          stdout=subprocess.PIPE,
783                                          shell=True)
784                     out, err = p.communicate()
785                     res = p.returncode
786                     if res != 0:
787                         print(command)
788                         print(out)
789                         print(err)
790                 else:
791                     res = os.system(command)
792                 self.assertEqual(0, res, "non-zero exit status")
793         finally:
794             if old_path:
795                 os.environ['PYTHONPATH'] = old_path
796             else:
797                 del os.environ['PYTHONPATH']
798
799
800 # TODO: Support cython_freeze needed here as well.
801 # TODO: Windows support.
802
803 class EmbedTest(unittest.TestCase):
804     
805     working_dir = "Demos/embed"
806     
807     def setUp(self):
808         self.old_dir = os.getcwd()
809         os.chdir(self.working_dir)
810         os.system(
811             "make PYTHON='%s' clean > /dev/null" % sys.executable)
812     
813     def tearDown(self):
814         try:
815             os.system(
816                 "make PYTHON='%s' clean > /dev/null" % sys.executable)
817         except:
818             pass
819         os.chdir(self.old_dir)
820         
821     def test_embed(self):
822         from distutils import sysconfig
823         libname = sysconfig.get_config_var('LIBRARY')
824         libdir = sysconfig.get_config_var('LIBDIR')
825         if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
826             libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
827             if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
828                 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
829                 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
830                     # report the error for the original directory
831                     libdir = sysconfig.get_config_var('LIBDIR')
832         self.assert_(os.system(
833             "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
834         try:
835             os.remove('make.output')
836         except OSError:
837             pass
838
839 class MissingDependencyExcluder:
840     def __init__(self, deps):
841         # deps: { module name : matcher func }
842         self.exclude_matchers = []
843         for mod, matcher in deps.items():
844             try:
845                 __import__(mod)
846             except ImportError:
847                 self.exclude_matchers.append(matcher)
848         self.tests_missing_deps = []
849     def __call__(self, testname):
850         for matcher in self.exclude_matchers:
851             if matcher(testname):
852                 self.tests_missing_deps.append(testname)
853                 return True
854         return False
855
856 class VersionDependencyExcluder:
857     def __init__(self, deps):
858         # deps: { version : matcher func }
859         from sys import version_info
860         self.exclude_matchers = []
861         for ver, (compare, matcher) in deps.items():
862             if compare(version_info, ver):
863                 self.exclude_matchers.append(matcher)
864         self.tests_missing_deps = []
865     def __call__(self, testname):
866         for matcher in self.exclude_matchers:
867             if matcher(testname):
868                 self.tests_missing_deps.append(testname)
869                 return True
870         return False
871
872 class FileListExcluder:
873
874     def __init__(self, list_file):
875         self.excludes = {}
876         f = open(list_file)
877         try:
878             for line in f.readlines():
879                 line = line.strip()
880                 if line and line[0] != '#':
881                     self.excludes[line.split()[0]] = True
882         finally:
883             f.close()
884                 
885     def __call__(self, testname):
886         return testname in self.excludes or testname.split('.')[-1] in self.excludes
887
888 def refactor_for_py3(distdir, cy3_dir):
889     # need to convert Cython sources first
890     import lib2to3.refactor
891     from distutils.util import copydir_run_2to3
892     fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
893                if fix.split('fix_')[-1] not in ('next',)
894                ]
895     if not os.path.exists(cy3_dir):
896         os.makedirs(cy3_dir)
897     import distutils.log as dlog
898     dlog.set_threshold(dlog.INFO)
899     copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
900                      template = '''
901                      global-exclude *
902                      graft Cython
903                      recursive-exclude Cython *
904                      recursive-include Cython *.py *.pyx *.pxd
905                      ''')
906     sys.path.insert(0, cy3_dir)
907
908 class PendingThreadsError(RuntimeError):
909     pass
910
911 threads_seen = []
912
913 def check_thread_termination(ignore_seen=True):
914     if threading is None: # no threading enabled in CPython
915         return
916     current = threading.currentThread()
917     blocking_threads = []
918     for t in threading.enumerate():
919         if not t.isAlive() or t == current:
920             continue
921         t.join(timeout=2)
922         if t.isAlive():
923             if not ignore_seen:
924                 blocking_threads.append(t)
925                 continue
926             for seen in threads_seen:
927                 if t is seen:
928                     break
929             else:
930                 threads_seen.append(t)
931                 blocking_threads.append(t)
932     if not blocking_threads:
933         return
934     sys.stderr.write("warning: left-over threads found after running test:\n")
935     for t in blocking_threads:
936         sys.stderr.write('...%s\n'  % repr(t))
937     raise PendingThreadsError("left-over threads found after running test")
938
939 def main():
940     from optparse import OptionParser
941     parser = OptionParser()
942     parser.add_option("--no-cleanup", dest="cleanup_workdir",
943                       action="store_false", default=True,
944                       help="do not delete the generated C files (allows passing --no-cython on next run)")
945     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
946                       action="store_false", default=True,
947                       help="do not delete the generated shared libary files (allows manual module experimentation)")
948     parser.add_option("--no-cython", dest="with_cython",
949                       action="store_false", default=True,
950                       help="do not run the Cython compiler, only the C compiler")
951     parser.add_option("--no-c", dest="use_c",
952                       action="store_false", default=True,
953                       help="do not test C compilation")
954     parser.add_option("--no-cpp", dest="use_cpp",
955                       action="store_false", default=True,
956                       help="do not test C++ compilation")
957     parser.add_option("--no-unit", dest="unittests",
958                       action="store_false", default=True,
959                       help="do not run the unit tests")
960     parser.add_option("--no-doctest", dest="doctests",
961                       action="store_false", default=True,
962                       help="do not run the doctests")
963     parser.add_option("--no-file", dest="filetests",
964                       action="store_false", default=True,
965                       help="do not run the file based tests")
966     parser.add_option("--no-pyregr", dest="pyregr",
967                       action="store_false", default=True,
968                       help="do not run the regression tests of CPython in tests/pyregr/")    
969     parser.add_option("--cython-only", dest="cython_only",
970                       action="store_true", default=False,
971                       help="only compile pyx to c, do not run C compiler or run the tests")
972     parser.add_option("--no-refnanny", dest="with_refnanny",
973                       action="store_false", default=True,
974                       help="do not regression test reference counting")
975     parser.add_option("--no-fork", dest="fork",
976                       action="store_false", default=True,
977                       help="do not fork to run tests")
978     parser.add_option("--sys-pyregr", dest="system_pyregr",
979                       action="store_true", default=False,
980                       help="run the regression tests of the CPython installation")
981     parser.add_option("-x", "--exclude", dest="exclude",
982                       action="append", metavar="PATTERN",
983                       help="exclude tests matching the PATTERN")
984     parser.add_option("-C", "--coverage", dest="coverage",
985                       action="store_true", default=False,
986                       help="collect source coverage data for the Compiler")
987     parser.add_option("--coverage-xml", dest="coverage_xml",
988                       action="store_true", default=False,
989                       help="collect source coverage data for the Compiler in XML format")
990     parser.add_option("-A", "--annotate", dest="annotate_source",
991                       action="store_true", default=True,
992                       help="generate annotated HTML versions of the test source files")
993     parser.add_option("--no-annotate", dest="annotate_source",
994                       action="store_false",
995                       help="do not generate annotated HTML versions of the test source files")
996     parser.add_option("-v", "--verbose", dest="verbosity",
997                       action="count", default=0,
998                       help="display test progress, pass twice to print test names")
999     parser.add_option("-T", "--ticket", dest="tickets",
1000                       action="append",
1001                       help="a bug ticket number to run the respective test in 'tests/*'")
1002     parser.add_option("-3", dest="language_level",
1003                       action="store_const", const=3, default=2,
1004                       help="set language level to Python 3 (useful for running the CPython regression tests)'")
1005     parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1006                       help="write test results in XML to directory DIR")
1007     parser.add_option("--exit-ok", dest="exit_ok", default=False,
1008                       action="store_true",
1009                       help="exit without error code even on test failures")
1010
1011     options, cmd_args = parser.parse_args()
1012
1013     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1014     ROOTDIR = os.path.join(DISTDIR, 'tests')
1015     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1016
1017     if sys.version_info[0] >= 3:
1018         options.doctests = False
1019         if options.with_cython:
1020             try:
1021                 # try if Cython is installed in a Py3 version
1022                 import Cython.Compiler.Main
1023             except Exception:
1024                 # back out anything the import process loaded, then
1025                 # 2to3 the Cython sources to make them re-importable
1026                 cy_modules = [ name for name in sys.modules
1027                                if name == 'Cython' or name.startswith('Cython.') ]
1028                 for name in cy_modules:
1029                     del sys.modules[name]
1030                 # hasn't been refactored yet - do it now
1031                 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1032                 if sys.version_info >= (3,1):
1033                     refactor_for_py3(DISTDIR, cy3_dir)
1034                 elif os.path.isdir(cy3_dir):
1035                     sys.path.insert(0, cy3_dir)
1036                 else:
1037                     options.with_cython = False
1038
1039     WITH_CYTHON = options.with_cython
1040
1041     if options.coverage or options.coverage_xml:
1042         if not WITH_CYTHON:
1043             options.coverage = options.coverage_xml = False
1044         else:
1045             from coverage import coverage as _coverage
1046             coverage = _coverage(branch=True)
1047             coverage.erase()
1048             coverage.start()
1049
1050     if WITH_CYTHON:
1051         global CompilationOptions, pyrex_default_options, cython_compile
1052         from Cython.Compiler.Main import \
1053             CompilationOptions, \
1054             default_options as pyrex_default_options, \
1055             compile as cython_compile
1056         from Cython.Compiler import Errors
1057         Errors.LEVEL = 0 # show all warnings
1058         from Cython.Compiler import Options
1059         Options.generate_cleanup_code = 3   # complete cleanup code
1060         from Cython.Compiler import DebugFlags
1061         DebugFlags.debug_temp_code_comments = 1
1062
1063     # RUN ALL TESTS!
1064     UNITTEST_MODULE = "Cython"
1065     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1066     if WITH_CYTHON:
1067         if os.path.exists(WORKDIR):
1068             for path in os.listdir(WORKDIR):
1069                 if path in ("support", "Cy3"): continue
1070                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1071     if not os.path.exists(WORKDIR):
1072         os.makedirs(WORKDIR)
1073
1074     sys.stderr.write("Python %s\n" % sys.version)
1075     sys.stderr.write("\n")
1076     if WITH_CYTHON:
1077         from Cython.Compiler.Version import version
1078         sys.stderr.write("Running tests against Cython %s\n" % version)
1079     else:
1080         sys.stderr.write("Running tests without Cython.\n")
1081
1082     if options.with_refnanny:
1083         from pyximport.pyxbuild import pyx_to_dll
1084         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1085                              build_in_temp=True,
1086                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
1087         sys.path.insert(0, os.path.split(libpath)[0])
1088         CFLAGS.append("-DCYTHON_REFNANNY=1")
1089
1090     if options.xml_output_dir and options.fork:
1091         # doesn't currently work together
1092         sys.stderr.write("Disabling forked testing to support XML test output\n")
1093         options.fork = False
1094
1095     if WITH_CYTHON and options.language_level == 3:
1096         sys.stderr.write("Using Cython language level 3.\n")
1097
1098     sys.stderr.write("\n")
1099
1100     test_bugs = False
1101     if options.tickets:
1102         for ticket_number in options.tickets:
1103             test_bugs = True
1104             cmd_args.append('.*T%s$' % ticket_number)
1105     if not test_bugs:
1106         for selector in cmd_args:
1107             if selector.startswith('bugs'):
1108                 test_bugs = True
1109
1110     import re
1111     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1112     if not selectors:
1113         selectors = [ lambda x:True ]
1114
1115     # Chech which external modules are not present and exclude tests
1116     # which depends on them (by prefix)
1117
1118     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
1119     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
1120     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1121
1122     if options.exclude:
1123         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1124     
1125     if not test_bugs:
1126         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1127     
1128     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1129         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1130
1131     languages = []
1132     if options.use_c:
1133         languages.append('c')
1134     if options.use_cpp:
1135         languages.append('cpp')
1136
1137     test_suite = unittest.TestSuite()
1138
1139     if options.unittests:
1140         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1141
1142     if options.doctests:
1143         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1144
1145     if options.filetests and languages:
1146         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1147                                 options.annotate_source, options.cleanup_workdir,
1148                                 options.cleanup_sharedlibs, options.pyregr,
1149                                 options.cython_only, languages, test_bugs,
1150                                 options.fork, options.language_level)
1151         test_suite.addTest(filetests.build_suite())
1152
1153     if options.system_pyregr and languages:
1154         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1155                                 options.annotate_source, options.cleanup_workdir,
1156                                 options.cleanup_sharedlibs, True,
1157                                 options.cython_only, languages, test_bugs,
1158                                 options.fork, options.language_level)
1159         test_suite.addTest(
1160             filetests.handle_directory(
1161                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1162                 'pyregr'))
1163
1164     if options.xml_output_dir:
1165         from Cython.Tests.xmlrunner import XMLTestRunner
1166         test_runner = XMLTestRunner(output=options.xml_output_dir,
1167                                     verbose=options.verbosity > 0)
1168     else:
1169         test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1170
1171     result = test_runner.run(test_suite)
1172
1173     if options.coverage or options.coverage_xml:
1174         coverage.stop()
1175         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1176         modules = [ module for name, module in sys.modules.items()
1177                     if module is not None and
1178                     name.startswith('Cython.Compiler.') and 
1179                     name[len('Cython.Compiler.'):] not in ignored_modules ]
1180         if options.coverage:
1181             coverage.report(modules, show_missing=0)
1182         if options.coverage_xml:
1183             coverage.xml_report(modules, outfile="coverage-report.xml")
1184
1185     if missing_dep_excluder.tests_missing_deps:
1186         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1187         for test in missing_dep_excluder.tests_missing_deps:
1188             sys.stderr.write("   %s\n" % test)
1189
1190     if options.with_refnanny:
1191         import refnanny
1192         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1193
1194     print("ALL DONE")
1195
1196     if options.exit_ok:
1197         return_code = 0
1198     else:
1199         return_code = not result.wasSuccessful()
1200
1201     try:
1202         check_thread_termination(ignore_seen=False)
1203         sys.exit(return_code)
1204     except PendingThreadsError:
1205         # normal program exit won't kill the threads, do it the hard way here
1206         os._exit(return_code)
1207
1208 if __name__ == '__main__':
1209     try:
1210         main()
1211     except SystemExit: # <= Py2.4 ...
1212         raise
1213     except Exception:
1214         traceback.print_exc()
1215         try:
1216             check_thread_termination(ignore_seen=False)
1217         except PendingThreadsError:
1218             # normal program exit won't kill the threads, do it the hard way here
1219             os._exit(1)