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