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