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