merge
[cython.git] / runtests.py
1 #!/usr/bin/python
2
3 import os, sys, re, shutil, unittest, doctest
4
5 WITH_CYTHON = True
6
7 from distutils.dist import Distribution
8 from distutils.core import Extension
9 from distutils.command.build_ext import build_ext as _build_ext
10 distutils_distro = Distribution()
11
12 TEST_DIRS = ['compile', 'errors', 'run', 'pyregr']
13 TEST_RUN_DIRS = ['run', 'pyregr', 'bugs']
14
15 # Lists external modules, and a matcher matching tests
16 # which should be excluded if the module is not present.
17 EXT_DEP_MODULES = {
18     'numpy' : re.compile('.*\.numpy_.*').match
19 }
20
21 def get_numpy_include_dirs():
22     import numpy
23     return [numpy.get_include()]
24
25 EXT_DEP_INCLUDES = [
26     # test name matcher , callable returning list
27     (re.compile('numpy_.*').match, get_numpy_include_dirs),
28 ]
29
30 VER_DEP_MODULES = {
31 # such as:
32 #    (2,4) : lambda x: x in ['run.set']
33 }
34
35 INCLUDE_DIRS = [ d for d in os.getenv('INCLUDE', '').split(os.pathsep) if d ]
36 CFLAGS = os.getenv('CFLAGS', '').split()
37
38 class build_ext(_build_ext):
39     def build_extension(self, ext):
40         if ext.language == 'c++':
41             try:
42                 self.compiler.compiler_so.remove('-Wstrict-prototypes')
43             except Exception:
44                 pass
45         _build_ext.build_extension(self, ext)
46
47 class ErrorWriter(object):
48     match_error = re.compile('(warning:)?(?:.*:)?\s*([-0-9]+)\s*:\s*([-0-9]+)\s*:\s*(.*)').match
49     def __init__(self):
50         self.output = []
51         self.write = self.output.append
52
53     def _collect(self, collect_errors, collect_warnings):
54         s = ''.join(self.output)
55         result = []
56         for line in s.split('\n'):
57             match = self.match_error(line)
58             if match:
59                 is_warning, line, column, message = match.groups()
60                 if (is_warning and collect_warnings) or \
61                         (not is_warning and collect_errors):
62                     result.append( (int(line), int(column), message.strip()) )
63         result.sort()
64         return [ "%d:%d: %s" % values for values in result ]
65
66     def geterrors(self):
67         return self._collect(True, False)
68
69     def getwarnings(self):
70         return self._collect(False, True)
71
72     def getall(self):
73         return self._collect(True, True)
74
75 class TestBuilder(object):
76     def __init__(self, rootdir, workdir, selectors, exclude_selectors, annotate,
77                  cleanup_workdir, cleanup_sharedlibs, with_pyregr, cython_only,
78                  languages, test_bugs):
79         self.rootdir = rootdir
80         self.workdir = workdir
81         self.selectors = selectors
82         self.exclude_selectors = exclude_selectors
83         self.annotate = annotate
84         self.cleanup_workdir = cleanup_workdir
85         self.cleanup_sharedlibs = cleanup_sharedlibs
86         self.with_pyregr = with_pyregr
87         self.cython_only = cython_only
88         self.languages = languages
89         self.test_bugs = test_bugs
90
91     def build_suite(self):
92         suite = unittest.TestSuite()
93         test_dirs = TEST_DIRS
94         if self.test_bugs and 'bugs' not in test_dirs:
95             test_dirs.append('bugs')
96         filenames = os.listdir(self.rootdir)
97         filenames.sort()
98         for filename in filenames:
99             if not WITH_CYTHON and filename == "errors":
100                 # we won't get any errors without running Cython
101                 continue
102             path = os.path.join(self.rootdir, filename)
103             if os.path.isdir(path) and filename in test_dirs:
104                 if filename == 'pyregr' and not self.with_pyregr:
105                     continue
106                 suite.addTest(
107                     self.handle_directory(path, filename))
108         return suite
109
110     def handle_directory(self, path, context):
111         workdir = os.path.join(self.workdir, context)
112         if not os.path.exists(workdir):
113             os.makedirs(workdir)
114
115         expect_errors = (context == 'errors')
116         suite = unittest.TestSuite()
117         filenames = os.listdir(path)
118         filenames.sort()
119         for filename in filenames:
120             if not (filename.endswith(".pyx") or filename.endswith(".py")):
121                 continue
122             if filename.startswith('.'): continue # certain emacs backup files
123             if context == 'pyregr' and not filename.startswith('test_'):
124                 continue
125             module = os.path.splitext(filename)[0]
126             fqmodule = "%s.%s" % (context, module)
127             if not [ 1 for match in self.selectors
128                      if match(fqmodule) ]:
129                 continue
130             if self.exclude_selectors:
131                 if [1 for match in self.exclude_selectors if match(fqmodule)]:
132                     continue
133             if context in TEST_RUN_DIRS:
134                 if module.startswith("test_"):
135                     test_class = CythonUnitTestCase
136                 else:
137                     test_class = CythonRunTestCase
138             else:
139                 test_class = CythonCompileTestCase
140             for test in self.build_tests(test_class, path, workdir,
141                                          module, expect_errors):
142                 suite.addTest(test)
143         return suite
144
145     def build_tests(self, test_class, path, workdir, module, expect_errors):
146         if expect_errors:
147             languages = self.languages[:1]
148         else:
149             languages = self.languages
150         tests = [ self.build_test(test_class, path, workdir, module,
151                                   language, expect_errors)
152                   for language in languages ]
153         return tests
154
155     def build_test(self, test_class, path, workdir, module,
156                    language, expect_errors):
157         workdir = os.path.join(workdir, language)
158         if not os.path.exists(workdir):
159             os.makedirs(workdir)
160         return test_class(path, workdir, module,
161                           language=language,
162                           expect_errors=expect_errors,
163                           annotate=self.annotate,
164                           cleanup_workdir=self.cleanup_workdir,
165                           cleanup_sharedlibs=self.cleanup_sharedlibs,
166                           cython_only=self.cython_only)
167
168 class CythonCompileTestCase(unittest.TestCase):
169     def __init__(self, directory, workdir, module, language='c',
170                  expect_errors=False, annotate=False, cleanup_workdir=True,
171                  cleanup_sharedlibs=True, cython_only=False):
172         self.directory = directory
173         self.workdir = workdir
174         self.module = module
175         self.language = language
176         self.expect_errors = expect_errors
177         self.annotate = annotate
178         self.cleanup_workdir = cleanup_workdir
179         self.cleanup_sharedlibs = cleanup_sharedlibs
180         self.cython_only = cython_only
181         unittest.TestCase.__init__(self)
182
183     def shortDescription(self):
184         return "compiling (%s) %s" % (self.language, self.module)
185
186     def setUp(self):
187         if self.workdir not in sys.path:
188             sys.path.insert(0, self.workdir)
189
190     def tearDown(self):
191         try:
192             sys.path.remove(self.workdir)
193         except ValueError:
194             pass
195         try:
196             del sys.modules[self.module]
197         except KeyError:
198             pass
199         cleanup_c_files = WITH_CYTHON and self.cleanup_workdir
200         cleanup_lib_files = self.cleanup_sharedlibs
201         if os.path.exists(self.workdir):
202             for rmfile in os.listdir(self.workdir):
203                 if not cleanup_c_files:
204                     if rmfile[-2:] in (".c", ".h") or rmfile[-4:] == ".cpp":
205                         continue
206                 if not cleanup_lib_files and rmfile.endswith(".so") or rmfile.endswith(".dll"):
207                     continue
208                 if self.annotate and rmfile.endswith(".html"):
209                     continue
210                 try:
211                     rmfile = os.path.join(self.workdir, rmfile)
212                     if os.path.isdir(rmfile):
213                         shutil.rmtree(rmfile, ignore_errors=True)
214                     else:
215                         os.remove(rmfile)
216                 except IOError:
217                     pass
218         else:
219             os.makedirs(self.workdir)
220
221     def runTest(self):
222         self.runCompileTest()
223
224     def runCompileTest(self):
225         self.compile(self.directory, self.module, self.workdir,
226                      self.directory, self.expect_errors, self.annotate)
227
228     def find_module_source_file(self, source_file):
229         if not os.path.exists(source_file):
230             source_file = source_file[:-1]
231         return source_file
232
233     def build_target_filename(self, module_name):
234         target = '%s.%s' % (module_name, self.language)
235         return target
236
237     def split_source_and_output(self, directory, module, workdir):
238         source_file = os.path.join(directory, module) + '.pyx'
239         source_and_output = open(
240             self.find_module_source_file(source_file), 'rU')
241         out = open(os.path.join(workdir, module + '.pyx'), 'w')
242         for line in source_and_output:
243             last_line = line
244             if line.startswith("_ERRORS"):
245                 out.close()
246                 out = ErrorWriter()
247             else:
248                 out.write(line)
249         try:
250             geterrors = out.geterrors
251         except AttributeError:
252             return []
253         else:
254             return geterrors()
255
256     def run_cython(self, directory, module, targetdir, incdir, annotate):
257         include_dirs = INCLUDE_DIRS[:]
258         if incdir:
259             include_dirs.append(incdir)
260         source = self.find_module_source_file(
261             os.path.join(directory, module + '.pyx'))
262         target = os.path.join(targetdir, self.build_target_filename(module))
263         options = CompilationOptions(
264             pyrex_default_options,
265             include_path = include_dirs,
266             output_file = target,
267             annotate = annotate,
268             use_listing_file = False,
269             cplus = self.language == 'cpp',
270             generate_pxi = False)
271         cython_compile(source, options=options,
272                        full_module_name=module)
273
274     def run_distutils(self, module, workdir, incdir):
275         cwd = os.getcwd()
276         os.chdir(workdir)
277         try:
278             build_extension = build_ext(distutils_distro)
279             build_extension.include_dirs = INCLUDE_DIRS[:]
280             if incdir:
281                 build_extension.include_dirs.append(incdir)
282             build_extension.finalize_options()
283             ext_include_dirs = []
284             for match, get_additional_include_dirs in EXT_DEP_INCLUDES:
285                 if match(module):
286                     ext_include_dirs += get_additional_include_dirs()
287             extension = Extension(
288                 module,
289                 sources = [self.build_target_filename(module)],
290                 include_dirs = ext_include_dirs,
291                 extra_compile_args = CFLAGS,
292                 )
293             if self.language == 'cpp':
294                 extension.language = 'c++'
295             build_extension.extensions = [extension]
296             build_extension.build_temp = workdir
297             build_extension.build_lib  = workdir
298             build_extension.run()
299         finally:
300             os.chdir(cwd)
301
302     def compile(self, directory, module, workdir, incdir,
303                 expect_errors, annotate):
304         expected_errors = errors = ()
305         if expect_errors:
306             expected_errors = self.split_source_and_output(
307                 directory, module, workdir)
308             directory = workdir
309
310         if WITH_CYTHON:
311             old_stderr = sys.stderr
312             try:
313                 sys.stderr = ErrorWriter()
314                 self.run_cython(directory, module, workdir, incdir, annotate)
315                 errors = sys.stderr.geterrors()
316             finally:
317                 sys.stderr = old_stderr
318
319         if errors or expected_errors:
320             for expected, error in zip(expected_errors, errors):
321                 self.assertEquals(expected, error)
322             if len(errors) < len(expected_errors):
323                 expected_error = expected_errors[len(errors)]
324                 self.assertEquals(expected_error, None)
325             elif len(errors) > len(expected_errors):
326                 unexpected_error = errors[len(expected_errors)]
327                 self.assertEquals(None, unexpected_error)
328         else:
329             if not self.cython_only:
330                 self.run_distutils(module, workdir, incdir)
331
332 class CythonRunTestCase(CythonCompileTestCase):
333     def shortDescription(self):
334         return "compiling (%s) and running %s" % (self.language, self.module)
335
336     def run(self, result=None):
337         if result is None:
338             result = self.defaultTestResult()
339         result.startTest(self)
340         try:
341             self.setUp()
342             self.runCompileTest()
343             if not self.cython_only:
344                 doctest.DocTestSuite(self.module).run(result)
345         except Exception:
346             result.addError(self, sys.exc_info())
347             result.stopTest(self)
348         try:
349             self.tearDown()
350         except Exception:
351             pass
352
353 class CythonUnitTestCase(CythonCompileTestCase):
354     def shortDescription(self):
355         return "compiling (%s) tests in %s" % (self.language, self.module)
356
357     def run(self, result=None):
358         if result is None:
359             result = self.defaultTestResult()
360         result.startTest(self)
361         try:
362             self.setUp()
363             self.runCompileTest()
364             unittest.defaultTestLoader.loadTestsFromName(self.module).run(result)
365         except Exception:
366             result.addError(self, sys.exc_info())
367             result.stopTest(self)
368         try:
369             self.tearDown()
370         except Exception:
371             pass
372
373 def collect_unittests(path, module_prefix, suite, selectors):
374     def file_matches(filename):
375         return filename.startswith("Test") and filename.endswith(".py")
376
377     def package_matches(dirname):
378         return dirname == "Tests"
379
380     loader = unittest.TestLoader()
381
382     skipped_dirs = []
383
384     for dirpath, dirnames, filenames in os.walk(path):
385         if dirpath != path and "__init__.py" not in filenames:
386             skipped_dirs.append(dirpath + os.path.sep)
387             continue
388         skip = False
389         for dir in skipped_dirs:
390             if dirpath.startswith(dir):
391                 skip = True
392         if skip:
393             continue
394         parentname = os.path.split(dirpath)[-1]
395         if package_matches(parentname):
396             for f in filenames:
397                 if file_matches(f):
398                     filepath = os.path.join(dirpath, f)[:-len(".py")]
399                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
400                     if not [ 1 for match in selectors if match(modulename) ]:
401                         continue
402                     module = __import__(modulename)
403                     for x in modulename.split('.')[1:]:
404                         module = getattr(module, x)
405                     suite.addTests([loader.loadTestsFromModule(module)])
406
407 def collect_doctests(path, module_prefix, suite, selectors):
408     def package_matches(dirname):
409         return dirname not in ("Mac", "Distutils", "Plex")
410     def file_matches(filename):
411         return (filename.endswith(".py") and not ('~' in filename
412                 or '#' in filename or filename.startswith('.')))
413     import doctest, types
414     for dirpath, dirnames, filenames in os.walk(path):
415         parentname = os.path.split(dirpath)[-1]
416         if package_matches(parentname):
417             for f in filenames:
418                 if file_matches(f):
419                     if not f.endswith('.py'): continue
420                     filepath = os.path.join(dirpath, f)[:-len(".py")]
421                     modulename = module_prefix + filepath[len(path)+1:].replace(os.path.sep, '.')
422                     if not [ 1 for match in selectors if match(modulename) ]:
423                         continue
424                     module = __import__(modulename)
425                     for x in modulename.split('.')[1:]:
426                         module = getattr(module, x)
427                     if hasattr(module, "__doc__") or hasattr(module, "__test__"):
428                         try:
429                             suite.addTest(doctest.DocTestSuite(module))
430                         except ValueError: # no tests
431                             pass
432
433 class MissingDependencyExcluder:
434     def __init__(self, deps):
435         # deps: { module name : matcher func }
436         self.exclude_matchers = []
437         for mod, matcher in deps.items():
438             try:
439                 __import__(mod)
440             except ImportError:
441                 self.exclude_matchers.append(matcher)
442         self.tests_missing_deps = []
443     def __call__(self, testname):
444         for matcher in self.exclude_matchers:
445             if matcher(testname):
446                 self.tests_missing_deps.append(testname)
447                 return True
448         return False
449
450 class VersionDependencyExcluder:
451     def __init__(self, deps):
452         # deps: { version : matcher func }
453         from sys import version_info
454         self.exclude_matchers = []
455         for ver, matcher in deps.items():
456             if version_info < ver:
457                 self.exclude_matchers.append(matcher)
458         self.tests_missing_deps = []
459     def __call__(self, testname):
460         for matcher in self.exclude_matchers:
461             if matcher(testname):
462                 self.tests_missing_deps.append(testname)
463                 return True
464         return False
465
466 if __name__ == '__main__':
467     from optparse import OptionParser
468     parser = OptionParser()
469     parser.add_option("--no-cleanup", dest="cleanup_workdir",
470                       action="store_false", default=True,
471                       help="do not delete the generated C files (allows passing --no-cython on next run)")
472     parser.add_option("--no-cleanup-sharedlibs", dest="cleanup_sharedlibs",
473                       action="store_false", default=True,
474                       help="do not delete the generated shared libary files (allows manual module experimentation)")
475     parser.add_option("--no-cython", dest="with_cython",
476                       action="store_false", default=True,
477                       help="do not run the Cython compiler, only the C compiler")
478     parser.add_option("--no-c", dest="use_c",
479                       action="store_false", default=True,
480                       help="do not test C compilation")
481     parser.add_option("--no-cpp", dest="use_cpp",
482                       action="store_false", default=True,
483                       help="do not test C++ compilation")
484     parser.add_option("--no-unit", dest="unittests",
485                       action="store_false", default=True,
486                       help="do not run the unit tests")
487     parser.add_option("--no-doctest", dest="doctests",
488                       action="store_false", default=True,
489                       help="do not run the doctests")
490     parser.add_option("--no-file", dest="filetests",
491                       action="store_false", default=True,
492                       help="do not run the file based tests")
493     parser.add_option("--no-pyregr", dest="pyregr",
494                       action="store_false", default=True,
495                       help="do not run the regression tests of CPython in tests/pyregr/")    
496     parser.add_option("--cython-only", dest="cython_only",
497                       action="store_true", default=False,
498                       help="only compile pyx to c, do not run C compiler or run the tests")
499     parser.add_option("--no-refnanny", dest="with_refnanny",
500                       action="store_false", default=True,
501                       help="do not regression test reference counting")
502     parser.add_option("--sys-pyregr", dest="system_pyregr",
503                       action="store_true", default=False,
504                       help="run the regression tests of the CPython installation")
505     parser.add_option("-x", "--exclude", dest="exclude",
506                       action="append", metavar="PATTERN",
507                       help="exclude tests matching the PATTERN")
508     parser.add_option("-C", "--coverage", dest="coverage",
509                       action="store_true", default=False,
510                       help="collect source coverage data for the Compiler")
511     parser.add_option("-A", "--annotate", dest="annotate_source",
512                       action="store_true", default=True,
513                       help="generate annotated HTML versions of the test source files")
514     parser.add_option("--no-annotate", dest="annotate_source",
515                       action="store_false",
516                       help="do not generate annotated HTML versions of the test source files")
517     parser.add_option("-v", "--verbose", dest="verbosity",
518                       action="count", default=0,
519                       help="display test progress, pass twice to print test names")
520     parser.add_option("-T", "--ticket", dest="tickets",
521                       action="append",
522                       help="a bug ticket number to run the respective test in 'tests/bugs'")
523
524     options, cmd_args = parser.parse_args()
525
526     if sys.version_info[0] >= 3:
527         # make sure we do not import (or run) Cython itself
528         options.doctests    = False
529         options.with_cython = False
530         options.unittests   = False
531         options.pyregr      = False
532
533     if options.coverage:
534         import coverage
535         coverage.erase()
536         coverage.start()
537
538     WITH_CYTHON = options.with_cython
539
540     if WITH_CYTHON:
541         from Cython.Compiler.Main import \
542             CompilationOptions, \
543             default_options as pyrex_default_options, \
544             compile as cython_compile
545         from Cython.Compiler import Errors
546         Errors.LEVEL = 0 # show all warnings
547
548     # RUN ALL TESTS!
549     ROOTDIR = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0]), 'tests')
550     WORKDIR = os.path.join(os.getcwd(), 'BUILD')
551     UNITTEST_MODULE = "Cython"
552     UNITTEST_ROOT = os.path.join(os.getcwd(), UNITTEST_MODULE)
553     if WITH_CYTHON:
554         if os.path.exists(WORKDIR):
555             for path in os.listdir(WORKDIR):
556                 if path in ("support",): continue
557                 shutil.rmtree(os.path.join(WORKDIR, path), ignore_errors=True)
558     if not os.path.exists(WORKDIR):
559         os.makedirs(WORKDIR)
560
561     if WITH_CYTHON:
562         from Cython.Compiler.Version import version
563         sys.stderr.write("Running tests against Cython %s\n" % version)
564         from Cython.Compiler import DebugFlags
565         DebugFlags.debug_temp_code_comments = 1
566     else:
567         sys.stderr.write("Running tests without Cython.\n")
568     sys.stderr.write("Python %s\n" % sys.version)
569     sys.stderr.write("\n")
570
571     if options.with_refnanny:
572         from pyximport.pyxbuild import pyx_to_dll
573         libpath = pyx_to_dll(os.path.join("Cython", "Runtime", "refnanny.pyx"),
574                              build_in_temp=True,
575                              pyxbuild_dir=os.path.join(WORKDIR, "support"))
576         sys.path.insert(0, os.path.split(libpath)[0])
577         CFLAGS.append("-DCYTHON_REFNANNY")
578
579     test_bugs = False
580     if options.tickets:
581         for ticket_number in options.tickets:
582             test_bugs = True
583             cmd_args.append('bugs.*T%s$' % ticket_number)
584     if not test_bugs:
585         for selector in cmd_args:
586             if selector.startswith('bugs'):
587                 test_bugs = True
588
589     import re
590     selectors = [ re.compile(r, re.I|re.U).search for r in cmd_args ]
591     if not selectors:
592         selectors = [ lambda x:True ]
593
594     # Chech which external modules are not present and exclude tests
595     # which depends on them (by prefix)
596
597     missing_dep_excluder = MissingDependencyExcluder(EXT_DEP_MODULES) 
598     version_dep_excluder = VersionDependencyExcluder(VER_DEP_MODULES) 
599     exclude_selectors = [missing_dep_excluder, version_dep_excluder] # want to pring msg at exit
600
601     if options.exclude:
602         exclude_selectors += [ re.compile(r, re.I|re.U).search for r in options.exclude ]
603
604     languages = []
605     if options.use_c:
606         languages.append('c')
607     if options.use_cpp:
608         languages.append('cpp')
609
610     test_suite = unittest.TestSuite()
611
612     if options.unittests:
613         collect_unittests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
614
615     if options.doctests:
616         collect_doctests(UNITTEST_ROOT, UNITTEST_MODULE + ".", test_suite, selectors)
617
618     if options.filetests and languages:
619         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
620                                 options.annotate_source, options.cleanup_workdir,
621                                 options.cleanup_sharedlibs, options.pyregr,
622                                 options.cython_only, languages, test_bugs)
623         test_suite.addTest(filetests.build_suite())
624
625     if options.system_pyregr and languages:
626         filetests = TestBuilder(ROOTDIR, WORKDIR, selectors, exclude_selectors,
627                                 options.annotate_source, options.cleanup_workdir,
628                                 options.cleanup_sharedlibs, True,
629                                 options.cython_only, languages)
630         test_suite.addTest(
631             filetests.handle_directory(
632                 os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3], 'test'),
633                 'pyregr'))
634
635     unittest.TextTestRunner(verbosity=options.verbosity).run(test_suite)
636
637     if options.coverage:
638         coverage.stop()
639         ignored_modules = ('Options', 'Version', 'DebugFlags', 'CmdLine')
640         modules = [ module for name, module in sys.modules.items()
641                     if module is not None and
642                     name.startswith('Cython.Compiler.') and 
643                     name[len('Cython.Compiler.'):] not in ignored_modules ]
644         coverage.report(modules, show_missing=0)
645
646     if missing_dep_excluder.tests_missing_deps:
647         sys.stderr.write("Following tests excluded because of missing dependencies on your system:\n")
648         for test in missing_dep_excluder.tests_missing_deps:
649             sys.stderr.write("   %s\n" % test)
650
651     if options.with_refnanny:
652         import refnanny
653         sys.stderr.write("\n".join([repr(x) for x in refnanny.reflog]))