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