Merge branch 'master' of https://github.com/cython/cython
[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                    extra_compile_options=None):
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         
354         if extra_compile_options is None:
355             extra_compile_options = {}
356         
357         try:
358             CompilationOptions
359         except NameError:
360             from Cython.Compiler.Main import CompilationOptions
361             from Cython.Compiler.Main import compile as cython_compile
362             from Cython.Compiler.Main import default_options
363         
364         options = CompilationOptions(
365             default_options,
366             include_path = include_dirs,
367             output_file = target,
368             annotate = annotate,
369             use_listing_file = False,
370             cplus = self.language == 'cpp',
371             language_level = self.language_level,
372             generate_pxi = False,
373             evaluate_tree_assertions = True,
374             **extra_compile_options
375             )
376         cython_compile(source, options=options,
377                        full_module_name=module)
378
379     def run_distutils(self, test_directory, module, workdir, incdir, 
380                       extra_extension_args=None):
381         cwd = os.getcwd()
382         os.chdir(workdir)
383         try:
384             build_extension = build_ext(distutils_distro)
385             build_extension.include_dirs = INCLUDE_DIRS[:]
386             if incdir:
387                 build_extension.include_dirs.append(incdir)
388             build_extension.finalize_options()
389             ext_include_dirs = []
390             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
391                 if match(module):
392                     ext_include_dirs += get_additional_include_dirs()
393             self.copy_related_files(test_directory, workdir, module)
394             
395             if extra_extension_args is None:
396                 extra_extension_args = {}
397             
398             extension = Extension(
399                 module,
400                 sources = self.find_source_files(workdir, module),
401                 include_dirs = ext_include_dirs,
402                 extra_compile_args = CFLAGS,
403                 **extra_extension_args
404                 )
405             if self.language == 'cpp':
406                 extension.language = 'c++'
407             build_extension.extensions = [extension]
408             build_extension.build_temp = workdir
409             build_extension.build_lib  = workdir
410             build_extension.run()
411         finally:
412             os.chdir(cwd)
413
414     def compile(self, test_directory, module, workdir, incdir,
415                 expect_errors, annotate):
416         expected_errors = errors = ()
417         if expect_errors:
418             expected_errors = self.split_source_and_output(
419                 test_directory, module, workdir)
420             test_directory = workdir
421
422         if WITH_CYTHON:
423             old_stderr = sys.stderr
424             try:
425                 sys.stderr = ErrorWriter()
426                 self.run_cython(test_directory, module, workdir, incdir, annotate)
427                 errors = sys.stderr.geterrors()
428             finally:
429                 sys.stderr = old_stderr
430
431         if errors or expected_errors:
432             try:
433                 for expected, error in zip(expected_errors, errors):
434                     self.assertEquals(expected, error)
435                 if len(errors) < len(expected_errors):
436                     expected_error = expected_errors[len(errors)]
437                     self.assertEquals(expected_error, None)
438                 elif len(errors) > len(expected_errors):
439                     unexpected_error = errors[len(expected_errors)]
440                     self.assertEquals(None, unexpected_error)
441             except AssertionError:
442                 print("\n=== Expected errors: ===")
443                 print('\n'.join(expected_errors))
444                 print("\n\n=== Got errors: ===")
445                 print('\n'.join(errors))
446                 print('\n')
447                 raise
448         else:
449             if not self.cython_only:
450                 self.run_distutils(test_directory, module, workdir, incdir)
451
452 class CythonRunTestCase(CythonCompileTestCase):
453     def shortDescription(self):
454         return "compiling (%s) and running %s" % (self.language, self.module)
455
456     def run(self, result=None):
457         if result is None:
458             result = self.defaultTestResult()
459         result.startTest(self)
460         try:
461             self.setUp()
462             try:
463                 self.runCompileTest()
464                 if not self.cython_only:
465                     self.run_doctests(self.module, result)
466             finally:
467                 check_thread_termination()
468         except Exception:
469             result.addError(self, sys.exc_info())
470             result.stopTest(self)
471         try:
472             self.tearDown()
473         except Exception:
474             pass
475
476     def run_doctests(self, module_name, result):
477         if sys.version_info[0] >= 3 or not hasattr(os, 'fork') or not self.fork:
478             doctest.DocTestSuite(module_name).run(result)
479             gc.collect()
480             return
481
482         # fork to make sure we do not keep the tested module loaded
483         result_handle, result_file = tempfile.mkstemp()
484         os.close(result_handle)
485         child_id = os.fork()
486         if not child_id:
487             result_code = 0
488             try:
489                 try:
490                     tests = None
491                     try:
492                         partial_result = PartialTestResult(result)
493                         tests = doctest.DocTestSuite(module_name)
494                         tests.run(partial_result)
495                         gc.collect()
496                     except Exception:
497                         if tests is None:
498                             # importing failed, try to fake a test class
499                             tests = _FakeClass(
500                                 failureException=sys.exc_info()[1],
501                                 _shortDescription=self.shortDescription(),
502                                 module_name=None)
503                         partial_result.addError(tests, sys.exc_info())
504                         result_code = 1
505                     output = open(result_file, 'wb')
506                     pickle.dump(partial_result.data(), output)
507                 except:
508                     traceback.print_exc()
509             finally:
510                 try: output.close()
511                 except: pass
512                 os._exit(result_code)
513
514         try:
515             cid, result_code = os.waitpid(child_id, 0)
516             # os.waitpid returns the child's result code in the
517             # upper byte of result_code, and the signal it was
518             # killed by in the lower byte
519             if result_code & 255:
520                 raise Exception("Tests in module '%s' were unexpectedly killed by signal %d"%
521                                 (module_name, result_code & 255))
522             result_code = result_code >> 8
523             if result_code in (0,1):
524                 input = open(result_file, 'rb')
525                 try:
526                     PartialTestResult.join_results(result, pickle.load(input))
527                 finally:
528                     input.close()
529             if result_code:
530                 raise Exception("Tests in module '%s' exited with status %d" %
531                                 (module_name, result_code))
532         finally:
533             try: os.unlink(result_file)
534             except: pass
535
536 class PureDoctestTestCase(unittest.TestCase):
537     def __init__(self, module_name, module_path):
538         self.module_name = module_name
539         self.module_path = module_path
540         unittest.TestCase.__init__(self, 'run')
541
542     def shortDescription(self):
543         return "running pure doctests in %s" % self.module_name
544
545     def run(self, result=None):
546         if result is None:
547             result = self.defaultTestResult()
548         loaded_module_name = 'pure_doctest__' + self.module_name
549         result.startTest(self)
550         try:
551             self.setUp()
552
553             import imp
554             m = imp.load_source(loaded_module_name, self.module_path)
555             try:
556                 doctest.DocTestSuite(m).run(result)
557             finally:
558                 del m
559                 if loaded_module_name in sys.modules:
560                     del sys.modules[loaded_module_name]
561                 check_thread_termination()
562         except Exception:
563             result.addError(self, sys.exc_info())
564             result.stopTest(self)
565         try:
566             self.tearDown()
567         except Exception:
568             pass
569
570 is_private_field = re.compile('^_[^_]').match
571
572 class _FakeClass(object):
573     def __init__(self, **kwargs):
574         self._shortDescription = kwargs.get('module_name')
575         self.__dict__.update(kwargs)
576     def shortDescription(self):
577         return self._shortDescription
578
579 try: # Py2.7+ and Py3.2+
580     from unittest.runner import _TextTestResult
581 except ImportError:
582     from unittest import _TextTestResult
583
584 class PartialTestResult(_TextTestResult):
585     def __init__(self, base_result):
586         _TextTestResult.__init__(
587             self, self._StringIO(), True,
588             base_result.dots + base_result.showAll*2)
589
590     def strip_error_results(self, results):
591         for test_case, error in results:
592             for attr_name in filter(is_private_field, dir(test_case)):
593                 if attr_name == '_dt_test':
594                     test_case._dt_test = _FakeClass(
595                         name=test_case._dt_test.name)
596                 elif attr_name != '_shortDescription':
597                     setattr(test_case, attr_name, None)
598
599     def data(self):
600         self.strip_error_results(self.failures)
601         self.strip_error_results(self.errors)
602         return (self.failures, self.errors, self.testsRun,
603                 self.stream.getvalue())
604
605     def join_results(result, data):
606         """Static method for merging the result back into the main
607         result object.
608         """
609         failures, errors, tests_run, output = data
610         if output:
611             result.stream.write(output)
612         result.errors.extend(errors)
613         result.failures.extend(failures)
614         result.testsRun += tests_run
615
616     join_results = staticmethod(join_results)
617
618     class _StringIO(StringIO):
619         def writeln(self, line):
620             self.write("%s\n" % line)
621
622
623 class CythonUnitTestCase(CythonCompileTestCase):
624     def shortDescription(self):
625         return "compiling (%s) tests in %s" % (self.language, self.module)
626
627     def run(self, result=None):
628         if result is None:
629             result = self.defaultTestResult()
630         result.startTest(self)
631         try:
632             self.setUp()
633             try:
634                 self.runCompileTest()
635                 unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
636             finally:
637                 check_thread_termination()
638         except Exception:
639             result.addError(self, sys.exc_info())
640             result.stopTest(self)
641         try:
642             self.tearDown()
643         except Exception:
644             pass
645
646 include_debugger = sys.version_info[:2] > (2, 4)
647
648 def collect_unittests(path, module_prefix, suite, selectors):
649     def file_matches(filename):
650         return filename.startswith("Test") and filename.endswith(".py")
651
652     def package_matches(dirname):
653         return dirname == "Tests"
654
655     loader = unittest.TestLoader()
656     
657     if include_debugger:
658         skipped_dirs = []
659     else:
660         cython_dir = os.path.dirname(os.path.abspath(__file__))
661         skipped_dirs = [os.path.join(cython_dir, 'Cython', 'Debugger')]
662
663     for dirpath, dirnames, filenames in os.walk(path):
664         if dirpath != path and "__init__.py" not in filenames:
665             skipped_dirs.append(dirpath + os.path.sep)
666             continue
667         skip = False
668         for dir in skipped_dirs:
669             if dirpath.startswith(dir):
670                 skip = True
671         if skip:
672             continue
673         parentname = os.path.split(dirpath)[-1]
674         if package_matches(parentname):
675             for f in filenames:
676                 if file_matches(f):
677                     filepath = os.path.join(dirpath, f)[:-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                     suite.addTests([loader.loadTestsFromModule(module)])
685
686
687
688 def collect_doctests(path, module_prefix, suite, selectors):
689     def package_matches(dirname):
690         if dirname == 'Debugger' and not include_debugger:
691             return False
692         return dirname not in ("Mac", "Distutils", "Plex")
693     def file_matches(filename):
694         filename, ext = os.path.splitext(filename)
695         blacklist = ['libcython', 'libpython', 'test_libcython_in_gdb', 
696                      'TestLibCython']
697         return (ext == '.py' and not
698                 '~' in filename and not
699                 '#' in filename and not
700                 filename.startswith('.') and not
701                 filename in blacklist)
702     import doctest, types
703     for dirpath, dirnames, filenames in os.walk(path):
704         parentname = os.path.split(dirpath)[-1]
705         if package_matches(parentname):
706             for f in filenames:
707                 if file_matches(f):
708                     if not f.endswith('.py'): continue
709                     filepath = os.path.join(dirpath, f)
710                     if os.path.getsize(filepath) == 0: continue
711                     if 'no doctest' in open(filepath).next(): continue
712                     filepath = filepath[:-len(".py")]
713                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
714                     if not [ 1 for match in selectors if match(modulename) ]:
715                         continue
716                     module = __import__(modulename)
717                     for x in modulename.split('.')[1:]:
718                         module = getattr(module, x)
719                     if hasattr(module, "__doc__") or hasattr(module, "__test__"):
720                         try:
721                             suite.addTest(doctest.DocTestSuite(module))
722                         except ValueError: # no tests
723                             pass
724
725
726 class EndToEndTest(unittest.TestCase):
727     """
728     This is a test of build/*.srctree files, where srctree defines a full
729     directory structure and its header gives a list of commands to run.
730     """
731     cython_root = os.path.dirname(os.path.abspath(__file__))
732     
733     def __init__(self, treefile, workdir, cleanup_workdir=True):
734         self.treefile = treefile
735         self.workdir = os.path.join(workdir, os.path.splitext(treefile)[0])
736         self.cleanup_workdir = cleanup_workdir
737         cython_syspath = self.cython_root
738         for path in sys.path[::-1]:
739             if path.startswith(self.cython_root):
740                 # Py3 installation and refnanny build prepend their
741                 # fixed paths to sys.path => prefer that over the
742                 # generic one
743                 cython_syspath = path + os.pathsep + cython_syspath
744         self.cython_syspath = cython_syspath
745         unittest.TestCase.__init__(self)
746
747     def shortDescription(self):
748         return "End-to-end %s" % self.treefile
749
750     def setUp(self):
751         from Cython.TestUtils import unpack_source_tree
752         _, self.commands = unpack_source_tree(
753             os.path.join('tests', 'build', self.treefile), self.workdir)
754         self.old_dir = os.getcwd()
755         os.chdir(self.workdir)
756         if self.workdir not in sys.path:
757             sys.path.insert(0, self.workdir)
758
759     def tearDown(self):
760         if self.cleanup_workdir:
761             shutil.rmtree(self.workdir)
762         os.chdir(self.old_dir)
763     
764     def runTest(self):
765         commands = (self.commands
766             .replace("CYTHON", "PYTHON %s" % os.path.join(self.cython_root, 'cython.py'))
767             .replace("PYTHON", sys.executable))
768         try:
769             old_path = os.environ.get('PYTHONPATH')
770             os.environ['PYTHONPATH'] = os.path.join(self.cython_syspath, (old_path or ''))
771             for command in commands.split('\n'):
772                 if sys.version_info[:2] >= (2,4):
773                     import subprocess
774                     p = subprocess.Popen(commands,
775                                          stderr=subprocess.PIPE,
776                                          stdout=subprocess.PIPE,
777                                          shell=True)
778                     out, err = p.communicate()
779                     res = p.returncode
780                     if res != 0:
781                         print(command)
782                         print(out)
783                         print(err)
784                 else:
785                     res = os.system(command)
786                 self.assertEqual(0, res, "non-zero exit status")
787         finally:
788             if old_path:
789                 os.environ['PYTHONPATH'] = old_path
790             else:
791                 del os.environ['PYTHONPATH']
792
793
794 # TODO: Support cython_freeze needed here as well.
795 # TODO: Windows support.
796
797 class EmbedTest(unittest.TestCase):
798     
799     working_dir = "Demos/embed"
800     
801     def setUp(self):
802         self.old_dir = os.getcwd()
803         os.chdir(self.working_dir)
804         os.system(
805             "make PYTHON='%s' clean > /dev/null" % sys.executable)
806     
807     def tearDown(self):
808         try:
809             os.system(
810                 "make PYTHON='%s' clean > /dev/null" % sys.executable)
811         except:
812             pass
813         os.chdir(self.old_dir)
814         
815     def test_embed(self):
816         from distutils import sysconfig
817         libname = sysconfig.get_config_var('LIBRARY')
818         libdir = sysconfig.get_config_var('LIBDIR')
819         if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
820             libdir = os.path.join(os.path.dirname(sys.executable), '..', 'lib')
821             if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
822                 libdir = os.path.join(libdir, 'python%d.%d' % sys.version_info[:2], 'config')
823                 if not os.path.isdir(libdir) or libname not in os.listdir(libdir):
824                     # report the error for the original directory
825                     libdir = sysconfig.get_config_var('LIBDIR')
826         self.assert_(os.system(
827             "make PYTHON='%s' LIBDIR1='%s' test > make.output" % (sys.executable, libdir)) == 0)
828         try:
829             os.remove('make.output')
830         except OSError:
831             pass
832
833 class MissingDependencyExcluder:
834     def __init__(self, deps):
835         # deps: { module name : matcher func }
836         self.exclude_matchers = []
837         for mod, matcher in deps.items():
838             try:
839                 __import__(mod)
840             except ImportError:
841                 self.exclude_matchers.append(matcher)
842         self.tests_missing_deps = []
843     def __call__(self, testname):
844         for matcher in self.exclude_matchers:
845             if matcher(testname):
846                 self.tests_missing_deps.append(testname)
847                 return True
848         return False
849
850 class VersionDependencyExcluder:
851     def __init__(self, deps):
852         # deps: { version : matcher func }
853         from sys import version_info
854         self.exclude_matchers = []
855         for ver, (compare, matcher) in deps.items():
856             if compare(version_info, ver):
857                 self.exclude_matchers.append(matcher)
858         self.tests_missing_deps = []
859     def __call__(self, testname):
860         for matcher in self.exclude_matchers:
861             if matcher(testname):
862                 self.tests_missing_deps.append(testname)
863                 return True
864         return False
865
866 class FileListExcluder:
867
868     def __init__(self, list_file):
869         self.excludes = {}
870         f = open(list_file)
871         try:
872             for line in f.readlines():
873                 line = line.strip()
874                 if line and line[0] != '#':
875                     self.excludes[line.split()[0]] = True
876         finally:
877             f.close()
878                 
879     def __call__(self, testname):
880         return testname in self.excludes or testname.split('.')[-1] in self.excludes
881
882 def refactor_for_py3(distdir, cy3_dir):
883     # need to convert Cython sources first
884     import lib2to3.refactor
885     from distutils.util import copydir_run_2to3
886     fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
887                if fix.split('fix_')[-1] not in ('next',)
888                ]
889     if not os.path.exists(cy3_dir):
890         os.makedirs(cy3_dir)
891     import distutils.log as dlog
892     dlog.set_threshold(dlog.INFO)
893     copydir_run_2to3(distdir, cy3_dir, fixer_names=fixers,
894                      template = '''
895                      global-exclude *
896                      graft Cython
897                      recursive-exclude Cython *
898                      recursive-include Cython *.py *.pyx *.pxd
899                      ''')
900     sys.path.insert(0, cy3_dir)
901
902 class PendingThreadsError(RuntimeError):
903     pass
904
905 threads_seen = []
906
907 def check_thread_termination(ignore_seen=True):
908     if threading is None: # no threading enabled in CPython
909         return
910     current = threading.currentThread()
911     blocking_threads = []
912     for t in threading.enumerate():
913         if not t.isAlive() or t == current:
914             continue
915         t.join(timeout=2)
916         if t.isAlive():
917             if not ignore_seen:
918                 blocking_threads.append(t)
919                 continue
920             for seen in threads_seen:
921                 if t is seen:
922                     break
923             else:
924                 threads_seen.append(t)
925                 blocking_threads.append(t)
926     if not blocking_threads:
927         return
928     sys.stderr.write("warning: left-over threads found after running test:\n")
929     for t in blocking_threads:
930         sys.stderr.write('...%s\n'  % repr(t))
931     raise PendingThreadsError("left-over threads found after running test")
932
933 def main():
934     from optparse import OptionParser
935     parser = OptionParser()
936     parser.add_option("--no-cleanup", dest="cleanup_workdir",
937                       action="store_false", default=True,
938                       help="do not delete the generated C files (allows passing --no-cython on next run)")
939     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
940                       action="store_false", default=True,
941                       help="do not delete the generated shared libary files (allows manual module experimentation)")
942     parser.add_option("--no-cython", dest="with_cython",
943                       action="store_false", default=True,
944                       help="do not run the Cython compiler, only the C compiler")
945     parser.add_option("--no-c", dest="use_c",
946                       action="store_false", default=True,
947                       help="do not test C compilation")
948     parser.add_option("--no-cpp", dest="use_cpp",
949                       action="store_false", default=True,
950                       help="do not test C++ compilation")
951     parser.add_option("--no-unit", dest="unittests",
952                       action="store_false", default=True,
953                       help="do not run the unit tests")
954     parser.add_option("--no-doctest", dest="doctests",
955                       action="store_false", default=True,
956                       help="do not run the doctests")
957     parser.add_option("--no-file", dest="filetests",
958                       action="store_false", default=True,
959                       help="do not run the file based tests")
960     parser.add_option("--no-pyregr", dest="pyregr",
961                       action="store_false", default=True,
962                       help="do not run the regression tests of CPython in tests/pyregr/")    
963     parser.add_option("--cython-only", dest="cython_only",
964                       action="store_true", default=False,
965                       help="only compile pyx to c, do not run C compiler or run the tests")
966     parser.add_option("--no-refnanny", dest="with_refnanny",
967                       action="store_false", default=True,
968                       help="do not regression test reference counting")
969     parser.add_option("--no-fork", dest="fork",
970                       action="store_false", default=True,
971                       help="do not fork to run tests")
972     parser.add_option("--sys-pyregr", dest="system_pyregr",
973                       action="store_true", default=False,
974                       help="run the regression tests of the CPython installation")
975     parser.add_option("-x", "--exclude", dest="exclude",
976                       action="append", metavar="PATTERN",
977                       help="exclude tests matching the PATTERN")
978     parser.add_option("-C", "--coverage", dest="coverage",
979                       action="store_true", default=False,
980                       help="collect source coverage data for the Compiler")
981     parser.add_option("--coverage-xml", dest="coverage_xml",
982                       action="store_true", default=False,
983                       help="collect source coverage data for the Compiler in XML format")
984     parser.add_option("-A", "--annotate", dest="annotate_source",
985                       action="store_true", default=True,
986                       help="generate annotated HTML versions of the test source files")
987     parser.add_option("--no-annotate", dest="annotate_source",
988                       action="store_false",
989                       help="do not generate annotated HTML versions of the test source files")
990     parser.add_option("-v", "--verbose", dest="verbosity",
991                       action="count", default=0,
992                       help="display test progress, pass twice to print test names")
993     parser.add_option("-T", "--ticket", dest="tickets",
994                       action="append",
995                       help="a bug ticket number to run the respective test in 'tests/*'")
996     parser.add_option("-3", dest="language_level",
997                       action="store_const", const=3, default=2,
998                       help="set language level to Python 3 (useful for running the CPython regression tests)'")
999     parser.add_option("--xml-output", dest="xml_output_dir", metavar="DIR",
1000                       help="write test results in XML to directory DIR")
1001     parser.add_option("--exit-ok", dest="exit_ok", default=False,
1002                       action="store_true",
1003                       help="exit without error code even on test failures")
1004
1005     options, cmd_args = parser.parse_args()
1006
1007     DISTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]))
1008     ROOTDIR = os.path.join(DISTDIR, 'tests')
1009     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
1010
1011     if sys.version_info[0] >= 3:
1012         options.doctests = False
1013         if options.with_cython:
1014             try:
1015                 # try if Cython is installed in a Py3 version
1016                 import Cython.Compiler.Main
1017             except Exception:
1018                 # back out anything the import process loaded, then
1019                 # 2to3 the Cython sources to make them re-importable
1020                 cy_modules = [ name for name in sys.modules
1021                                if name == 'Cython' or name.startswith('Cython.') ]
1022                 for name in cy_modules:
1023                     del sys.modules[name]
1024                 # hasn't been refactored yet - do it now
1025                 cy3_dir = os.path.join(WORKDIR, 'Cy3')
1026                 if sys.version_info >= (3,1):
1027                     refactor_for_py3(DISTDIR, cy3_dir)
1028                 elif os.path.isdir(cy3_dir):
1029                     sys.path.insert(0, cy3_dir)
1030                 else:
1031                     options.with_cython = False
1032
1033     WITH_CYTHON = options.with_cython
1034
1035     if options.coverage or options.coverage_xml:
1036         if not WITH_CYTHON:
1037             options.coverage = options.coverage_xml = False
1038         else:
1039             from coverage import coverage as _coverage
1040             coverage = _coverage(branch=True)
1041             coverage.erase()
1042             coverage.start()
1043
1044     if WITH_CYTHON:
1045         global CompilationOptions, pyrex_default_options, cython_compile
1046         from Cython.Compiler.Main import \
1047             CompilationOptions, \
1048             default_options as pyrex_default_options, \
1049             compile as cython_compile
1050         from Cython.Compiler import Errors
1051         Errors.LEVEL = 0 # show all warnings
1052         from Cython.Compiler import Options
1053         Options.generate_cleanup_code = 3   # complete cleanup code
1054         from Cython.Compiler import DebugFlags
1055         DebugFlags.debug_temp_code_comments = 1
1056
1057     # RUN ALL TESTS!
1058     UNITTEST_MODULE = "Cython"
1059     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
1060     if WITH_CYTHON:
1061         if os.path.exists(WORKDIR):
1062             for path in os.listdir(WORKDIR):
1063                 if path in ("support", "Cy3"): continue
1064                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
1065     if not os.path.exists(WORKDIR):
1066         os.makedirs(WORKDIR)
1067
1068     sys.stderr.write("Python %s\n" % sys.version)
1069     sys.stderr.write("\n")
1070     if WITH_CYTHON:
1071         from Cython.Compiler.Version import version
1072         sys.stderr.write("Running tests against Cython %s\n" % version)
1073     else:
1074         sys.stderr.write("Running tests without Cython.\n")
1075
1076     if options.with_refnanny:
1077         from pyximport.pyxbuild import pyx_to_dll
1078         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
1079                              build_in_temp=True,
1080                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
1081         sys.path.insert(0, os.path.split(libpath)[0])
1082         CFLAGS.append("-DCYTHON_REFNANNY=1")
1083
1084     if options.xml_output_dir and options.fork:
1085         # doesn't currently work together
1086         sys.stderr.write("Disabling forked testing to support XML test output\n")
1087         options.fork = False
1088
1089     if WITH_CYTHON and options.language_level == 3:
1090         sys.stderr.write("Using Cython language level 3.\n")
1091
1092     sys.stderr.write("\n")
1093
1094     test_bugs = False
1095     if options.tickets:
1096         for ticket_number in options.tickets:
1097             test_bugs = True
1098             cmd_args.append('.*T%s$' % ticket_number)
1099     if not test_bugs:
1100         for selector in cmd_args:
1101             if selector.startswith('bugs'):
1102                 test_bugs = True
1103
1104     import re
1105     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
1106     if not selectors:
1107         selectors = [ lambda x:True ]
1108
1109     # Chech which external modules are not present and exclude tests
1110     # which depends on them (by prefix)
1111
1112     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
1113     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
1114     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
1115
1116     if options.exclude:
1117         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
1118     
1119     if not test_bugs:
1120         exclude_selectors += [ FileListExcluder("tests/bugs.txt") ]
1121     
1122     if sys.platform in ['win32', 'cygwin'] and sys.version_info < (2,6):
1123         exclude_selectors += [ lambda x: x == "run.specialfloat" ]
1124
1125     languages = []
1126     if options.use_c:
1127         languages.append('c')
1128     if options.use_cpp:
1129         languages.append('cpp')
1130
1131     test_suite = unittest.TestSuite()
1132
1133     if options.unittests:
1134         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1135
1136     if options.doctests:
1137         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
1138
1139     if options.filetests and languages:
1140         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1141                                 options.annotate_source, options.cleanup_workdir,
1142                                 options.cleanup_sharedlibs, options.pyregr,
1143                                 options.cython_only, languages, test_bugs,
1144                                 options.fork, options.language_level)
1145         test_suite.addTest(filetests.build_suite())
1146
1147     if options.system_pyregr and languages:
1148         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
1149                                 options.annotate_source, options.cleanup_workdir,
1150                                 options.cleanup_sharedlibs, True,
1151                                 options.cython_only, languages, test_bugs,
1152                                 options.fork, options.language_level)
1153         test_suite.addTest(
1154             filetests.handle_directory(
1155                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
1156                 'pyregr'))
1157
1158     if options.xml_output_dir:
1159         from Cython.Tests.xmlrunner import XMLTestRunner
1160         test_runner = XMLTestRunner(output=options.xml_output_dir,
1161                                     verbose=options.verbosity > 0)
1162     else:
1163         test_runner = unittest.TextTestRunner(verbosity=options.verbosity)
1164
1165     result = test_runner.run(test_suite)
1166
1167     if options.coverage or options.coverage_xml:
1168         coverage.stop()
1169         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
1170         modules = [ module for name, module in sys.modules.items()
1171                     if module is not None and
1172                     name.startswith('Cython.Compiler.') and 
1173                     name[len('Cython.Compiler.'):] not in ignored_modules ]
1174         if options.coverage:
1175             coverage.report(modules, show_missing=0)
1176         if options.coverage_xml:
1177             coverage.xml_report(modules, outfile="coverage-report.xml")
1178
1179     if missing_dep_excluder.tests_missing_deps:
1180         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
1181         for test in missing_dep_excluder.tests_missing_deps:
1182             sys.stderr.write("   %s\n" % test)
1183
1184     if options.with_refnanny:
1185         import refnanny
1186         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))
1187
1188     print("ALL DONE")
1189
1190     if options.exit_ok:
1191         return_code = 0
1192     else:
1193         return_code = not result.wasSuccessful()
1194
1195     try:
1196         check_thread_termination(ignore_seen=False)
1197         sys.exit(return_code)
1198     except PendingThreadsError:
1199         # normal program exit won't kill the threads, do it the hard way here
1200         os._exit(return_code)
1201
1202 if __name__ == '__main__':
1203     try:
1204         main()
1205     except SystemExit: # <= Py2.4 ...
1206         raise
1207     except Exception:
1208         traceback.print_exc()
1209         try:
1210             check_thread_termination(ignore_seen=False)
1211         except PendingThreadsError:
1212             # normal program exit won't kill the threads, do it the hard way here
1213             os._exit(1)