test_build_ext.py revision 1672e10dc2d7b70ee1830fbe0294e81f25560387
1import sys 2import os 3import tempfile 4import shutil 5from StringIO import StringIO 6 7from distutils.core import Extension, Distribution 8from distutils.command.build_ext import build_ext 9from distutils import sysconfig 10 11import unittest 12from test import test_support 13 14class BuildExtTestCase(unittest.TestCase): 15 def setUp(self): 16 # Create a simple test environment 17 # Note that we're making changes to sys.path 18 self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_") 19 self.sys_path = sys.path[:] 20 sys.path.append(self.tmp_dir) 21 22 xx_c = os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c') 23 shutil.copy(xx_c, self.tmp_dir) 24 25 def test_build_ext(self): 26 xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') 27 xx_ext = Extension('xx', [xx_c]) 28 dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) 29 dist.package_dir = self.tmp_dir 30 cmd = build_ext(dist) 31 if os.name == "nt": 32 # On Windows, we must build a debug version iff running 33 # a debug build of Python 34 cmd.debug = sys.executable.endswith("_d.exe") 35 cmd.build_lib = self.tmp_dir 36 cmd.build_temp = self.tmp_dir 37 38 old_stdout = sys.stdout 39 if not test_support.verbose: 40 # silence compiler output 41 sys.stdout = StringIO() 42 try: 43 cmd.ensure_finalized() 44 cmd.run() 45 finally: 46 sys.stdout = old_stdout 47 48 import xx 49 50 for attr in ('error', 'foo', 'new', 'roj'): 51 self.assert_(hasattr(xx, attr)) 52 53 self.assertEquals(xx.foo(2, 5), 7) 54 self.assertEquals(xx.foo(13,15), 28) 55 self.assertEquals(xx.new().demo(), None) 56 doc = 'This is a template module just for instruction.' 57 self.assertEquals(xx.__doc__, doc) 58 self.assert_(isinstance(xx.Null(), xx.Null)) 59 self.assert_(isinstance(xx.Str(), xx.Str)) 60 61 def tearDown(self): 62 # Get everything back to normal 63 test_support.unload('xx') 64 sys.path = self.sys_path 65 # XXX on Windows the test leaves a directory with xx module in TEMP 66 shutil.rmtree(self.tmp_dir, os.name == 'nt' or sys.platform == 'cygwin') 67 68def test_suite(): 69 if not sysconfig.python_build: 70 if test_support.verbose: 71 print 'test_build_ext: The test must be run in a python build dir' 72 return unittest.TestSuite() 73 else: return unittest.makeSuite(BuildExtTestCase) 74 75if __name__ == '__main__': 76 test_support.run_unittest(test_suite()) 77