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