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