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