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