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