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