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