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