test_build_ext.py 15 KB
Newer Older
Georg Brandl's avatar
Georg Brandl committed
1 2
import sys
import os
3
import tempfile
Georg Brandl's avatar
Georg Brandl committed
4 5
import shutil
from io import StringIO
6 7 8
import warnings
from test.support import check_warnings
from test.support import captured_stdout
Georg Brandl's avatar
Georg Brandl committed
9 10 11 12

from distutils.core import Extension, Distribution
from distutils.command.build_ext import build_ext
from distutils import sysconfig
13
from distutils.tests.support import TempdirManager
14 15
from distutils.tests.support import LoggingSilencer
from distutils.extension import Extension
16 17
from distutils.errors import (UnknownFileError, DistutilsSetupError,
                              CompileError)
Georg Brandl's avatar
Georg Brandl committed
18 19 20 21

import unittest
from test import support

22 23 24 25
# http://bugs.python.org/issue4373
# Don't load the xx module more than once.
ALREADY_TESTED = False

26 27 28 29
def _get_source_filename():
    srcdir = sysconfig.get_config_var('srcdir')
    return os.path.join(srcdir, 'Modules', 'xxmodule.c')

30 31 32
class BuildExtTestCase(TempdirManager,
                       LoggingSilencer,
                       unittest.TestCase):
Georg Brandl's avatar
Georg Brandl committed
33 34 35
    def setUp(self):
        # Create a simple test environment
        # Note that we're making changes to sys.path
36
        super(BuildExtTestCase, self).setUp()
37
        self.tmp_dir = self.mkdtemp()
Georg Brandl's avatar
Georg Brandl committed
38 39
        self.sys_path = sys.path[:]
        sys.path.append(self.tmp_dir)
40
        shutil.copy(_get_source_filename(), self.tmp_dir)
41 42 43 44 45 46
        if sys.version > "2.6":
            import site
            self.old_user_base = site.USER_BASE
            site.USER_BASE = self.mkdtemp()
            from distutils.command import build_ext
            build_ext.USER_BASE = site.USER_BASE
Georg Brandl's avatar
Georg Brandl committed
47 48

    def test_build_ext(self):
49
        global ALREADY_TESTED
Georg Brandl's avatar
Georg Brandl committed
50 51 52 53 54
        xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
        xx_ext = Extension('xx', [xx_c])
        dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
        dist.package_dir = self.tmp_dir
        cmd = build_ext(dist)
55 56 57 58
        if os.name == "nt":
            # On Windows, we must build a debug version iff running
            # a debug build of Python
            cmd.debug = sys.executable.endswith("_d.exe")
Georg Brandl's avatar
Georg Brandl committed
59 60 61 62 63 64 65 66 67 68 69 70 71
        cmd.build_lib = self.tmp_dir
        cmd.build_temp = self.tmp_dir

        old_stdout = sys.stdout
        if not support.verbose:
            # silence compiler output
            sys.stdout = StringIO()
        try:
            cmd.ensure_finalized()
            cmd.run()
        finally:
            sys.stdout = old_stdout

72 73 74 75 76
        if ALREADY_TESTED:
            return
        else:
            ALREADY_TESTED = True

Georg Brandl's avatar
Georg Brandl committed
77 78 79
        import xx

        for attr in ('error', 'foo', 'new', 'roj'):
80
            self.assertTrue(hasattr(xx, attr))
Georg Brandl's avatar
Georg Brandl committed
81 82 83 84 85 86

        self.assertEquals(xx.foo(2, 5), 7)
        self.assertEquals(xx.foo(13,15), 28)
        self.assertEquals(xx.new().demo(), None)
        doc = 'This is a template module just for instruction.'
        self.assertEquals(xx.__doc__, doc)
87 88
        self.assertTrue(isinstance(xx.Null(), xx.Null))
        self.assertTrue(isinstance(xx.Str(), xx.Str))
Georg Brandl's avatar
Georg Brandl committed
89 90 91 92 93

    def tearDown(self):
        # Get everything back to normal
        support.unload('xx')
        sys.path = self.sys_path
94 95 96 97 98 99
        if sys.version > "2.6":
            import site
            site.USER_BASE = self.old_user_base
            from distutils.command import build_ext
            build_ext.USER_BASE = self.old_user_base
        super(BuildExtTestCase, self).tearDown()
Georg Brandl's avatar
Georg Brandl committed
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    def test_solaris_enable_shared(self):
        dist = Distribution({'name': 'xx'})
        cmd = build_ext(dist)
        old = sys.platform

        sys.platform = 'sunos' # fooling finalize_options
        from distutils.sysconfig import  _config_vars
        old_var = _config_vars.get('Py_ENABLE_SHARED')
        _config_vars['Py_ENABLE_SHARED'] = 1
        try:
            cmd.ensure_finalized()
        finally:
            sys.platform = old
            if old_var is None:
                del _config_vars['Py_ENABLE_SHARED']
            else:
                _config_vars['Py_ENABLE_SHARED'] = old_var

119
        # make sure we get some library dirs under solaris
120
        self.assertTrue(len(cmd.library_dirs) > 0)
121

122 123 124 125 126 127 128 129 130
    def test_user_site(self):
        # site.USER_SITE was introduced in 2.6
        if sys.version < '2.6':
            return

        import site
        dist = Distribution({'name': 'xx'})
        cmd = build_ext(dist)

131
        # making sure the user option is there
132 133
        options = [name for name, short, lable in
                   cmd.user_options]
134
        self.assertTrue('user' in options)
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

        # setting a value
        cmd.user = 1

        # setting user based lib and include
        lib = os.path.join(site.USER_BASE, 'lib')
        incl = os.path.join(site.USER_BASE, 'include')
        os.mkdir(lib)
        os.mkdir(incl)

        # let's run finalize
        cmd.ensure_finalized()

        # see if include_dirs and library_dirs
        # were set
150 151 152
        self.assertTrue(lib in cmd.library_dirs)
        self.assertTrue(lib in cmd.rpath)
        self.assertTrue(incl in cmd.include_dirs)
153

154 155 156 157 158 159 160 161
    def test_optional_extension(self):

        # this extension will fail, but let's ignore this failure
        # with the optional argument.
        modules = [Extension('foo', ['xxx'], optional=False)]
        dist = Distribution({'name': 'xx', 'ext_modules': modules})
        cmd = build_ext(dist)
        cmd.ensure_finalized()
162 163
        self.assertRaises((UnknownFileError, CompileError),
                          cmd.run)  # should raise an error
164 165 166 167 168 169 170

        modules = [Extension('foo', ['xxx'], optional=True)]
        dist = Distribution({'name': 'xx', 'ext_modules': modules})
        cmd = build_ext(dist)
        cmd.ensure_finalized()
        cmd.run()  # should pass

171 172 173 174 175 176 177 178 179 180
    def test_finalize_options(self):
        # Make sure Python's include directories (for Python.h, pyconfig.h,
        # etc.) are in the include search path.
        modules = [Extension('foo', ['xxx'], optional=False)]
        dist = Distribution({'name': 'xx', 'ext_modules': modules})
        cmd = build_ext(dist)
        cmd.finalize_options()

        from distutils import sysconfig
        py_include = sysconfig.get_python_inc()
181
        self.assertTrue(py_include in cmd.include_dirs)
182 183

        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
184
        self.assertTrue(plat_py_include in cmd.include_dirs)
185 186 187 188 189 190 191 192 193 194 195 196 197

        # make sure cmd.libraries is turned into a list
        # if it's a string
        cmd = build_ext(dist)
        cmd.libraries = 'my_lib'
        cmd.finalize_options()
        self.assertEquals(cmd.libraries, ['my_lib'])

        # make sure cmd.library_dirs is turned into a list
        # if it's a string
        cmd = build_ext(dist)
        cmd.library_dirs = 'my_lib_dir'
        cmd.finalize_options()
198
        self.assertTrue('my_lib_dir' in cmd.library_dirs)
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

        # make sure rpath is turned into a list
        # if it's a list of os.pathsep's paths
        cmd = build_ext(dist)
        cmd.rpath = os.pathsep.join(['one', 'two'])
        cmd.finalize_options()
        self.assertEquals(cmd.rpath, ['one', 'two'])

        # XXX more tests to perform for win32

        # make sure define is turned into 2-tuples
        # strings if they are ','-separated strings
        cmd = build_ext(dist)
        cmd.define = 'one,two'
        cmd.finalize_options()
        self.assertEquals(cmd.define, [('one', '1'), ('two', '1')])

        # make sure undef is turned into a list of
        # strings if they are ','-separated strings
        cmd = build_ext(dist)
        cmd.undef = 'one,two'
        cmd.finalize_options()
        self.assertEquals(cmd.undef, ['one', 'two'])

        # make sure swig_opts is turned into a list
        cmd = build_ext(dist)
        cmd.swig_opts = None
        cmd.finalize_options()
        self.assertEquals(cmd.swig_opts, [])

        cmd = build_ext(dist)
        cmd.swig_opts = '1 2'
        cmd.finalize_options()
        self.assertEquals(cmd.swig_opts, ['1', '2'])

    def test_check_extensions_list(self):
        dist = Distribution()
        cmd = build_ext(dist)
        cmd.finalize_options()

        #'extensions' option must be a list of Extension instances
        self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, 'foo')

        # each element of 'ext_modules' option must be an
        # Extension instance or 2-tuple
        exts = [('bar', 'foo', 'bar'), 'foo']
        self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)

        # first element of each tuple in 'ext_modules'
        # must be the extension name (a string) and match
        # a python dotted-separated name
        exts = [('foo-bar', '')]
        self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)

        # second element of each tuple in 'ext_modules'
        # must be a ary (build info)
        exts = [('foo.bar', '')]
        self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)

        # ok this one should pass
        exts = [('foo.bar', {'sources': [''], 'libraries': 'foo',
                             'some': 'bar'})]
        cmd.check_extensions_list(exts)
        ext = exts[0]
263
        self.assertTrue(isinstance(ext, Extension))
264 265 266 267 268

        # check_extensions_list adds in ext the values passed
        # when they are in ('include_dirs', 'library_dirs', 'libraries'
        # 'extra_objects', 'extra_compile_args', 'extra_link_args')
        self.assertEquals(ext.libraries, 'foo')
269
        self.assertTrue(not hasattr(ext, 'some'))
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

        # 'macros' element of build info dict must be 1- or 2-tuple
        exts = [('foo.bar', {'sources': [''], 'libraries': 'foo',
                'some': 'bar', 'macros': [('1', '2', '3'), 'foo']})]
        self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)

        exts[0][1]['macros'] = [('1', '2'), ('3',)]
        cmd.check_extensions_list(exts)
        self.assertEquals(exts[0].undef_macros, ['3'])
        self.assertEquals(exts[0].define_macros, [('1', '2')])

    def test_get_source_files(self):
        modules = [Extension('foo', ['xxx'], optional=False)]
        dist = Distribution({'name': 'xx', 'ext_modules': modules})
        cmd = build_ext(dist)
        cmd.ensure_finalized()
        self.assertEquals(cmd.get_source_files(), ['xxx'])

288 289 290 291 292 293 294 295 296 297 298
    def test_compiler_option(self):
        # cmd.compiler is an option and
        # should not be overriden by a compiler instance
        # when the command is run
        dist = Distribution()
        cmd = build_ext(dist)
        cmd.compiler = 'unix'
        cmd.ensure_finalized()
        cmd.run()
        self.assertEquals(cmd.compiler, 'unix')

299
    def test_get_outputs(self):
300 301
        tmp_dir = self.mkdtemp()
        c_file = os.path.join(tmp_dir, 'foo.c')
302
        self.write_file(c_file, 'void initfoo(void) {};\n')
303 304 305
        ext = Extension('foo', [c_file], optional=False)
        dist = Distribution({'name': 'xx',
                             'ext_modules': [ext]})
306 307 308 309
        cmd = build_ext(dist)
        cmd.ensure_finalized()
        self.assertEquals(len(cmd.get_outputs()), 1)

310 311 312 313 314 315 316 317
        if os.name == "nt":
            cmd.debug = sys.executable.endswith("_d.exe")

        cmd.build_lib = os.path.join(self.tmp_dir, 'build')
        cmd.build_temp = os.path.join(self.tmp_dir, 'tempt')

        # issue #5977 : distutils build_ext.get_outputs
        # returns wrong result with --inplace
318 319 320 321 322 323 324 325 326
        other_tmp_dir = os.path.realpath(self.mkdtemp())
        old_wd = os.getcwd()
        os.chdir(other_tmp_dir)
        try:
            cmd.inplace = 1
            cmd.run()
            so_file = cmd.get_outputs()[0]
        finally:
            os.chdir(old_wd)
327
        self.assertTrue(os.path.exists(so_file))
328 329
        self.assertEquals(os.path.splitext(so_file)[-1],
                          sysconfig.get_config_var('SO'))
330
        so_dir = os.path.dirname(so_file)
331
        self.assertEquals(so_dir, other_tmp_dir)
332 333 334 335

        cmd.inplace = 0
        cmd.run()
        so_file = cmd.get_outputs()[0]
336
        self.assertTrue(os.path.exists(so_file))
337 338
        self.assertEquals(os.path.splitext(so_file)[-1],
                          sysconfig.get_config_var('SO'))
339 340 341
        so_dir = os.path.dirname(so_file)
        self.assertEquals(so_dir, cmd.build_lib)

342
        # inplace = 0, cmd.package = 'bar'
343 344
        build_py = cmd.get_finalized_command('build_py')
        build_py.package_dir = {'': 'bar'}
345
        path = cmd.get_ext_fullpath('foo')
346
        # checking that the last directory is the build_dir
347
        path = os.path.split(path)[0]
348
        self.assertEquals(path, cmd.build_lib)
349 350 351 352 353 354 355 356 357 358 359 360 361

        # inplace = 1, cmd.package = 'bar'
        cmd.inplace = 1
        other_tmp_dir = os.path.realpath(self.mkdtemp())
        old_wd = os.getcwd()
        os.chdir(other_tmp_dir)
        try:
            path = cmd.get_ext_fullpath('foo')
        finally:
            os.chdir(old_wd)
        # checking that the last directory is bar
        path = os.path.split(path)[0]
        lastdir = os.path.split(path)[-1]
362
        self.assertEquals(lastdir, 'bar')
363

364 365 366 367 368 369
    def test_ext_fullpath(self):
        # building lxml.etree inplace
        #etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
        #etree_ext = Extension('lxml.etree', [etree_c])
        #dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
        dist = Distribution()
370 371 372 373 374 375 376 377 378
        cmd = build_ext(dist)
        cmd.inplace = 1
        cmd.distribution.package_dir = {'': 'src'}
        cmd.distribution.packages = ['lxml', 'lxml.html']
        curdir = os.getcwd()
        wanted = os.path.join(curdir, 'src', 'lxml', 'etree.so')
        path = cmd.get_ext_fullpath('lxml.etree')
        self.assertEquals(wanted, path)

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
        # building lxml.etree not inplace
        cmd.inplace = 0
        cmd.build_lib = os.path.join(curdir, 'tmpdir')
        wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree.so')
        path = cmd.get_ext_fullpath('lxml.etree')
        self.assertEquals(wanted, path)

        # building twisted.runner.portmap not inplace
        build_py = cmd.get_finalized_command('build_py')
        build_py.package_dir = {}
        cmd.distribution.packages = ['twisted', 'twisted.runner.portmap']
        path = cmd.get_ext_fullpath('twisted.runner.portmap')
        wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
                              'portmap.so')
        self.assertEquals(wanted, path)

        # building twisted.runner.portmap inplace
        cmd.inplace = 1
        path = cmd.get_ext_fullpath('twisted.runner.portmap')
        wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap.so')
        self.assertEquals(wanted, path)

401 402 403 404 405 406 407 408 409 410 411
    def test_compiler_deprecation_warning(self):
        dist = Distribution()
        cmd = build_ext(dist)

        with check_warnings() as w:
            warnings.simplefilter("always")
            cmd.compiler = object()
            self.assertEquals(len(w.warnings), 1)
            cmd.compile = 'unix'
            self.assertEquals(len(w.warnings), 1)

Georg Brandl's avatar
Georg Brandl committed
412
def test_suite():
413 414
    src = _get_source_filename()
    if not os.path.exists(src):
Georg Brandl's avatar
Georg Brandl committed
415
        if support.verbose:
416 417
            print('test_build_ext: Cannot find source code (test'
                  ' must run in python build dir)')
Georg Brandl's avatar
Georg Brandl committed
418 419 420 421 422
        return unittest.TestSuite()
    else: return unittest.makeSuite(BuildExtTestCase)

if __name__ == '__main__':
    support.run_unittest(test_suite())