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