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