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