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