test runner: check for thread termination after each test
[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 try:
14     from StringIO import StringIO
15 except ImportError:
16     from io import StringIO
17
18 try:
19     import cPickle as pickle
20 except ImportError:
21     import pickle
22
23 try:
24     import threading
25 except ImportError: # No threads, no problems
26     threading = None
27
28
29 WITH_CYTHON = True
30
31 from distutils.dist import Distribution
32 from distutils.core import Extension
33 from distutils.command.build_ext import build_ext as _build_ext
34 distutils_distro = Distribution()
35
36 TEST_DIRS = ['compile', 'errors', 'run', 'wrappers', 'pyregr', 'build']
37 TEST_RUN_DIRS = ['run', 'wrappers', 'pyregr']
38
39 # Lists external modules, and a matcher matching tests
40 # which should be excluded if the module is not present.
41 EXT_DEP_MODULES = {
42     'numpy' : re.compile('.*\.numpy_.*').match,
43     'pstats' : re.compile('.*\.pstats_.*').match,
44     'posix' : re.compile('.*\.posix_.*').match,
45 }
46
47 def get_numpy_include_dirs():
48     import numpy
49     return [numpy.get_include()]
50
51 EXT_DEP_INCLUDES = [
52     # test name matcher , callable returning list
53     (re.compile('numpy_.*').match, get_numpy_include_dirs),
54 ]
55
56 VER_DEP_MODULES = {
57     # tests are excluded if 'CurrentPythonVersion OP VersionTuple', i.e.
58     # (2,4) : (operator.le, ...) excludes ... when PyVer <= 2.4.x
59     (2,5) : (operator.lt, lambda x: x in ['run.any',
60                                           'run.all',
61                                           ]),
62     (2,4) : (operator.le, lambda x: x in ['run.extern_builtins_T258'
63                                           ]),
64     (2,6) : (operator.lt, lambda x: x in ['run.print_function',
65                                           'run.cython3',
66                                           ]),
67     # The next line should start (3,); but this is a dictionary, so
68     # we can only have one (3,) key.  Since 2.7 is supposed to be the
69     # last 2.x release, things would have to change drastically for this
70     # to be unsafe...
71     (2,999): (operator.lt, lambda x: x in ['run.special_methods_T561_py3']),
72     (3,): (operator.ge, lambda x: x in ['run.non_future_division',
73                                         'compile.extsetslice',
74                                         'compile.extdelslice',
75                                         'run.special_methods_T561_py2']),
76 }
77
78 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
79 CFLAGS = os.getenv('CFLAGS', '').split()
80
81 class build_ext(_build_ext):
82     def build_extension(self, ext):
83         if ext.language == 'c++':
84             try:
85                 try: # Py2.7+ & Py3.2+ 
86                     compiler_obj = self.compiler_obj
87                 except AttributeError:
88                     compiler_obj = self.compiler
89                 compiler_obj.compiler_so.remove('-Wstrict-prototypes')
90             except Exception:
91                 pass
92         _build_ext.build_extension(self, ext)
93
94 class ErrorWriter(object):
95     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
96     def __init__(self):
97         self.output = []
98         self.write = self.output.append
99
100     def _collect(self, collect_errors, collect_warnings):
101         s = ''.join(self.output)
102         result = []
103         for line in s.split('\n'):
104             match = self.match_error(line)
105             if match:
106                 is_warning, line, column, message = match.groups()
107                 if (is_warning and collect_warnings) or \
108                         (not is_warning and collect_errors):
109                     result.append( (int(line), int(column), message.strip()) )
110         result.sort()
111         return [ "%d:%d: %s" % values for values in result ]
112
113     def geterrors(self):
114         return self._collect(True, False)
115
116     def getwarnings(self):
117         return self._collect(False, True)
118
119     def getall(self):
120         return self._collect(True, True)
121
122 class TestBuilder(object):
123     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
124                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
125                  languages, test_bugs, fork, language_level):
126         self.rootdir = rootdir
127         self.workdir = workdir
128         self.selectors = selectors
129         self.exclude_selectors = exclude_selectors
130         self.annotate = annotate
131         self.cleanup_workdir = cleanup_workdir
132         self.cleanup_sharedlibs = cleanup_sharedlibs
133         self.with_pyregr = with_pyregr
134         self.cython_only = cython_only
135         self.languages = languages
136         self.test_bugs = test_bugs
137         self.fork = fork
138         self.language_level = language_level
139
140     def build_suite(self):
141         suite = unittest.TestSuite()
142         test_dirs = TEST_DIRS
143         filenames = os.listdir(self.rootdir)
144         filenames.sort()
145         for filename in filenames:
146             if not WITH_CYTHON and filename == "errors":
147                 # we won't get any errors without running Cython
148                 continue
149             path = os.path.join(self.rootdir, filename)
150             if os.path.isdir(path) and filename in test_dirs:
151                 if filename == 'pyregr' and not self.with_pyregr:
152                     continue
153                 suite.addTest(
154                     self.handle_directory(path, filename))
155         if sys.platform not in ['win32'] and sys.version_info[0] < 3:
156             # Non-Windows makefile, can't run Cython under Py3.
157             if [1 for selector in self.selectors if selector("embedded")]:
158                 suite.addTest(unittest.makeSuite(EmbedTest))
159         return suite
160
161     def handle_directory(self, path, context):
162         workdir = os.path.join(self.workdir, context)
163         if not os.path.exists(workdir):
164             os.makedirs(workdir)
165
166         expect_errors = (context == 'errors')
167         suite = unittest.TestSuite()
168         filenames = os.listdir(path)
169         filenames.sort()
170         for filename in filenames:
171             if context == "build" and filename.endswith(".srctree"):
172                 if not [ 1 for match in self.selectors if match(filename) ]:
173                     continue
174                 suite.addTest(EndToEndTest(filename, workdir, self.cleanup_workdir))
175                 continue
176             if not (filename.endswith(".pyx") or filename.endswith(".py")):
177                 continue
178             if filename.startswith('.'): continue # certain emacs backup files
179             if context == 'pyregr' and not filename.startswith('test_'):
180                 continue
181             module = os.path.splitext(filename)[0]
182             fqmodule = "%s.%s" % (context, module)
183             if not [ 1 for match in self.selectors
184                      if match(fqmodule) ]:
185                 continue
186             if self.exclude_selectors:
187                 if [1 for match in self.exclude_selectors if match(fqmodule)]:
188                     continue
189             if context in TEST_RUN_DIRS:
190                 if module.startswith("test_"):
191                     test_class = CythonUnitTestCase
192                 else:
193                     test_class = CythonRunTestCase
194             else:
195                 test_class = CythonCompileTestCase
196             for test in self.build_tests(test_class, path, workdir,
197                                          module, expect_errors):
198                 suite.addTest(test)
199             if context == 'run' and filename.endswith('.py'):
200                 # additionally test file in real Python
201                 suite.addTest(PureDoctestTestCase(module, os.path.join(path, filename)))
202         return suite
203
204     def build_tests(self, test_class, path, workdir, module, expect_errors):
205         if expect_errors:
206             if 'cpp' in module and 'cpp' in self.languages:
207                 languages = ['cpp']
208             else:
209                 languages = self.languages[:1]
210         else:
211             languages = self.languages
212         if 'cpp' in module and 'c' in languages:
213             languages = list(languages)
214             languages.remove('c')
215         tests = [ self.build_test(test_class, path, workdir, module,
216                                   language, expect_errors)
217                   for language in languages ]
218         return tests
219
220     def build_test(self, test_class, path, workdir, module,
221                    language, expect_errors):
222         workdir = os.path.join(workdir, language)
223         if not os.path.exists(workdir):
224             os.makedirs(workdir)
225         return test_class(path, workdir, module,
226                           language=language,
227                           expect_errors=expect_errors,
228                           annotate=self.annotate,
229                           cleanup_workdir=self.cleanup_workdir,
230                           cleanup_sharedlibs=self.cleanup_sharedlibs,
231                           cython_only=self.cython_only,
232                           fork=self.fork,
233                           language_level=self.language_level)
234
235 class CythonCompileTestCase(unittest.TestCase):
236     def __init__(self, test_directory, workdir, module, language='c',
237                  expect_errors=False, annotate=False, cleanup_workdir=True,
238                  cleanup_sharedlibs=True, cython_only=False, fork=True,
239                  language_level=2):
240         self.test_directory = test_directory
241         self.workdir = workdir
242         self.module = module
243         self.language = language
244         self.expect_errors = expect_errors
245         self.annotate = annotate
246         self.cleanup_workdir = cleanup_workdir
247         self.cleanup_sharedlibs = cleanup_sharedlibs
248         self.cython_only = cython_only
249         self.fork = fork
250         self.language_level = language_level
251         unittest.TestCase.__init__(self)
252
253     def shortDescription(self):
254         return "compiling (%s) %s" % (self.language, self.module)
255
256     def setUp(self):
257         if self.workdir not in sys.path:
258             sys.path.insert(0, self.workdir)
259
260     def tearDown(self):
261         try:
262             sys.path.remove(self.workdir)
263         except ValueError:
264             pass
265         try:
266             del sys.modules[self.module]
267         except KeyError:
268             pass
269         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
270         cleanup_lib_files = self.cleanup_sharedlibs
271         if os.path.exists(self.workdir):
272             for rmfile in os.listdir(self.workdir):
273                 if not cleanup_c_files:
274                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
275                         continue
276                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
277                     continue
278                 if self.annotate and rmfile.endswith(".html"):
279                     continue
280                 try:
281                     rmfile = os.path.join(self.workdir, rmfile)
282                     if os.path.isdir(rmfile):
283                         shutil.rmtree(rmfile, ignore_errors=True)
284                     else:
285                         os.remove(rmfile)
286                 except IOError:
287                     pass
288         else:
289             os.makedirs(self.workdir)
290
291     def runTest(self):
292         self.runCompileTest()
293
294     def runCompileTest(self):
295         self.compile(self.test_directory, self.module, self.workdir,
296                      self.test_directory, self.expect_errors, self.annotate)
297
298     def find_module_source_file(self, source_file):
299         if not os.path.exists(source_file):
300             source_file = source_file[:-1]
301         return source_file
302
303     def build_target_filename(self, module_name):
304         target = '%s.%s' % (module_name, self.language)
305         return target
306
307     def copy_related_files(self, test_directory, target_directory, module_name):
308         is_related = re.compile('%s_.*[.].*' % module_name).match
309         for filename in os.listdir(test_directory):
310             if is_related(filename):
311                 shutil.copy(os.path.join(test_directory, filename),
312                             target_directory)
313
314     def find_source_files(self, workdir, module_name):
315         is_related = re.compile('%s_.*[.]%s' % (module_name, self.language)).match
316         return [self.build_target_filename(module_name)] + [
317             filename for filename in os.listdir(workdir)
318             if is_related(filename) and os.path.isfile(os.path.join(workdir, filename)) ]
319
320     def split_source_and_output(self, test_directory, module, workdir):
321         source_file = self.find_module_source_file(os.path.join(test_directory, module) + '.pyx')
322         source_and_output = codecs.open(source_file, 'rU', 'ISO-8859-1')
323         try:
324             out = codecs.open(os.path.join(workdir, module + os.path.splitext(source_file)[1]),
325                               'w', 'ISO-8859-1')
326             for line in source_and_output:
327                 last_line = line
328                 if line.startswith("_ERRORS"):
329                     out.close()
330                     out = ErrorWriter()
331                 else:
332                     out.write(line)
333         finally:
334             source_and_output.close()
335         try:
336             geterrors = out.geterrors
337         except AttributeError:
338             out.close()
339             return []
340         else:
341             return geterrors()
342
343     def run_cython(self, test_directory, module, targetdir, incdir, annotate):
344         include_dirs = INCLUDE_DIRS[:]
345         if incdir:
346             include_dirs.append(incdir)
347         source = self.find_module_source_file(
348             os.path.join(test_directory, module + '.pyx'))
349         target = os.path.join(targetdir, self.build_target_filename(module))
350         options = CompilationOptions(
351             pyrex_default_options,
352             include_path = include_dirs,
353             output_file = target,
354             annotate = annotate,
355             use_listing_file = False,
356             cplus = self.language == 'cpp',
357             language_level = self.language_level,
358             generate_pxi = False,
359             evaluate_tree_assertions = True,
360             )
361         cython_compile(source, options=options,
362                        full_module_name=module)
363
364     def run_distutils(self, test_directory, module, workdir, incdir):
365         cwd = os.getcwd()
366         os.chdir(workdir)
367         try:
368             build_extension = build_ext(distutils_distro)
369             build_extension.include_dirs = INCLUDE_DIRS[:]
370             if incdir:
371                 build_extension.include_dirs.append(incdir)
372             build_extension.finalize_options()
373             ext_include_dirs = []
374             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
375                 if match(module):
376                     ext_include_dirs += get_additional_include_dirs()
377             self.copy_related_files(test_directory, workdir, module)
378             extension = Extension(
379                 module,
380                 sources = self.find_source_files(workdir, module),
381                 include_dirs = ext_include_dirs,
382                 extra_compile_args = CFLAGS,
383                 )
384             if self.language == 'cpp':
385                 extension.language = 'c++'
386             build_extension.extensions = [extension]
387             build_extension.build_temp = workdir
388             build_extension.build_lib  = workdir
389             build_extension.run()
390         finally:
391             os.chdir(cwd)
392
393     def compile(self, test_directory, module, workdir, incdir,
394                 expect_errors, annotate):
395         expected_errors = errors = ()
396         if expect_errors:
397             expected_errors = self.split_source_and_output(
398                 test_directory, module, workdir)
399             test_directory = workdir
400
401         if WITH_CYTHON:
402             old_stderr = sys.stderr
403             try:
404                 sys.stderr = ErrorWriter()
405                 self.run_cython(test_directory, module, workdir, incdir, annotate)
406                 errors = sys.stderr.geterrors()
407             finally:
408                 sys.stderr = old_stderr
409
410         if errors or expected_errors:
411             try:
412                 for expected, error in zip(expected_errors, errors):
413                     self.assertEquals(expected, error)
414                 if len(errors) < len(expected_errors):
415                     expected_error = expected_errors[len(errors)]
416                     self.assertEquals(expected_error, None)
417                 elif len(errors) > len(expected_errors):
418                     unexpected_error = errors[len(expected_errors)]
419                     self.assertEquals(None, unexpected_error)
420             except AssertionError:
421                 print("\n=== Expected errors: ===")
422                 print('\n'.join(expected_errors))
423                 print("\n\n=== Got errors: ===")
424                 print('\n'.join(errors))
425                 print('\n')
426                 raise
427         else:
428             if not self.cython_only:
429                 self.run_distutils(test_directory, module, workdir, incdir)
430
431 class CythonRunTestCase(CythonCompileTestCase):
432     def shortDescription(self):
433         return "compiling (%s) and running %s" % (self.language, self.module)
434
435     def run(self, result=None):
436         if result is None:
437             result = self.defaultTestResult()
438         result.startTest(self)
439         try:
440             self.setUp()
441             try:
442                 self.runCompileTest()
443                 if not self.cython_only:
444                     self.run_doctests(self.module, result)
445             finally:
446                 check_thread_termination()
447         except Exception:
448             result.addError(self, sys.exc_info())
449             result.stopTest(self)
450         try:
451             self.tearDown()
452         except Exception:
453             pass
454
455     def run_doctests(self, module_name, result):
456         if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
457             doctest.DocTestSuite(module_name).run(result)
458             gc.collect()
459             return
460
461         # fork to make sure we do not keep the tested module loaded
462         result_handle, result_file = tempfile.mkstemp()
463         os.close(result_handle)
464         child_id = os.fork()
465         if not child_id:
466             result_code = 0
467             try:
468                 try:
469                     tests = None
470                     try:
471                         partial_result = PartialTestResult(result)
472                         tests = doctest.DocTestSuite(module_name)
473                         tests.run(partial_result)
474                         gc.collect()
475                     except Exception:
476                         if tests is None:
477                             # importing failed, try to fake a test class
478                             tests = _FakeClass(
479                                 failureException=sys.exc_info()[1],
480                                 _shortDescription=self.shortDescription(),
481                                 module_name=None)
482                         partial_result.addError(tests, sys.exc_info())
483                         result_code = 1
484                     output = open(result_file, 'wb')
485                     pickle.dump(partial_result.data(), output)
486                 except:
487                     import traceback
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 def check_thread_termination():
852     if threading is None: # no threading enabled in CPython
853         return
854     current = threading.currentThread()
855     blocking_threads = []
856     for t in threading.enumerate():
857         if not t.isAlive() or t == current:
858             continue
859         t.join(timeout=2)
860         if t.isAlive():
861             blocking_threads.append(t)
862     if not blocking_threads:
863         return
864     sys.stderr.write("warning: left-over threads found after running test:\n")
865     for t in blocking_threads:
866         sys.stderr.write('...%s\n'  % repr(t))
867     raise RuntimeError("left-over threads found after running test")
868
869 if __name__ == '__main__':
870     from optparse import OptionParser
871     parser = OptionParser()
872     parser.add_option("--no-cleanup", dest="cleanup_workdir",
873                       action="store_false", default=True,
874                       help="do not delete the generated C files (allows passing --no-cython on next run)")
875     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
876                       action="store_false", default=True,
877                       help="do not delete the generated shared libary files (allows manual module experimentation)")
878     parser.add_option("--no-cython", dest="with_cython",
879                       action="store_false", default=True,
880                       help="do not run the Cython compiler, only the C compiler")
881     parser.add_option("--no-c", dest="use_c",
882                       action="store_false", default=True,
883                       help="do not test C compilation")
884     parser.add_option("--no-cpp", dest="use_cpp",
885                       action="store_false", default=True,
886                       help="do not test C++ compilation")
887     parser.add_option("--no-unit", dest="unittests",
888                       action="store_false", default=True,
889                       help="do not run the unit tests")
890     parser.add_option("--no-doctest", dest="doctests",
891                       action="store_false", default=True,
892                       help="do not run the doctests")
893     parser.add_option("--no-file", dest="filetests",
894                       action="store_false", default=True,
895                       help="do not run the file based tests")
896     parser.add_option("--no-pyregr", dest="pyregr",
897                       action="store_false", default=True,
898                       help="do not run the regression tests of CPython in tests/pyregr/")    
899     parser.add_option("--cython-only", dest="cython_only",
900                       action="store_true", default=False,
901                       help="only compile pyx to c, do not run C compiler or run the tests")
902     parser.add_option("--no-refnanny", dest="with_refnanny",
903                       action="store_false", default=True,
904                       help="do not regression test reference counting")
905     parser.add_option("--no-fork", dest="fork",
906                       action="store_false", default=True,
907                       help="do not fork to run tests")
908     parser.add_option("--sys-pyregr", dest="system_pyregr",
909                       action="store_true", default=False,
910                       help="run the regression tests of the CPython installation")
911     parser.add_option("-x", "--exclude", dest="exclude",
912                       action="append", metavar="PATTERN",
913                       help="exclude tests matching the PATTERN")
914     parser.add_option("-C", "--coverage", dest="coverage",
915                       action="store_true", default=False,
916                       help="collect source coverage data for the Compiler")
917     parser.add_option("--coverage-xml", dest="coverage_xml",
918                       action="store_true", default=False,
919                       help="collect source coverage data for the Compiler in XML format")
920     parser.add_option("-A", "--annotate", dest="annotate_source",
921                       action="store_true", default=True,
922                       help="generate annotated HTML versions of the test source files")
923     parser.add_option("--no-annotate", dest="annotate_source",
924                       action="store_false",
925                       help="do not generate annotated HTML versions of the test source files")
926     parser.add_option("-v", "--verbose", dest="verbosity",
927                       action="count", default=0,
928                       help="display test progress, pass twice to print test names")
929     parser.add_option("-T", "--ticket", dest="tickets",
930                       action="append",
931                       help="a bug ticket number to run the respective test in 'tests/*'")
932     parser.add_option("-3", dest="language_level",
933                       action="store_const", const=3, default=2,
934                       help="set language level to Python 3 (useful for running the CPython regression tests)'")
935     parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
936                       help="write test results in XML to directory DIR")
937     parser.add_option("--exit-ok", dest="exit_ok", default=False,
938                       action="store_true",
939                       help="exit without error code even on test failures")
940
941     options, cmd_args = parser.parse_args()
942
943     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
944     ROOTDIR = os.path.join(DISTDIR, 'tests')
945     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
946
947     if sys.version_info[0] >= 3:
948         options.doctests = False
949         if options.with_cython:
950             try:
951                 # try if Cython is installed in a Py3 version
952                 import Cython.Compiler.Main
953             except Exception:
954                 # back out anything the import process loaded, then
955                 # 2to3 the Cython sources to make them re-importable
956                 cy_modules = [ name for name in sys.modules
957                                if name == 'Cython' or name.startswith('Cython.') ]
958                 for name in cy_modules:
959                     del sys.modules[name]
960                 # hasn't been refactored yet - do it now
961                 cy3_dir = os.path.join(WORKDIR, 'Cy3')
962                 if sys.version_info >= (3,1):
963                     refactor_for_py3(DISTDIR, cy3_dir)
964                 elif os.path.isdir(cy3_dir):
965                     sys.path.insert(0, cy3_dir)
966                 else:
967                     options.with_cython = False
968
969     WITH_CYTHON = options.with_cython
970
971     if options.coverage or options.coverage_xml:
972         if not WITH_CYTHON:
973             options.coverage = options.coverage_xml = False
974         else:
975             from coverage import coverage as _coverage
976             coverage = _coverage(branch=True)
977             coverage.erase()
978             coverage.start()
979
980     if WITH_CYTHON:
981         from Cython.Compiler.Main import \
982             CompilationOptions, \
983             default_options as pyrex_default_options, \
984             compile as cython_compile
985         from Cython.Compiler import Errors
986         Errors.LEVEL = 0 # show all warnings
987         from Cython.Compiler import Options
988         Options.generate_cleanup_code = 3   # complete cleanup code
989         from Cython.Compiler import DebugFlags
990         DebugFlags.debug_temp_code_comments = 1
991
992     # RUN ALL TESTS!
993     UNITTEST_MODULE = "Cython"
994     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
995     if WITH_CYTHON:
996         if os.path.exists(WORKDIR):
997             for path in os.listdir(WORKDIR):
998                 if path in ("support", "Cy3"): continue
999                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1000     if not os.path.exists(WORKDIR):
1001         os.makedirs(WORKDIR)
1002
1003     sys.stderr.write("Python %s\n" % sys.version)
1004     sys.stderr.write("\n")
1005     if WITH_CYTHON:
1006         from Cython.Compiler.Version import version
1007         sys.stderr.write("Running tests against Cython %s\n" % version)
1008     else:
1009         sys.stderr.write("Running tests without Cython.\n")
1010
1011     if options.with_refnanny:
1012         from pyximport.pyxbuild import pyx_to_dll
1013         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1014                              build_in_temp=True,
1015                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
1016         sys.path.insert(0, os.path.split(libpath)[0])
1017         CFLAGS.append("-DCYTHON_REFNANNY=1")
1018
1019     if options.xml_output_dir and options.fork:
1020         # doesn't currently work together
1021         sys.stderr.write("Disabling forked testing to support XML test output\n")
1022         options.fork = False
1023
1024     if WITH_CYTHON and options.language_level == 3:
1025         sys.stderr.write("Using Cython language level 3.\n")
1026
1027     sys.stderr.write("\n")
1028
1029     test_bugs = False
1030     if options.tickets:
1031         for ticket_number in options.tickets:
1032             test_bugs = True
1033             cmd_args.append('.*T%s$' % ticket_number)
1034     if not test_bugs:
1035         for selector in cmd_args:
1036             if selector.startswith('bugs'):
1037                 test_bugs = True
1038
1039     import re
1040     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1041     if not selectors:
1042         selectors = [ lambda x:True ]
1043
1044     # Chech which external modules are not present and exclude tests
1045     # which depends on them (by prefix)
1046
1047     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
1048     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
1049     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1050
1051     if options.exclude:
1052         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1053     
1054     if not test_bugs:
1055         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1056     
1057     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1058         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1059
1060     languages = []
1061     if options.use_c:
1062         languages.append('c')
1063     if options.use_cpp:
1064         languages.append('cpp')
1065
1066     test_suite = unittest.TestSuite()
1067
1068     if options.unittests:
1069         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1070
1071     if options.doctests:
1072         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1073
1074     if options.filetests and languages:
1075         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1076                                 options.annotate_source, options.cleanup_workdir,
1077                                 options.cleanup_sharedlibs, options.pyregr,
1078                                 options.cython_only, languages, test_bugs,
1079                                 options.fork, options.language_level)
1080         test_suite.addTest(filetests.build_suite())
1081
1082     if options.system_pyregr and languages:
1083         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1084                                 options.annotate_source, options.cleanup_workdir,
1085                                 options.cleanup_sharedlibs, True,
1086                                 options.cython_only, languages, test_bugs,
1087                                 options.fork, options.language_level)
1088         test_suite.addTest(
1089             filetests.handle_directory(
1090                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1091                 'pyregr'))
1092
1093     if options.xml_output_dir:
1094         from Cython.Tests.xmlrunner import XMLTestRunner
1095         test_runner = XMLTestRunner(output=options.xml_output_dir,
1096                                     verbose=options.verbosity > 0)
1097     else:
1098         test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1099
1100     result = test_runner.run(test_suite)
1101
1102     if options.coverage or options.coverage_xml:
1103         coverage.stop()
1104         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1105         modules = [ module for name, module in sys.modules.items()
1106                     if module is not None and
1107                     name.startswith('Cython.Compiler.') and 
1108                     name[len('Cython.Compiler.'):] not in ignored_modules ]
1109         if options.coverage:
1110             coverage.report(modules, show_missing=0)
1111         if options.coverage_xml:
1112             coverage.xml_report(modules, outfile="coverage-report.xml")
1113
1114     if missing_dep_excluder.tests_missing_deps:
1115         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1116         for test in missing_dep_excluder.tests_missing_deps:
1117             sys.stderr.write("   %s\n" % test)
1118
1119     if options.with_refnanny:
1120         import refnanny
1121         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1122
1123     if options.exit_ok:
1124         sys.exit(0)
1125     else:
1126         sys.exit(not result.wasSuccessful())