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