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