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