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