Changeset 391 for python/trunk/Lib/distutils/tests
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 22 edited
- 21 copied
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/distutils/tests/__init__.py
r2 r391 16 16 import sys 17 17 import unittest 18 from test.test_support import run_unittest 18 19 19 20 20 here = os.path.dirname(__file__) 21 here = os.path.dirname(__file__) or os.curdir 21 22 22 23 … … 33 34 34 35 if __name__ == "__main__": 35 unittest.main(defaultTest="test_suite")36 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/support.py
r2 r391 1 1 """Support code for distutils test cases.""" 2 2 import os 3 import sys 3 4 import shutil 4 5 import tempfile 5 6 import unittest 7 import sysconfig 8 from copy import deepcopy 9 import warnings 10 11 from distutils import log 6 12 from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL 7 from distutils import log 8 from distutils.dist import Distribution 9 from distutils.cmd import Command 13 from distutils.core import Distribution 14 15 16 def capture_warnings(func): 17 def _capture_warnings(*args, **kw): 18 with warnings.catch_warnings(): 19 warnings.simplefilter("ignore") 20 return func(*args, **kw) 21 return _capture_warnings 22 10 23 11 24 class LoggingSilencer(object): … … 20 33 log.Log._log = self._log 21 34 self.logs = [] 22 self._old_warn = Command.warn23 Command.warn = self._warn24 35 25 36 def tearDown(self): 26 37 log.set_threshold(self.threshold) 27 38 log.Log._log = self._old_log 28 Command.warn = self._old_warn29 39 super(LoggingSilencer, self).tearDown() 30 31 def _warn(self, msg):32 self.logs.append(('', msg, ''))33 40 34 41 def _log(self, level, msg, args): … … 57 64 def setUp(self): 58 65 super(TempdirManager, self).setUp() 66 self.old_cwd = os.getcwd() 59 67 self.tempdirs = [] 60 68 61 69 def tearDown(self): 70 # Restore working dir, for Solaris and derivatives, where rmdir() 71 # on the current directory fails. 72 os.chdir(self.old_cwd) 62 73 super(TempdirManager, self).tearDown() 63 74 while self.tempdirs: 64 75 d = self.tempdirs.pop() 65 shutil.rmtree(d )76 shutil.rmtree(d, os.name in ('nt', 'cygwin')) 66 77 67 78 def mkdtemp(self): … … 76 87 def write_file(self, path, content='xxx'): 77 88 """Writes a file in the given path. 89 78 90 79 91 path can be a string or a sequence. … … 104 116 return pkg_dir, dist 105 117 118 106 119 class DummyCommand: 107 120 """Class to store options for retrieval via set_undefined_options().""" … … 113 126 def ensure_finalized(self): 114 127 pass 128 129 130 class EnvironGuard(object): 131 132 def setUp(self): 133 super(EnvironGuard, self).setUp() 134 self.old_environ = deepcopy(os.environ) 135 136 def tearDown(self): 137 for key, value in self.old_environ.items(): 138 if os.environ.get(key) != value: 139 os.environ[key] = value 140 141 for key in os.environ.keys(): 142 if key not in self.old_environ: 143 del os.environ[key] 144 145 super(EnvironGuard, self).tearDown() 146 147 148 def copy_xxmodule_c(directory): 149 """Helper for tests that need the xxmodule.c source file. 150 151 Example use: 152 153 def test_compile(self): 154 copy_xxmodule_c(self.tmpdir) 155 self.assertIn('xxmodule.c', os.listdir(self.tmpdir)) 156 157 If the source file can be found, it will be copied to *directory*. If not, 158 the test will be skipped. Errors during copy are not caught. 159 """ 160 filename = _get_xxmodule_path() 161 if filename is None: 162 raise unittest.SkipTest('cannot find xxmodule.c (test must run in ' 163 'the python build dir)') 164 shutil.copy(filename, directory) 165 166 167 def _get_xxmodule_path(): 168 # FIXME when run from regrtest, srcdir seems to be '.', which does not help 169 # us find the xxmodule.c file 170 srcdir = sysconfig.get_config_var('srcdir') 171 candidates = [ 172 # use installed copy if available 173 os.path.join(os.path.dirname(__file__), 'xxmodule.c'), 174 # otherwise try using copy from build directory 175 os.path.join(srcdir, 'Modules', 'xxmodule.c'), 176 # srcdir mysteriously can be $srcdir/Lib/distutils/tests when 177 # this file is run from its parent directory, so walk up the 178 # tree to find the real srcdir 179 os.path.join(srcdir, '..', '..', '..', 'Modules', 'xxmodule.c'), 180 ] 181 for path in candidates: 182 if os.path.exists(path): 183 return path 184 185 186 def fixup_build_ext(cmd): 187 """Function needed to make build_ext tests pass. 188 189 When Python was build with --enable-shared on Unix, -L. is not good 190 enough to find the libpython<blah>.so. This is because regrtest runs 191 it under a tempdir, not in the top level where the .so lives. By the 192 time we've gotten here, Python's already been chdir'd to the tempdir. 193 194 When Python was built with in debug mode on Windows, build_ext commands 195 need their debug attribute set, and it is not done automatically for 196 some reason. 197 198 This function handles both of these things. Example use: 199 200 cmd = build_ext(dist) 201 support.fixup_build_ext(cmd) 202 cmd.ensure_finalized() 203 204 Unlike most other Unix platforms, Mac OS X embeds absolute paths 205 to shared libraries into executables, so the fixup is not needed there. 206 """ 207 if os.name == 'nt': 208 cmd.debug = sys.executable.endswith('_d.exe') 209 elif sysconfig.get_config_var('Py_ENABLE_SHARED'): 210 # To further add to the shared builds fun on Unix, we can't just add 211 # library_dirs to the Extension() instance because that doesn't get 212 # plumbed through to the final compiler command. 213 runshared = sysconfig.get_config_var('RUNSHARED') 214 if runshared is None: 215 cmd.library_dirs = ['.'] 216 else: 217 if sys.platform == 'darwin': 218 cmd.library_dirs = [] 219 else: 220 name, equals, value = runshared.partition('=') 221 cmd.library_dirs = value.split(os.pathsep) -
python/trunk/Lib/distutils/tests/test_bdist_wininst.py
r2 r391 1 1 """Tests for distutils.command.bdist_wininst.""" 2 2 import unittest 3 import os4 3 5 from distutils.dist import Distribution 4 from test.test_support import run_unittest 5 6 6 from distutils.command.bdist_wininst import bdist_wininst 7 7 from distutils.tests import support … … 16 16 # this test makes sure it works now for every platform 17 17 # let's create a command 18 tmp_dir = self.mkdtemp() 19 pkg_dir = os.path.join(tmp_dir, 'foo') 20 os.mkdir(pkg_dir) 21 dist = Distribution() 18 pkg_pth, dist = self.create_dist() 22 19 cmd = bdist_wininst(dist) 23 20 cmd.ensure_finalized() … … 27 24 # no matter what platform we have 28 25 exe_file = cmd.get_exe_bytes() 29 self.assert _(len(exe_file) > 10)26 self.assertTrue(len(exe_file) > 10) 30 27 31 28 def test_suite(): … … 33 30 34 31 if __name__ == '__main__': 35 test_support.run_unittest(test_suite())32 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_build_ext.py
r2 r391 1 1 import sys 2 2 import os 3 import tempfile4 import shutil5 3 from StringIO import StringIO 4 import textwrap 6 5 7 6 from distutils.core import Extension, Distribution … … 9 8 from distutils import sysconfig 10 9 from distutils.tests import support 11 from distutils.errors import DistutilsSetupError 10 from distutils.errors import (DistutilsSetupError, CompileError, 11 DistutilsPlatformError) 12 12 13 13 import unittest … … 18 18 ALREADY_TESTED = False 19 19 20 def _get_source_filename():21 srcdir = sysconfig.get_config_var('srcdir')22 if srcdir is None:23 return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')24 return os.path.join(srcdir, 'Modules', 'xxmodule.c')25 20 26 21 class BuildExtTestCase(support.TempdirManager, … … 28 23 unittest.TestCase): 29 24 def setUp(self): 30 # Create a simple test environment31 # Note that we're making changes to sys.path32 25 super(BuildExtTestCase, self).setUp() 33 self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_")34 self. sys_path = sys.path[:]26 self.tmp_dir = self.mkdtemp() 27 self.xx_created = False 35 28 sys.path.append(self.tmp_dir) 36 shutil.copy(_get_source_filename(), self.tmp_dir) 29 self.addCleanup(sys.path.remove, self.tmp_dir) 30 if sys.version > "2.6": 31 import site 32 self.old_user_base = site.USER_BASE 33 site.USER_BASE = self.mkdtemp() 34 from distutils.command import build_ext 35 build_ext.USER_BASE = site.USER_BASE 36 37 def tearDown(self): 38 if self.xx_created: 39 test_support.unload('xx') 40 # XXX on Windows the test leaves a directory 41 # with xx module in TEMP 42 super(BuildExtTestCase, self).tearDown() 37 43 38 44 def test_build_ext(self): 39 45 global ALREADY_TESTED 46 support.copy_xxmodule_c(self.tmp_dir) 47 self.xx_created = True 40 48 xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') 41 49 xx_ext = Extension('xx', [xx_c]) … … 43 51 dist.package_dir = self.tmp_dir 44 52 cmd = build_ext(dist) 45 if os.name == "nt": 46 # On Windows, we must build a debug version iff running 47 # a debug build of Python 48 cmd.debug = sys.executable.endswith("_d.exe") 53 support.fixup_build_ext(cmd) 49 54 cmd.build_lib = self.tmp_dir 50 55 cmd.build_temp = self.tmp_dir … … 68 73 69 74 for attr in ('error', 'foo', 'new', 'roj'): 70 self.assert_(hasattr(xx, attr)) 71 72 self.assertEquals(xx.foo(2, 5), 7) 73 self.assertEquals(xx.foo(13,15), 28) 74 self.assertEquals(xx.new().demo(), None) 75 doc = 'This is a template module just for instruction.' 76 self.assertEquals(xx.__doc__, doc) 77 self.assert_(isinstance(xx.Null(), xx.Null)) 78 self.assert_(isinstance(xx.Str(), xx.Str)) 79 80 def tearDown(self): 81 # Get everything back to normal 82 test_support.unload('xx') 83 sys.path = self.sys_path 84 # XXX on Windows the test leaves a directory with xx module in TEMP 85 shutil.rmtree(self.tmp_dir, os.name == 'nt' or sys.platform == 'cygwin') 86 super(BuildExtTestCase, self).tearDown() 75 self.assertTrue(hasattr(xx, attr)) 76 77 self.assertEqual(xx.foo(2, 5), 7) 78 self.assertEqual(xx.foo(13,15), 28) 79 self.assertEqual(xx.new().demo(), None) 80 if test_support.HAVE_DOCSTRINGS: 81 doc = 'This is a template module just for instruction.' 82 self.assertEqual(xx.__doc__, doc) 83 self.assertTrue(isinstance(xx.Null(), xx.Null)) 84 self.assertTrue(isinstance(xx.Str(), xx.Str)) 87 85 88 86 def test_solaris_enable_shared(self): … … 105 103 106 104 # make sure we get some library dirs under solaris 107 self.assert_(len(cmd.library_dirs) > 0) 105 self.assertTrue(len(cmd.library_dirs) > 0) 106 107 def test_user_site(self): 108 # site.USER_SITE was introduced in 2.6 109 if sys.version < '2.6': 110 return 111 112 import site 113 dist = Distribution({'name': 'xx'}) 114 cmd = build_ext(dist) 115 116 # making sure the user option is there 117 options = [name for name, short, label in 118 cmd.user_options] 119 self.assertIn('user', options) 120 121 # setting a value 122 cmd.user = 1 123 124 # setting user based lib and include 125 lib = os.path.join(site.USER_BASE, 'lib') 126 incl = os.path.join(site.USER_BASE, 'include') 127 os.mkdir(lib) 128 os.mkdir(incl) 129 130 cmd.ensure_finalized() 131 132 # see if include_dirs and library_dirs were set 133 self.assertIn(lib, cmd.library_dirs) 134 self.assertIn(lib, cmd.rpath) 135 self.assertIn(incl, cmd.include_dirs) 108 136 109 137 def test_finalize_options(self): … … 115 143 cmd.finalize_options() 116 144 117 from distutils import sysconfig118 145 py_include = sysconfig.get_python_inc() 119 self.assert _(py_include in cmd.include_dirs)146 self.assertTrue(py_include in cmd.include_dirs) 120 147 121 148 plat_py_include = sysconfig.get_python_inc(plat_specific=1) 122 self.assert _(plat_py_include in cmd.include_dirs)149 self.assertTrue(plat_py_include in cmd.include_dirs) 123 150 124 151 # make sure cmd.libraries is turned into a list 125 152 # if it's a string 126 153 cmd = build_ext(dist) 127 cmd.libraries = 'my_lib '128 cmd.finalize_options() 129 self.assertEqual s(cmd.libraries, ['my_lib'])154 cmd.libraries = 'my_lib, other_lib lastlib' 155 cmd.finalize_options() 156 self.assertEqual(cmd.libraries, ['my_lib', 'other_lib', 'lastlib']) 130 157 131 158 # make sure cmd.library_dirs is turned into a list 132 159 # if it's a string 133 160 cmd = build_ext(dist) 134 cmd.library_dirs = 'my_lib_dir' 135 cmd.finalize_options() 136 self.assert_('my_lib_dir' in cmd.library_dirs) 161 cmd.library_dirs = 'my_lib_dir%sother_lib_dir' % os.pathsep 162 cmd.finalize_options() 163 self.assertIn('my_lib_dir', cmd.library_dirs) 164 self.assertIn('other_lib_dir', cmd.library_dirs) 137 165 138 166 # make sure rpath is turned into a list 139 # if it's a list of os.pathsep's paths140 cmd = build_ext(dist) 141 cmd.rpath = os.pathsep.join(['one', 'two'])142 cmd.finalize_options() 143 self.assertEqual s(cmd.rpath, ['one', 'two'])167 # if it's a string 168 cmd = build_ext(dist) 169 cmd.rpath = 'one%stwo' % os.pathsep 170 cmd.finalize_options() 171 self.assertEqual(cmd.rpath, ['one', 'two']) 144 172 145 173 # XXX more tests to perform for win32 … … 150 178 cmd.define = 'one,two' 151 179 cmd.finalize_options() 152 self.assertEqual s(cmd.define, [('one', '1'), ('two', '1')])180 self.assertEqual(cmd.define, [('one', '1'), ('two', '1')]) 153 181 154 182 # make sure undef is turned into a list of … … 157 185 cmd.undef = 'one,two' 158 186 cmd.finalize_options() 159 self.assertEqual s(cmd.undef, ['one', 'two'])187 self.assertEqual(cmd.undef, ['one', 'two']) 160 188 161 189 # make sure swig_opts is turned into a list … … 163 191 cmd.swig_opts = None 164 192 cmd.finalize_options() 165 self.assertEqual s(cmd.swig_opts, [])193 self.assertEqual(cmd.swig_opts, []) 166 194 167 195 cmd = build_ext(dist) 168 196 cmd.swig_opts = '1 2' 169 197 cmd.finalize_options() 170 self.assertEqual s(cmd.swig_opts, ['1', '2'])198 self.assertEqual(cmd.swig_opts, ['1', '2']) 171 199 172 200 def test_check_extensions_list(self): … … 199 227 cmd.check_extensions_list(exts) 200 228 ext = exts[0] 201 self.assert _(isinstance(ext, Extension))229 self.assertTrue(isinstance(ext, Extension)) 202 230 203 231 # check_extensions_list adds in ext the values passed 204 232 # when they are in ('include_dirs', 'library_dirs', 'libraries' 205 233 # 'extra_objects', 'extra_compile_args', 'extra_link_args') 206 self.assertEqual s(ext.libraries, 'foo')207 self.assert _(not hasattr(ext, 'some'))234 self.assertEqual(ext.libraries, 'foo') 235 self.assertTrue(not hasattr(ext, 'some')) 208 236 209 237 # 'macros' element of build info dict must be 1- or 2-tuple … … 214 242 exts[0][1]['macros'] = [('1', '2'), ('3',)] 215 243 cmd.check_extensions_list(exts) 216 self.assertEqual s(exts[0].undef_macros, ['3'])217 self.assertEqual s(exts[0].define_macros, [('1', '2')])244 self.assertEqual(exts[0].undef_macros, ['3']) 245 self.assertEqual(exts[0].define_macros, [('1', '2')]) 218 246 219 247 def test_get_source_files(self): … … 222 250 cmd = build_ext(dist) 223 251 cmd.ensure_finalized() 224 self.assertEqual s(cmd.get_source_files(), ['xxx'])252 self.assertEqual(cmd.get_source_files(), ['xxx']) 225 253 226 254 def test_compiler_option(self): … … 233 261 cmd.ensure_finalized() 234 262 cmd.run() 235 self.assertEqual s(cmd.compiler, 'unix')263 self.assertEqual(cmd.compiler, 'unix') 236 264 237 265 def test_get_outputs(self): … … 243 271 'ext_modules': [ext]}) 244 272 cmd = build_ext(dist) 245 cmd.ensure_finalized() 246 self.assertEquals(len(cmd.get_outputs()), 1) 247 248 if os.name == "nt": 249 cmd.debug = sys.executable.endswith("_d.exe") 273 support.fixup_build_ext(cmd) 274 cmd.ensure_finalized() 275 self.assertEqual(len(cmd.get_outputs()), 1) 250 276 251 277 cmd.build_lib = os.path.join(self.tmp_dir, 'build') … … 263 289 finally: 264 290 os.chdir(old_wd) 265 self.assert _(os.path.exists(so_file))266 self.assertEqual s(os.path.splitext(so_file)[-1],267 291 self.assertTrue(os.path.exists(so_file)) 292 self.assertEqual(os.path.splitext(so_file)[-1], 293 sysconfig.get_config_var('SO')) 268 294 so_dir = os.path.dirname(so_file) 269 self.assertEqual s(so_dir, other_tmp_dir)295 self.assertEqual(so_dir, other_tmp_dir) 270 296 cmd.compiler = None 271 297 cmd.inplace = 0 272 298 cmd.run() 273 299 so_file = cmd.get_outputs()[0] 274 self.assert _(os.path.exists(so_file))275 self.assertEqual s(os.path.splitext(so_file)[-1],276 300 self.assertTrue(os.path.exists(so_file)) 301 self.assertEqual(os.path.splitext(so_file)[-1], 302 sysconfig.get_config_var('SO')) 277 303 so_dir = os.path.dirname(so_file) 278 self.assertEqual s(so_dir, cmd.build_lib)304 self.assertEqual(so_dir, cmd.build_lib) 279 305 280 306 # inplace = 0, cmd.package = 'bar' … … 284 310 # checking that the last directory is the build_dir 285 311 path = os.path.split(path)[0] 286 self.assertEqual s(path, cmd.build_lib)312 self.assertEqual(path, cmd.build_lib) 287 313 288 314 # inplace = 1, cmd.package = 'bar' … … 298 324 path = os.path.split(path)[0] 299 325 lastdir = os.path.split(path)[-1] 300 self.assertEqual s(lastdir, 'bar')326 self.assertEqual(lastdir, 'bar') 301 327 302 328 def test_ext_fullpath(self): … … 310 336 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 311 337 path = cmd.get_ext_fullpath('lxml.etree') 312 self.assertEqual s(wanted, path)338 self.assertEqual(wanted, path) 313 339 314 340 # building lxml.etree not inplace … … 317 343 wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext) 318 344 path = cmd.get_ext_fullpath('lxml.etree') 319 self.assertEqual s(wanted, path)345 self.assertEqual(wanted, path) 320 346 321 347 # building twisted.runner.portmap not inplace … … 326 352 wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 327 353 'portmap' + ext) 328 self.assertEqual s(wanted, path)354 self.assertEqual(wanted, path) 329 355 330 356 # building twisted.runner.portmap inplace … … 332 358 path = cmd.get_ext_fullpath('twisted.runner.portmap') 333 359 wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext) 334 self.assertEqual s(wanted, path)360 self.assertEqual(wanted, path) 335 361 336 362 def test_build_ext_inplace(self): … … 347 373 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 348 374 path = cmd.get_ext_fullpath('lxml.etree') 349 self.assertEqual s(wanted, path)375 self.assertEqual(wanted, path) 350 376 351 377 def test_setuptools_compat(self): 352 from setuptools_build_ext import build_ext as setuptools_build_ext 353 from setuptools_extension import Extension 354 355 etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') 356 etree_ext = Extension('lxml.etree', [etree_c]) 357 dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) 358 cmd = setuptools_build_ext(dist) 359 cmd.ensure_finalized() 360 cmd.inplace = 1 361 cmd.distribution.package_dir = {'': 'src'} 362 cmd.distribution.packages = ['lxml', 'lxml.html'] 363 curdir = os.getcwd() 364 ext = sysconfig.get_config_var("SO") 365 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 366 path = cmd.get_ext_fullpath('lxml.etree') 367 self.assertEquals(wanted, path) 378 import distutils.core, distutils.extension, distutils.command.build_ext 379 saved_ext = distutils.extension.Extension 380 try: 381 # on some platforms, it loads the deprecated "dl" module 382 test_support.import_module('setuptools_build_ext', deprecated=True) 383 384 # theses import patch Distutils' Extension class 385 from setuptools_build_ext import build_ext as setuptools_build_ext 386 from setuptools_extension import Extension 387 388 etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') 389 etree_ext = Extension('lxml.etree', [etree_c]) 390 dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) 391 cmd = setuptools_build_ext(dist) 392 cmd.ensure_finalized() 393 cmd.inplace = 1 394 cmd.distribution.package_dir = {'': 'src'} 395 cmd.distribution.packages = ['lxml', 'lxml.html'] 396 curdir = os.getcwd() 397 ext = sysconfig.get_config_var("SO") 398 wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) 399 path = cmd.get_ext_fullpath('lxml.etree') 400 self.assertEqual(wanted, path) 401 finally: 402 # restoring Distutils' Extension class otherwise its broken 403 distutils.extension.Extension = saved_ext 404 distutils.core.Extension = saved_ext 405 distutils.command.build_ext.Extension = saved_ext 368 406 369 407 def test_build_ext_path_with_os_sep(self): … … 375 413 ext_path = cmd.get_ext_fullpath(ext_name) 376 414 wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext) 377 self.assertEqual s(ext_path, wanted)415 self.assertEqual(ext_path, wanted) 378 416 379 417 def test_build_ext_path_cross_platform(self): … … 388 426 ext_path = cmd.get_ext_fullpath(ext_name) 389 427 wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext) 390 self.assertEquals(ext_path, wanted) 428 self.assertEqual(ext_path, wanted) 429 430 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') 431 def test_deployment_target_default(self): 432 # Issue 9516: Test that, in the absence of the environment variable, 433 # an extension module is compiled with the same deployment target as 434 # the interpreter. 435 self._try_compile_deployment_target('==', None) 436 437 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') 438 def test_deployment_target_too_low(self): 439 # Issue 9516: Test that an extension module is not allowed to be 440 # compiled with a deployment target less than that of the interpreter. 441 self.assertRaises(DistutilsPlatformError, 442 self._try_compile_deployment_target, '>', '10.1') 443 444 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX') 445 def test_deployment_target_higher_ok(self): 446 # Issue 9516: Test that an extension module can be compiled with a 447 # deployment target higher than that of the interpreter: the ext 448 # module may depend on some newer OS feature. 449 deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') 450 if deptarget: 451 # increment the minor version number (i.e. 10.6 -> 10.7) 452 deptarget = [int(x) for x in deptarget.split('.')] 453 deptarget[-1] += 1 454 deptarget = '.'.join(str(i) for i in deptarget) 455 self._try_compile_deployment_target('<', deptarget) 456 457 def _try_compile_deployment_target(self, operator, target): 458 orig_environ = os.environ 459 os.environ = orig_environ.copy() 460 self.addCleanup(setattr, os, 'environ', orig_environ) 461 462 if target is None: 463 if os.environ.get('MACOSX_DEPLOYMENT_TARGET'): 464 del os.environ['MACOSX_DEPLOYMENT_TARGET'] 465 else: 466 os.environ['MACOSX_DEPLOYMENT_TARGET'] = target 467 468 deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c') 469 470 with open(deptarget_c, 'w') as fp: 471 fp.write(textwrap.dedent('''\ 472 #include <AvailabilityMacros.h> 473 474 int dummy; 475 476 #if TARGET %s MAC_OS_X_VERSION_MIN_REQUIRED 477 #else 478 #error "Unexpected target" 479 #endif 480 481 ''' % operator)) 482 483 # get the deployment target that the interpreter was built with 484 target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') 485 target = tuple(map(int, target.split('.'))) 486 target = '%02d%01d0' % target 487 deptarget_ext = Extension( 488 'deptarget', 489 [deptarget_c], 490 extra_compile_args=['-DTARGET=%s'%(target,)], 491 ) 492 dist = Distribution({ 493 'name': 'deptarget', 494 'ext_modules': [deptarget_ext] 495 }) 496 dist.package_dir = self.tmp_dir 497 cmd = build_ext(dist) 498 cmd.build_lib = self.tmp_dir 499 cmd.build_temp = self.tmp_dir 500 501 try: 502 cmd.ensure_finalized() 503 cmd.run() 504 except CompileError: 505 self.fail("Wrong deployment target during compilation") 391 506 392 507 def test_suite(): 393 src = _get_source_filename() 394 if not os.path.exists(src): 395 if test_support.verbose: 396 print ('test_build_ext: Cannot find source code (test' 397 ' must run in python build dir)') 398 return unittest.TestSuite() 399 else: return unittest.makeSuite(BuildExtTestCase) 508 return unittest.makeSuite(BuildExtTestCase) 400 509 401 510 if __name__ == '__main__': -
python/trunk/Lib/distutils/tests/test_build_py.py
r2 r391 11 11 12 12 from distutils.tests import support 13 from test.test_support import run_unittest 13 14 14 15 … … 20 21 sources = self.mkdtemp() 21 22 f = open(os.path.join(sources, "__init__.py"), "w") 22 f.write("# Pretend this is a package.") 23 f.close() 23 try: 24 f.write("# Pretend this is a package.") 25 finally: 26 f.close() 24 27 f = open(os.path.join(sources, "README.txt"), "w") 25 f.write("Info about this package") 26 f.close() 28 try: 29 f.write("Info about this package") 30 finally: 31 f.close() 27 32 28 33 destination = self.mkdtemp() … … 53 58 pkgdest = os.path.join(destination, "pkg") 54 59 files = os.listdir(pkgdest) 55 self.assert_("__init__.py" in files) 56 self.assert_("__init__.pyc" in files) 57 self.assert_("README.txt" in files) 60 self.assertIn("__init__.py", files) 61 self.assertIn("README.txt", files) 62 # XXX even with -O, distutils writes pyc, not pyo; bug? 63 if sys.dont_write_bytecode: 64 self.assertNotIn("__init__.pyc", files) 65 else: 66 self.assertIn("__init__.pyc", files) 58 67 59 def test_empty_package_dir 68 def test_empty_package_dir(self): 60 69 # See SF 1668596/1720897. 61 70 cwd = os.getcwd() … … 105 114 sys.dont_write_bytecode = old_dont_write_bytecode 106 115 107 self.assert True('byte-compiling is disabled' inself.logs[0][1])116 self.assertIn('byte-compiling is disabled', self.logs[0][1]) 108 117 109 118 def test_suite(): … … 111 120 112 121 if __name__ == "__main__": 113 unittest.main(defaultTest="test_suite")122 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_build_scripts.py
r2 r391 6 6 from distutils.command.build_scripts import build_scripts 7 7 from distutils.core import Distribution 8 from distutilsimport sysconfig8 import sysconfig 9 9 10 10 from distutils.tests import support 11 from test.test_support import run_unittest 11 12 12 13 … … 17 18 def test_default_settings(self): 18 19 cmd = self.get_build_scripts_cmd("/foo/bar", []) 19 self.assert _(not cmd.force)20 self.assert _(cmd.build_dir is None)20 self.assertTrue(not cmd.force) 21 self.assertTrue(cmd.build_dir is None) 21 22 22 23 cmd.finalize_options() 23 24 24 self.assert _(cmd.force)25 self.assertTrue(cmd.force) 25 26 self.assertEqual(cmd.build_dir, "/foo/bar") 26 27 … … 38 39 built = os.listdir(target) 39 40 for name in expected: 40 self.assert _(name in built)41 self.assertTrue(name in built) 41 42 42 43 def get_build_scripts_cmd(self, target, scripts): … … 72 73 def write_script(self, dir, name, text): 73 74 f = open(os.path.join(dir, name), "w") 74 f.write(text) 75 f.close() 75 try: 76 f.write(text) 77 finally: 78 f.close() 76 79 77 80 def test_version_int(self): … … 92 95 # failed when writing the name of the executable 93 96 old = sysconfig.get_config_vars().get('VERSION') 94 sysconfig._ config_vars['VERSION'] = 497 sysconfig._CONFIG_VARS['VERSION'] = 4 95 98 try: 96 99 cmd.run() 97 100 finally: 98 101 if old is not None: 99 sysconfig._ config_vars['VERSION'] = old102 sysconfig._CONFIG_VARS['VERSION'] = old 100 103 101 104 built = os.listdir(target) 102 105 for name in expected: 103 self.assert _(name in built)106 self.assertTrue(name in built) 104 107 105 108 def test_suite(): … … 107 110 108 111 if __name__ == "__main__": 109 unittest.main(defaultTest="test_suite")112 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_config.py
r2 r391 3 3 import os 4 4 import unittest 5 import tempfile 6 import shutil 5 7 6 8 from distutils.core import PyPIRCCommand … … 10 12 11 13 from distutils.tests import support 14 from test.test_support import run_unittest 12 15 13 16 PYPIRC = """\ … … 46 49 47 50 48 class PyPIRCCommandTestCase(support.TempdirManager, unittest.TestCase): 51 class PyPIRCCommandTestCase(support.TempdirManager, 52 support.LoggingSilencer, 53 support.EnvironGuard, 54 unittest.TestCase): 49 55 50 56 def setUp(self): 51 57 """Patches the environment.""" 52 58 super(PyPIRCCommandTestCase, self).setUp() 53 if os.environ.has_key('HOME'): 54 self._old_home = os.environ['HOME'] 55 else: 56 self._old_home = None 57 tempdir = self.mkdtemp() 58 os.environ['HOME'] = tempdir 59 self.rc = os.path.join(tempdir, '.pypirc') 59 self.tmp_dir = self.mkdtemp() 60 os.environ['HOME'] = self.tmp_dir 61 self.rc = os.path.join(self.tmp_dir, '.pypirc') 60 62 self.dist = Distribution() 61 63 … … 72 74 def tearDown(self): 73 75 """Removes the patch.""" 74 if self._old_home is None:75 del os.environ['HOME']76 else:77 os.environ['HOME'] = self._old_home78 76 set_threshold(self.old_threshold) 79 77 super(PyPIRCCommandTestCase, self).tearDown() … … 85 83 86 84 # new format 87 f = open(self.rc, 'w') 88 try: 89 f.write(PYPIRC) 90 finally: 91 f.close() 92 85 self.write_file(self.rc, PYPIRC) 93 86 cmd = self._cmd(self.dist) 94 87 config = cmd._read_pypirc() … … 99 92 ('repository', 'http://pypi.python.org/pypi'), 100 93 ('server', 'server1'), ('username', 'me')] 101 self.assertEqual s(config, waited)94 self.assertEqual(config, waited) 102 95 103 96 # old format 104 f = open(self.rc, 'w') 105 f.write(PYPIRC_OLD) 106 f.close() 107 97 self.write_file(self.rc, PYPIRC_OLD) 108 98 config = cmd._read_pypirc() 109 99 config = config.items() … … 112 102 ('repository', 'http://pypi.python.org/pypi'), 113 103 ('server', 'server-login'), ('username', 'tarek')] 114 self.assertEqual s(config, waited)104 self.assertEqual(config, waited) 115 105 116 106 def test_server_empty_registration(self): 117 118 107 cmd = self._cmd(self.dist) 119 108 rc = cmd._get_rc_file() 120 self.assert_(not os.path.exists(rc)) 121 109 self.assertTrue(not os.path.exists(rc)) 122 110 cmd._store_pypirc('tarek', 'xxx') 123 124 self.assert_(os.path.exists(rc)) 125 content = open(rc).read() 126 127 self.assertEquals(content, WANTED) 128 111 self.assertTrue(os.path.exists(rc)) 112 f = open(rc) 113 try: 114 content = f.read() 115 self.assertEqual(content, WANTED) 116 finally: 117 f.close() 129 118 130 119 def test_suite(): … … 132 121 133 122 if __name__ == "__main__": 134 unittest.main(defaultTest="test_suite")123 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_core.py
r2 r391 7 7 import sys 8 8 import test.test_support 9 from test.test_support import captured_stdout, run_unittest 9 10 import unittest 10 11 from distutils.tests import support 11 12 12 13 # setup script that uses __file__ … … 29 30 30 31 31 class CoreTestCase( unittest.TestCase):32 class CoreTestCase(support.EnvironGuard, unittest.TestCase): 32 33 33 34 def setUp(self): 35 super(CoreTestCase, self).setUp() 34 36 self.old_stdout = sys.stdout 35 37 self.cleanup_testfn() 38 self.old_argv = sys.argv, sys.argv[:] 36 39 37 40 def tearDown(self): 38 41 sys.stdout = self.old_stdout 39 42 self.cleanup_testfn() 43 sys.argv = self.old_argv[0] 44 sys.argv[:] = self.old_argv[1] 45 super(CoreTestCase, self).tearDown() 40 46 41 47 def cleanup_testfn(self): … … 47 53 48 54 def write_setup(self, text, path=test.test_support.TESTFN): 49 open(path, "w").write(text) 55 f = open(path, "w") 56 try: 57 f.write(text) 58 finally: 59 f.close() 50 60 return path 51 61 … … 74 84 self.assertEqual(cwd, output) 75 85 86 def test_debug_mode(self): 87 # this covers the code called when DEBUG is set 88 sys.argv = ['setup.py', '--name'] 89 with captured_stdout() as stdout: 90 distutils.core.setup(name='bar') 91 stdout.seek(0) 92 self.assertEqual(stdout.read(), 'bar\n') 93 94 distutils.core.DEBUG = True 95 try: 96 with captured_stdout() as stdout: 97 distutils.core.setup(name='bar') 98 finally: 99 distutils.core.DEBUG = False 100 stdout.seek(0) 101 wanted = "options (after parsing config files):\n" 102 self.assertEqual(stdout.readlines()[0], wanted) 76 103 77 104 def test_suite(): … … 79 106 80 107 if __name__ == "__main__": 81 unittest.main(defaultTest="test_suite")108 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_dist.py
r2 r391 1 # -*- coding: latin-1-*-1 # -*- coding: utf8 -*- 2 2 3 3 """Tests for distutils.dist.""" 4 5 import distutils.cmd6 import distutils.dist7 4 import os 8 5 import StringIO … … 12 9 import textwrap 13 10 14 from test.test_support import TESTFN 15 16 17 class test_dist(distutils.cmd.Command): 11 from distutils.dist import Distribution, fix_help_options 12 from distutils.cmd import Command 13 import distutils.dist 14 from test.test_support import TESTFN, captured_stdout, run_unittest 15 from distutils.tests import support 16 17 18 class test_dist(Command): 18 19 """Sample distutils extension command.""" 19 20 … … 26 27 27 28 28 class TestDistribution( distutils.dist.Distribution):29 class TestDistribution(Distribution): 29 30 """Distribution subclasses that avoids the default search for 30 31 configuration files. … … 38 39 39 40 40 class DistributionTestCase(unittest.TestCase): 41 class DistributionTestCase(support.TempdirManager, 42 support.LoggingSilencer, 43 support.EnvironGuard, 44 unittest.TestCase): 41 45 42 46 def setUp(self): 43 self.argv = sys.argv[:] 47 super(DistributionTestCase, self).setUp() 48 self.argv = sys.argv, sys.argv[:] 44 49 del sys.argv[1:] 45 50 46 51 def tearDown(self): 47 sys.argv[:] = self.argv 52 sys.argv = self.argv[0] 53 sys.argv[:] = self.argv[1] 54 super(DistributionTestCase, self).tearDown() 48 55 49 56 def create_distribution(self, configfiles=()): … … 53 60 d.parse_command_line() 54 61 return d 62 63 def test_debug_mode(self): 64 with open(TESTFN, "w") as f: 65 f.write("[global]\n") 66 f.write("command_packages = foo.bar, splat") 67 68 files = [TESTFN] 69 sys.argv.append("build") 70 71 with captured_stdout() as stdout: 72 self.create_distribution(files) 73 stdout.seek(0) 74 self.assertEqual(stdout.read(), '') 75 distutils.dist.DEBUG = True 76 try: 77 with captured_stdout() as stdout: 78 self.create_distribution(files) 79 stdout.seek(0) 80 self.assertEqual(stdout.read(), '') 81 finally: 82 distutils.dist.DEBUG = False 55 83 56 84 def test_command_packages_unspecified(self): … … 71 99 ["distutils.command", "foo.bar", "distutils.tests"]) 72 100 cmd = d.get_command_obj("test_dist") 73 self.assert _(isinstance(cmd, test_dist))101 self.assertIsInstance(cmd, test_dist) 74 102 self.assertEqual(cmd.sample_option, "sometext") 75 103 76 104 def test_command_packages_configfile(self): 77 105 sys.argv.append("build") 106 self.addCleanup(os.unlink, TESTFN) 78 107 f = open(TESTFN, "w") 79 108 try: 80 print >>f, "[global]" 81 print >>f, "command_packages = foo.bar, splat" 109 print >> f, "[global]" 110 print >> f, "command_packages = foo.bar, splat" 111 finally: 82 112 f.close() 83 d = self.create_distribution([TESTFN]) 84 self.assertEqual(d.get_command_packages(), 85 ["distutils.command", "foo.bar", "splat"]) 86 87 # ensure command line overrides config: 88 sys.argv[1:] = ["--command-packages", "spork", "build"] 89 d = self.create_distribution([TESTFN]) 90 self.assertEqual(d.get_command_packages(), 91 ["distutils.command", "spork"]) 92 93 # Setting --command-packages to '' should cause the default to 94 # be used even if a config file specified something else: 95 sys.argv[1:] = ["--command-packages", "", "build"] 96 d = self.create_distribution([TESTFN]) 97 self.assertEqual(d.get_command_packages(), ["distutils.command"]) 98 99 finally: 100 os.unlink(TESTFN) 113 114 d = self.create_distribution([TESTFN]) 115 self.assertEqual(d.get_command_packages(), 116 ["distutils.command", "foo.bar", "splat"]) 117 118 # ensure command line overrides config: 119 sys.argv[1:] = ["--command-packages", "spork", "build"] 120 d = self.create_distribution([TESTFN]) 121 self.assertEqual(d.get_command_packages(), 122 ["distutils.command", "spork"]) 123 124 # Setting --command-packages to '' should cause the default to 125 # be used even if a config file specified something else: 126 sys.argv[1:] = ["--command-packages", "", "build"] 127 d = self.create_distribution([TESTFN]) 128 self.assertEqual(d.get_command_packages(), ["distutils.command"]) 101 129 102 130 def test_write_pkg_file(self): 103 131 # Check DistributionMetadata handling of Unicode fields 104 my_file = os.path.join(os.path.dirname(__file__), 'f') 105 klass = distutils.dist.Distribution 106 107 dist = klass(attrs={'author': u'Mister Café', 132 tmp_dir = self.mkdtemp() 133 my_file = os.path.join(tmp_dir, 'f') 134 klass = Distribution 135 136 dist = klass(attrs={'author': u'Mister Café', 108 137 'name': 'my.package', 109 'maintainer': u'Café Junior', 110 'description': u'Café torréfié', 111 'long_description': u'Héhéhé'}) 112 138 'maintainer': u'Café Junior', 139 'description': u'Café torréfié', 140 'long_description': u'Héhéhé'}) 113 141 114 142 # let's make sure the file can be written 115 143 # with Unicode fields. they are encoded with 116 144 # PKG_INFO_ENCODING 117 try: 118 dist.metadata.write_pkg_file(open(my_file, 'w')) 119 finally: 120 if os.path.exists(my_file): 121 os.remove(my_file) 145 dist.metadata.write_pkg_file(open(my_file, 'w')) 122 146 123 147 # regular ascii is of course always usable … … 128 152 'long_description': 'Hehehe'}) 129 153 130 try: 131 dist.metadata.write_pkg_file(open(my_file, 'w')) 132 finally: 133 if os.path.exists(my_file): 134 os.remove(my_file) 154 my_file2 = os.path.join(tmp_dir, 'f2') 155 dist.metadata.write_pkg_file(open(my_file2, 'w')) 135 156 136 157 def test_empty_options(self): 137 158 # an empty options dictionary should not stay in the 138 159 # list of attributes 139 klass = distutils.dist.Distribution140 160 141 161 # catching warnings 142 162 warns = [] 163 143 164 def _warn(msg): 144 165 warns.append(msg) 145 166 146 old_warn = warnings.warn167 self.addCleanup(setattr, warnings, 'warn', warnings.warn) 147 168 warnings.warn = _warn 169 dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx', 170 'version': 'xxx', 'url': 'xxxx', 171 'options': {}}) 172 173 self.assertEqual(len(warns), 0) 174 self.assertNotIn('options', dir(dist)) 175 176 def test_finalize_options(self): 177 attrs = {'keywords': 'one,two', 178 'platforms': 'one,two'} 179 180 dist = Distribution(attrs=attrs) 181 dist.finalize_options() 182 183 # finalize_option splits platforms and keywords 184 self.assertEqual(dist.metadata.platforms, ['one', 'two']) 185 self.assertEqual(dist.metadata.keywords, ['one', 'two']) 186 187 def test_get_command_packages(self): 188 dist = Distribution() 189 self.assertEqual(dist.command_packages, None) 190 cmds = dist.get_command_packages() 191 self.assertEqual(cmds, ['distutils.command']) 192 self.assertEqual(dist.command_packages, 193 ['distutils.command']) 194 195 dist.command_packages = 'one,two' 196 cmds = dist.get_command_packages() 197 self.assertEqual(cmds, ['distutils.command', 'one', 'two']) 198 199 def test_announce(self): 200 # make sure the level is known 201 dist = Distribution() 202 args = ('ok',) 203 kwargs = {'level': 'ok2'} 204 self.assertRaises(ValueError, dist.announce, args, kwargs) 205 206 def test_find_config_files_disable(self): 207 # Ticket #1180: Allow user to disable their home config file. 208 temp_home = self.mkdtemp() 209 if os.name == 'posix': 210 user_filename = os.path.join(temp_home, ".pydistutils.cfg") 211 else: 212 user_filename = os.path.join(temp_home, "pydistutils.cfg") 213 214 with open(user_filename, 'w') as f: 215 f.write('[distutils]\n') 216 217 def _expander(path): 218 return temp_home 219 220 old_expander = os.path.expanduser 221 os.path.expanduser = _expander 148 222 try: 149 dist = klass(attrs={'author': 'xxx', 150 'name': 'xxx', 151 'version': 'xxx', 152 'url': 'xxxx', 153 'options': {}}) 223 d = distutils.dist.Distribution() 224 all_files = d.find_config_files() 225 226 d = distutils.dist.Distribution(attrs={'script_args': 227 ['--no-user-cfg']}) 228 files = d.find_config_files() 154 229 finally: 155 warnings.warn = old_warn 156 157 self.assertEquals(len(warns), 0) 158 159 class MetadataTestCase(unittest.TestCase): 160 161 def test_simple_metadata(self): 162 attrs = {"name": "package", 163 "version": "1.0"} 164 dist = distutils.dist.Distribution(attrs) 165 meta = self.format_metadata(dist) 166 self.assert_("Metadata-Version: 1.0" in meta) 167 self.assert_("provides:" not in meta.lower()) 168 self.assert_("requires:" not in meta.lower()) 169 self.assert_("obsoletes:" not in meta.lower()) 170 171 def test_provides(self): 172 attrs = {"name": "package", 173 "version": "1.0", 174 "provides": ["package", "package.sub"]} 175 dist = distutils.dist.Distribution(attrs) 176 self.assertEqual(dist.metadata.get_provides(), 177 ["package", "package.sub"]) 178 self.assertEqual(dist.get_provides(), 179 ["package", "package.sub"]) 180 meta = self.format_metadata(dist) 181 self.assert_("Metadata-Version: 1.1" in meta) 182 self.assert_("requires:" not in meta.lower()) 183 self.assert_("obsoletes:" not in meta.lower()) 184 185 def test_provides_illegal(self): 186 self.assertRaises(ValueError, 187 distutils.dist.Distribution, 188 {"name": "package", 189 "version": "1.0", 190 "provides": ["my.pkg (splat)"]}) 191 192 def test_requires(self): 193 attrs = {"name": "package", 194 "version": "1.0", 195 "requires": ["other", "another (==1.0)"]} 196 dist = distutils.dist.Distribution(attrs) 197 self.assertEqual(dist.metadata.get_requires(), 198 ["other", "another (==1.0)"]) 199 self.assertEqual(dist.get_requires(), 200 ["other", "another (==1.0)"]) 201 meta = self.format_metadata(dist) 202 self.assert_("Metadata-Version: 1.1" in meta) 203 self.assert_("provides:" not in meta.lower()) 204 self.assert_("Requires: other" in meta) 205 self.assert_("Requires: another (==1.0)" in meta) 206 self.assert_("obsoletes:" not in meta.lower()) 207 208 def test_requires_illegal(self): 209 self.assertRaises(ValueError, 210 distutils.dist.Distribution, 211 {"name": "package", 212 "version": "1.0", 213 "requires": ["my.pkg (splat)"]}) 214 215 def test_obsoletes(self): 216 attrs = {"name": "package", 217 "version": "1.0", 218 "obsoletes": ["other", "another (<1.0)"]} 219 dist = distutils.dist.Distribution(attrs) 220 self.assertEqual(dist.metadata.get_obsoletes(), 221 ["other", "another (<1.0)"]) 222 self.assertEqual(dist.get_obsoletes(), 223 ["other", "another (<1.0)"]) 224 meta = self.format_metadata(dist) 225 self.assert_("Metadata-Version: 1.1" in meta) 226 self.assert_("provides:" not in meta.lower()) 227 self.assert_("requires:" not in meta.lower()) 228 self.assert_("Obsoletes: other" in meta) 229 self.assert_("Obsoletes: another (<1.0)" in meta) 230 231 def test_obsoletes_illegal(self): 232 self.assertRaises(ValueError, 233 distutils.dist.Distribution, 234 {"name": "package", 235 "version": "1.0", 236 "obsoletes": ["my.pkg (splat)"]}) 237 238 def format_metadata(self, dist): 239 sio = StringIO.StringIO() 240 dist.metadata.write_pkg_file(sio) 241 return sio.getvalue() 242 243 def test_custom_pydistutils(self): 244 # fixes #2166 245 # make sure pydistutils.cfg is found 246 old = {} 247 for env in ('HOME', 'HOMEPATH', 'HOMEDRIVE'): 248 value = os.environ.get(env) 249 old[env] = value 250 if value is not None: 251 del os.environ[env] 252 253 if os.name == 'posix': 254 user_filename = ".pydistutils.cfg" 255 else: 256 user_filename = "pydistutils.cfg" 257 258 curdir = os.path.dirname(__file__) 259 user_filename = os.path.join(curdir, user_filename) 260 f = open(user_filename, 'w') 261 f.write('.') 262 f.close() 263 264 try: 265 dist = distutils.dist.Distribution() 266 267 # linux-style 268 if sys.platform in ('linux', 'darwin'): 269 os.environ['HOME'] = curdir 270 files = dist.find_config_files() 271 self.assert_(user_filename in files) 272 273 # win32-style 274 if sys.platform == 'win32': 275 # home drive should be found 276 os.environ['HOME'] = curdir 277 files = dist.find_config_files() 278 self.assert_(user_filename in files, 279 '%r not found in %r' % (user_filename, files)) 280 finally: 281 for key, value in old.items(): 282 if value is None: 283 continue 284 os.environ[key] = value 285 os.remove(user_filename) 230 os.path.expanduser = old_expander 231 232 # make sure --no-user-cfg disables the user cfg file 233 self.assertEqual(len(all_files)-1, len(files)) 234 235 236 class MetadataTestCase(support.TempdirManager, support.EnvironGuard, 237 unittest.TestCase): 238 239 def setUp(self): 240 super(MetadataTestCase, self).setUp() 241 self.argv = sys.argv, sys.argv[:] 242 243 def tearDown(self): 244 sys.argv = self.argv[0] 245 sys.argv[:] = self.argv[1] 246 super(MetadataTestCase, self).tearDown() 247 248 def test_classifier(self): 249 attrs = {'name': 'Boa', 'version': '3.0', 250 'classifiers': ['Programming Language :: Python :: 3']} 251 dist = Distribution(attrs) 252 meta = self.format_metadata(dist) 253 self.assertIn('Metadata-Version: 1.1', meta) 254 255 def test_download_url(self): 256 attrs = {'name': 'Boa', 'version': '3.0', 257 'download_url': 'http://example.org/boa'} 258 dist = Distribution(attrs) 259 meta = self.format_metadata(dist) 260 self.assertIn('Metadata-Version: 1.1', meta) 286 261 287 262 def test_long_description(self): … … 295 270 "long_description": long_desc} 296 271 297 dist = distutils.dist.Distribution(attrs)272 dist = Distribution(attrs) 298 273 meta = self.format_metadata(dist) 299 274 meta = meta.replace('\n' + 8 * ' ', '\n') 300 self.assertTrue(long_desc in meta) 275 self.assertIn(long_desc, meta) 276 277 def test_simple_metadata(self): 278 attrs = {"name": "package", 279 "version": "1.0"} 280 dist = Distribution(attrs) 281 meta = self.format_metadata(dist) 282 self.assertIn("Metadata-Version: 1.0", meta) 283 self.assertNotIn("provides:", meta.lower()) 284 self.assertNotIn("requires:", meta.lower()) 285 self.assertNotIn("obsoletes:", meta.lower()) 286 287 def test_provides(self): 288 attrs = {"name": "package", 289 "version": "1.0", 290 "provides": ["package", "package.sub"]} 291 dist = Distribution(attrs) 292 self.assertEqual(dist.metadata.get_provides(), 293 ["package", "package.sub"]) 294 self.assertEqual(dist.get_provides(), 295 ["package", "package.sub"]) 296 meta = self.format_metadata(dist) 297 self.assertIn("Metadata-Version: 1.1", meta) 298 self.assertNotIn("requires:", meta.lower()) 299 self.assertNotIn("obsoletes:", meta.lower()) 300 301 def test_provides_illegal(self): 302 self.assertRaises(ValueError, Distribution, 303 {"name": "package", 304 "version": "1.0", 305 "provides": ["my.pkg (splat)"]}) 306 307 def test_requires(self): 308 attrs = {"name": "package", 309 "version": "1.0", 310 "requires": ["other", "another (==1.0)"]} 311 dist = Distribution(attrs) 312 self.assertEqual(dist.metadata.get_requires(), 313 ["other", "another (==1.0)"]) 314 self.assertEqual(dist.get_requires(), 315 ["other", "another (==1.0)"]) 316 meta = self.format_metadata(dist) 317 self.assertIn("Metadata-Version: 1.1", meta) 318 self.assertNotIn("provides:", meta.lower()) 319 self.assertIn("Requires: other", meta) 320 self.assertIn("Requires: another (==1.0)", meta) 321 self.assertNotIn("obsoletes:", meta.lower()) 322 323 def test_requires_illegal(self): 324 self.assertRaises(ValueError, Distribution, 325 {"name": "package", 326 "version": "1.0", 327 "requires": ["my.pkg (splat)"]}) 328 329 def test_obsoletes(self): 330 attrs = {"name": "package", 331 "version": "1.0", 332 "obsoletes": ["other", "another (<1.0)"]} 333 dist = Distribution(attrs) 334 self.assertEqual(dist.metadata.get_obsoletes(), 335 ["other", "another (<1.0)"]) 336 self.assertEqual(dist.get_obsoletes(), 337 ["other", "another (<1.0)"]) 338 meta = self.format_metadata(dist) 339 self.assertIn("Metadata-Version: 1.1", meta) 340 self.assertNotIn("provides:", meta.lower()) 341 self.assertNotIn("requires:", meta.lower()) 342 self.assertIn("Obsoletes: other", meta) 343 self.assertIn("Obsoletes: another (<1.0)", meta) 344 345 def test_obsoletes_illegal(self): 346 self.assertRaises(ValueError, Distribution, 347 {"name": "package", 348 "version": "1.0", 349 "obsoletes": ["my.pkg (splat)"]}) 350 351 def format_metadata(self, dist): 352 sio = StringIO.StringIO() 353 dist.metadata.write_pkg_file(sio) 354 return sio.getvalue() 355 356 def test_custom_pydistutils(self): 357 # fixes #2166 358 # make sure pydistutils.cfg is found 359 if os.name == 'posix': 360 user_filename = ".pydistutils.cfg" 361 else: 362 user_filename = "pydistutils.cfg" 363 364 temp_dir = self.mkdtemp() 365 user_filename = os.path.join(temp_dir, user_filename) 366 f = open(user_filename, 'w') 367 try: 368 f.write('.') 369 finally: 370 f.close() 371 372 try: 373 dist = Distribution() 374 375 # linux-style 376 if sys.platform in ('linux', 'darwin'): 377 os.environ['HOME'] = temp_dir 378 files = dist.find_config_files() 379 self.assertIn(user_filename, files) 380 381 # win32-style 382 if sys.platform == 'win32': 383 # home drive should be found 384 os.environ['HOME'] = temp_dir 385 files = dist.find_config_files() 386 self.assertIn(user_filename, files, 387 '%r not found in %r' % (user_filename, files)) 388 finally: 389 os.remove(user_filename) 390 391 def test_fix_help_options(self): 392 help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] 393 fancy_options = fix_help_options(help_tuples) 394 self.assertEqual(fancy_options[0], ('a', 'b', 'c')) 395 self.assertEqual(fancy_options[1], (1, 2, 3)) 396 397 def test_show_help(self): 398 # smoke test, just makes sure some help is displayed 399 dist = Distribution() 400 sys.argv = [] 401 dist.help = 1 402 dist.script_name = 'setup.py' 403 with captured_stdout() as s: 404 dist.parse_command_line() 405 406 output = [line for line in s.getvalue().split('\n') 407 if line.strip() != ''] 408 self.assertTrue(output) 409 410 def test_read_metadata(self): 411 attrs = {"name": "package", 412 "version": "1.0", 413 "long_description": "desc", 414 "description": "xxx", 415 "download_url": "http://example.com", 416 "keywords": ['one', 'two'], 417 "requires": ['foo']} 418 419 dist = Distribution(attrs) 420 metadata = dist.metadata 421 422 # write it then reloads it 423 PKG_INFO = StringIO.StringIO() 424 metadata.write_pkg_file(PKG_INFO) 425 PKG_INFO.seek(0) 426 metadata.read_pkg_file(PKG_INFO) 427 428 self.assertEqual(metadata.name, "package") 429 self.assertEqual(metadata.version, "1.0") 430 self.assertEqual(metadata.description, "xxx") 431 self.assertEqual(metadata.download_url, 'http://example.com') 432 self.assertEqual(metadata.keywords, ['one', 'two']) 433 self.assertEqual(metadata.platforms, ['UNKNOWN']) 434 self.assertEqual(metadata.obsoletes, None) 435 self.assertEqual(metadata.requires, ['foo']) 436 301 437 302 438 def test_suite(): … … 307 443 308 444 if __name__ == "__main__": 309 unittest.main(defaultTest="test_suite")445 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_filelist.py
r2 r391 1 1 """Tests for distutils.filelist.""" 2 import os 3 import re 2 4 import unittest 3 from distutils.filelist import glob_to_re 4 5 class FileListTestCase(unittest.TestCase): 5 from distutils import debug 6 from distutils.log import WARN 7 from distutils.errors import DistutilsTemplateError 8 from distutils.filelist import glob_to_re, translate_pattern, FileList 9 10 from test.test_support import captured_stdout, run_unittest 11 from distutils.tests import support 12 13 MANIFEST_IN = """\ 14 include ok 15 include xo 16 exclude xo 17 include foo.tmp 18 include buildout.cfg 19 global-include *.x 20 global-include *.txt 21 global-exclude *.tmp 22 recursive-include f *.oo 23 recursive-exclude global *.x 24 graft dir 25 prune dir3 26 """ 27 28 29 def make_local_path(s): 30 """Converts '/' in a string to os.sep""" 31 return s.replace('/', os.sep) 32 33 34 class FileListTestCase(support.LoggingSilencer, 35 unittest.TestCase): 36 37 def assertNoWarnings(self): 38 self.assertEqual(self.get_logs(WARN), []) 39 self.clear_logs() 40 41 def assertWarnings(self): 42 self.assertGreater(len(self.get_logs(WARN)), 0) 43 self.clear_logs() 6 44 7 45 def test_glob_to_re(self): 8 # simple cases 9 self.assertEquals(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)') 10 self.assertEquals(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)') 11 self.assertEquals(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)') 12 13 # special cases 14 self.assertEquals(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)') 15 self.assertEquals(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)') 16 self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)') 17 self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)') 46 sep = os.sep 47 if os.sep == '\\': 48 sep = re.escape(os.sep) 49 50 for glob, regex in ( 51 # simple cases 52 ('foo*', r'foo[^%(sep)s]*\Z(?ms)'), 53 ('foo?', r'foo[^%(sep)s]\Z(?ms)'), 54 ('foo??', r'foo[^%(sep)s][^%(sep)s]\Z(?ms)'), 55 # special cases 56 (r'foo\\*', r'foo\\\\[^%(sep)s]*\Z(?ms)'), 57 (r'foo\\\*', r'foo\\\\\\[^%(sep)s]*\Z(?ms)'), 58 ('foo????', r'foo[^%(sep)s][^%(sep)s][^%(sep)s][^%(sep)s]\Z(?ms)'), 59 (r'foo\\??', r'foo\\\\[^%(sep)s][^%(sep)s]\Z(?ms)')): 60 regex = regex % {'sep': sep} 61 self.assertEqual(glob_to_re(glob), regex) 62 63 def test_process_template_line(self): 64 # testing all MANIFEST.in template patterns 65 file_list = FileList() 66 l = make_local_path 67 68 # simulated file list 69 file_list.allfiles = ['foo.tmp', 'ok', 'xo', 'four.txt', 70 'buildout.cfg', 71 # filelist does not filter out VCS directories, 72 # it's sdist that does 73 l('.hg/last-message.txt'), 74 l('global/one.txt'), 75 l('global/two.txt'), 76 l('global/files.x'), 77 l('global/here.tmp'), 78 l('f/o/f.oo'), 79 l('dir/graft-one'), 80 l('dir/dir2/graft2'), 81 l('dir3/ok'), 82 l('dir3/sub/ok.txt'), 83 ] 84 85 for line in MANIFEST_IN.split('\n'): 86 if line.strip() == '': 87 continue 88 file_list.process_template_line(line) 89 90 wanted = ['ok', 91 'buildout.cfg', 92 'four.txt', 93 l('.hg/last-message.txt'), 94 l('global/one.txt'), 95 l('global/two.txt'), 96 l('f/o/f.oo'), 97 l('dir/graft-one'), 98 l('dir/dir2/graft2'), 99 ] 100 101 self.assertEqual(file_list.files, wanted) 102 103 def test_debug_print(self): 104 file_list = FileList() 105 with captured_stdout() as stdout: 106 file_list.debug_print('xxx') 107 self.assertEqual(stdout.getvalue(), '') 108 109 debug.DEBUG = True 110 try: 111 with captured_stdout() as stdout: 112 file_list.debug_print('xxx') 113 self.assertEqual(stdout.getvalue(), 'xxx\n') 114 finally: 115 debug.DEBUG = False 116 117 def test_set_allfiles(self): 118 file_list = FileList() 119 files = ['a', 'b', 'c'] 120 file_list.set_allfiles(files) 121 self.assertEqual(file_list.allfiles, files) 122 123 def test_remove_duplicates(self): 124 file_list = FileList() 125 file_list.files = ['a', 'b', 'a', 'g', 'c', 'g'] 126 # files must be sorted beforehand (sdist does it) 127 file_list.sort() 128 file_list.remove_duplicates() 129 self.assertEqual(file_list.files, ['a', 'b', 'c', 'g']) 130 131 def test_translate_pattern(self): 132 # not regex 133 self.assertTrue(hasattr( 134 translate_pattern('a', anchor=True, is_regex=False), 135 'search')) 136 137 # is a regex 138 regex = re.compile('a') 139 self.assertEqual( 140 translate_pattern(regex, anchor=True, is_regex=True), 141 regex) 142 143 # plain string flagged as regex 144 self.assertTrue(hasattr( 145 translate_pattern('a', anchor=True, is_regex=True), 146 'search')) 147 148 # glob support 149 self.assertTrue(translate_pattern( 150 '*.py', anchor=True, is_regex=False).search('filelist.py')) 151 152 def test_exclude_pattern(self): 153 # return False if no match 154 file_list = FileList() 155 self.assertFalse(file_list.exclude_pattern('*.py')) 156 157 # return True if files match 158 file_list = FileList() 159 file_list.files = ['a.py', 'b.py'] 160 self.assertTrue(file_list.exclude_pattern('*.py')) 161 162 # test excludes 163 file_list = FileList() 164 file_list.files = ['a.py', 'a.txt'] 165 file_list.exclude_pattern('*.py') 166 self.assertEqual(file_list.files, ['a.txt']) 167 168 def test_include_pattern(self): 169 # return False if no match 170 file_list = FileList() 171 file_list.set_allfiles([]) 172 self.assertFalse(file_list.include_pattern('*.py')) 173 174 # return True if files match 175 file_list = FileList() 176 file_list.set_allfiles(['a.py', 'b.txt']) 177 self.assertTrue(file_list.include_pattern('*.py')) 178 179 # test * matches all files 180 file_list = FileList() 181 self.assertIsNone(file_list.allfiles) 182 file_list.set_allfiles(['a.py', 'b.txt']) 183 file_list.include_pattern('*') 184 self.assertEqual(file_list.allfiles, ['a.py', 'b.txt']) 185 186 def test_process_template(self): 187 l = make_local_path 188 # invalid lines 189 file_list = FileList() 190 for action in ('include', 'exclude', 'global-include', 191 'global-exclude', 'recursive-include', 192 'recursive-exclude', 'graft', 'prune', 'blarg'): 193 self.assertRaises(DistutilsTemplateError, 194 file_list.process_template_line, action) 195 196 # include 197 file_list = FileList() 198 file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')]) 199 200 file_list.process_template_line('include *.py') 201 self.assertEqual(file_list.files, ['a.py']) 202 self.assertNoWarnings() 203 204 file_list.process_template_line('include *.rb') 205 self.assertEqual(file_list.files, ['a.py']) 206 self.assertWarnings() 207 208 # exclude 209 file_list = FileList() 210 file_list.files = ['a.py', 'b.txt', l('d/c.py')] 211 212 file_list.process_template_line('exclude *.py') 213 self.assertEqual(file_list.files, ['b.txt', l('d/c.py')]) 214 self.assertNoWarnings() 215 216 file_list.process_template_line('exclude *.rb') 217 self.assertEqual(file_list.files, ['b.txt', l('d/c.py')]) 218 self.assertWarnings() 219 220 # global-include 221 file_list = FileList() 222 file_list.set_allfiles(['a.py', 'b.txt', l('d/c.py')]) 223 224 file_list.process_template_line('global-include *.py') 225 self.assertEqual(file_list.files, ['a.py', l('d/c.py')]) 226 self.assertNoWarnings() 227 228 file_list.process_template_line('global-include *.rb') 229 self.assertEqual(file_list.files, ['a.py', l('d/c.py')]) 230 self.assertWarnings() 231 232 # global-exclude 233 file_list = FileList() 234 file_list.files = ['a.py', 'b.txt', l('d/c.py')] 235 236 file_list.process_template_line('global-exclude *.py') 237 self.assertEqual(file_list.files, ['b.txt']) 238 self.assertNoWarnings() 239 240 file_list.process_template_line('global-exclude *.rb') 241 self.assertEqual(file_list.files, ['b.txt']) 242 self.assertWarnings() 243 244 # recursive-include 245 file_list = FileList() 246 file_list.set_allfiles(['a.py', l('d/b.py'), l('d/c.txt'), 247 l('d/d/e.py')]) 248 249 file_list.process_template_line('recursive-include d *.py') 250 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 251 self.assertNoWarnings() 252 253 file_list.process_template_line('recursive-include e *.py') 254 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 255 self.assertWarnings() 256 257 # recursive-exclude 258 file_list = FileList() 259 file_list.files = ['a.py', l('d/b.py'), l('d/c.txt'), l('d/d/e.py')] 260 261 file_list.process_template_line('recursive-exclude d *.py') 262 self.assertEqual(file_list.files, ['a.py', l('d/c.txt')]) 263 self.assertNoWarnings() 264 265 file_list.process_template_line('recursive-exclude e *.py') 266 self.assertEqual(file_list.files, ['a.py', l('d/c.txt')]) 267 self.assertWarnings() 268 269 # graft 270 file_list = FileList() 271 file_list.set_allfiles(['a.py', l('d/b.py'), l('d/d/e.py'), 272 l('f/f.py')]) 273 274 file_list.process_template_line('graft d') 275 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 276 self.assertNoWarnings() 277 278 file_list.process_template_line('graft e') 279 self.assertEqual(file_list.files, [l('d/b.py'), l('d/d/e.py')]) 280 self.assertWarnings() 281 282 # prune 283 file_list = FileList() 284 file_list.files = ['a.py', l('d/b.py'), l('d/d/e.py'), l('f/f.py')] 285 286 file_list.process_template_line('prune d') 287 self.assertEqual(file_list.files, ['a.py', l('f/f.py')]) 288 self.assertNoWarnings() 289 290 file_list.process_template_line('prune e') 291 self.assertEqual(file_list.files, ['a.py', l('f/f.py')]) 292 self.assertWarnings() 293 18 294 19 295 def test_suite(): … … 21 297 22 298 if __name__ == "__main__": 23 unittest.main(defaultTest="test_suite")299 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_install.py
r2 r391 2 2 3 3 import os 4 import sys 4 5 import unittest 5 6 import site 7 8 from test.test_support import captured_stdout, run_unittest 9 10 from distutils import sysconfig 6 11 from distutils.command.install import install 12 from distutils.command import install as install_module 13 from distutils.command.build_ext import build_ext 14 from distutils.command.install import INSTALL_SCHEMES 7 15 from distutils.core import Distribution 16 from distutils.errors import DistutilsOptionError 17 from distutils.extension import Extension 8 18 9 19 from distutils.tests import support 10 20 11 21 12 class InstallTestCase(support.TempdirManager, unittest.TestCase): 22 def _make_ext_name(modname): 23 if os.name == 'nt' and sys.executable.endswith('_d.exe'): 24 modname += '_d' 25 return modname + sysconfig.get_config_var('SO') 26 27 28 class InstallTestCase(support.TempdirManager, 29 support.LoggingSilencer, 30 unittest.TestCase): 13 31 14 32 def test_home_installation_scheme(self): … … 48 66 check_path(cmd.install_data, destination) 49 67 68 def test_user_site(self): 69 # site.USER_SITE was introduced in 2.6 70 if sys.version < '2.6': 71 return 72 73 # preparing the environment for the test 74 self.old_user_base = site.USER_BASE 75 self.old_user_site = site.USER_SITE 76 self.tmpdir = self.mkdtemp() 77 self.user_base = os.path.join(self.tmpdir, 'B') 78 self.user_site = os.path.join(self.tmpdir, 'S') 79 site.USER_BASE = self.user_base 80 site.USER_SITE = self.user_site 81 install_module.USER_BASE = self.user_base 82 install_module.USER_SITE = self.user_site 83 84 def _expanduser(path): 85 return self.tmpdir 86 self.old_expand = os.path.expanduser 87 os.path.expanduser = _expanduser 88 89 def cleanup(): 90 site.USER_BASE = self.old_user_base 91 site.USER_SITE = self.old_user_site 92 install_module.USER_BASE = self.old_user_base 93 install_module.USER_SITE = self.old_user_site 94 os.path.expanduser = self.old_expand 95 96 self.addCleanup(cleanup) 97 98 for key in ('nt_user', 'unix_user', 'os2_home'): 99 self.assertIn(key, INSTALL_SCHEMES) 100 101 dist = Distribution({'name': 'xx'}) 102 cmd = install(dist) 103 104 # making sure the user option is there 105 options = [name for name, short, lable in 106 cmd.user_options] 107 self.assertIn('user', options) 108 109 # setting a value 110 cmd.user = 1 111 112 # user base and site shouldn't be created yet 113 self.assertFalse(os.path.exists(self.user_base)) 114 self.assertFalse(os.path.exists(self.user_site)) 115 116 # let's run finalize 117 cmd.ensure_finalized() 118 119 # now they should 120 self.assertTrue(os.path.exists(self.user_base)) 121 self.assertTrue(os.path.exists(self.user_site)) 122 123 self.assertIn('userbase', cmd.config_vars) 124 self.assertIn('usersite', cmd.config_vars) 125 126 def test_handle_extra_path(self): 127 dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'}) 128 cmd = install(dist) 129 130 # two elements 131 cmd.handle_extra_path() 132 self.assertEqual(cmd.extra_path, ['path', 'dirs']) 133 self.assertEqual(cmd.extra_dirs, 'dirs') 134 self.assertEqual(cmd.path_file, 'path') 135 136 # one element 137 cmd.extra_path = ['path'] 138 cmd.handle_extra_path() 139 self.assertEqual(cmd.extra_path, ['path']) 140 self.assertEqual(cmd.extra_dirs, 'path') 141 self.assertEqual(cmd.path_file, 'path') 142 143 # none 144 dist.extra_path = cmd.extra_path = None 145 cmd.handle_extra_path() 146 self.assertEqual(cmd.extra_path, None) 147 self.assertEqual(cmd.extra_dirs, '') 148 self.assertEqual(cmd.path_file, None) 149 150 # three elements (no way !) 151 cmd.extra_path = 'path,dirs,again' 152 self.assertRaises(DistutilsOptionError, cmd.handle_extra_path) 153 154 def test_finalize_options(self): 155 dist = Distribution({'name': 'xx'}) 156 cmd = install(dist) 157 158 # must supply either prefix/exec-prefix/home or 159 # install-base/install-platbase -- not both 160 cmd.prefix = 'prefix' 161 cmd.install_base = 'base' 162 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 163 164 # must supply either home or prefix/exec-prefix -- not both 165 cmd.install_base = None 166 cmd.home = 'home' 167 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 168 169 # can't combine user with prefix/exec_prefix/home or 170 # install_(plat)base 171 cmd.prefix = None 172 cmd.user = 'user' 173 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 174 175 def test_record(self): 176 install_dir = self.mkdtemp() 177 project_dir, dist = self.create_dist(py_modules=['hello'], 178 scripts=['sayhi']) 179 os.chdir(project_dir) 180 self.write_file('hello.py', "def main(): print 'o hai'") 181 self.write_file('sayhi', 'from hello import main; main()') 182 183 cmd = install(dist) 184 dist.command_obj['install'] = cmd 185 cmd.root = install_dir 186 cmd.record = os.path.join(project_dir, 'filelist') 187 cmd.ensure_finalized() 188 cmd.run() 189 190 f = open(cmd.record) 191 try: 192 content = f.read() 193 finally: 194 f.close() 195 196 found = [os.path.basename(line) for line in content.splitlines()] 197 expected = ['hello.py', 'hello.pyc', 'sayhi', 198 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] 199 self.assertEqual(found, expected) 200 201 def test_record_extensions(self): 202 install_dir = self.mkdtemp() 203 project_dir, dist = self.create_dist(ext_modules=[ 204 Extension('xx', ['xxmodule.c'])]) 205 os.chdir(project_dir) 206 support.copy_xxmodule_c(project_dir) 207 208 buildextcmd = build_ext(dist) 209 support.fixup_build_ext(buildextcmd) 210 buildextcmd.ensure_finalized() 211 212 cmd = install(dist) 213 dist.command_obj['install'] = cmd 214 dist.command_obj['build_ext'] = buildextcmd 215 cmd.root = install_dir 216 cmd.record = os.path.join(project_dir, 'filelist') 217 cmd.ensure_finalized() 218 cmd.run() 219 220 f = open(cmd.record) 221 try: 222 content = f.read() 223 finally: 224 f.close() 225 226 found = [os.path.basename(line) for line in content.splitlines()] 227 expected = [_make_ext_name('xx'), 228 'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]] 229 self.assertEqual(found, expected) 230 231 def test_debug_mode(self): 232 # this covers the code called when DEBUG is set 233 old_logs_len = len(self.logs) 234 install_module.DEBUG = True 235 try: 236 with captured_stdout(): 237 self.test_record() 238 finally: 239 install_module.DEBUG = False 240 self.assertTrue(len(self.logs) > old_logs_len) 241 50 242 51 243 def test_suite(): … … 53 245 54 246 if __name__ == "__main__": 55 unittest.main(defaultTest="test_suite")247 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_install_lib.py
r2 r391 1 1 """Tests for distutils.command.install_data.""" 2 import os 2 3 import sys 3 import os4 4 import unittest 5 5 … … 8 8 from distutils.tests import support 9 9 from distutils.errors import DistutilsOptionError 10 from test.test_support import run_unittest 10 11 11 12 class InstallLibTestCase(support.TempdirManager, 12 13 support.LoggingSilencer, 14 support.EnvironGuard, 13 15 unittest.TestCase): 16 17 def test_finalize_options(self): 18 pkg_dir, dist = self.create_dist() 19 cmd = install_lib(dist) 20 21 cmd.finalize_options() 22 self.assertEqual(cmd.compile, 1) 23 self.assertEqual(cmd.optimize, 0) 24 25 # optimize must be 0, 1, or 2 26 cmd.optimize = 'foo' 27 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 28 cmd.optimize = '4' 29 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 30 31 cmd.optimize = '2' 32 cmd.finalize_options() 33 self.assertEqual(cmd.optimize, 2) 34 35 def _setup_byte_compile(self): 36 pkg_dir, dist = self.create_dist() 37 cmd = install_lib(dist) 38 cmd.compile = cmd.optimize = 1 39 40 f = os.path.join(pkg_dir, 'foo.py') 41 self.write_file(f, '# python file') 42 cmd.byte_compile([f]) 43 return pkg_dir 44 45 @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile not enabled') 46 def test_byte_compile(self): 47 pkg_dir = self._setup_byte_compile() 48 if sys.flags.optimize < 1: 49 self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyc'))) 50 else: 51 self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'foo.pyo'))) 52 53 def test_get_outputs(self): 54 pkg_dir, dist = self.create_dist() 55 cmd = install_lib(dist) 56 57 # setting up a dist environment 58 cmd.compile = cmd.optimize = 1 59 cmd.install_dir = pkg_dir 60 f = os.path.join(pkg_dir, 'foo.py') 61 self.write_file(f, '# python file') 62 cmd.distribution.py_modules = [pkg_dir] 63 cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] 64 cmd.distribution.packages = [pkg_dir] 65 cmd.distribution.script_name = 'setup.py' 66 67 # get_output should return 4 elements 68 self.assertTrue(len(cmd.get_outputs()) >= 2) 69 70 def test_get_inputs(self): 71 pkg_dir, dist = self.create_dist() 72 cmd = install_lib(dist) 73 74 # setting up a dist environment 75 cmd.compile = cmd.optimize = 1 76 cmd.install_dir = pkg_dir 77 f = os.path.join(pkg_dir, 'foo.py') 78 self.write_file(f, '# python file') 79 cmd.distribution.py_modules = [pkg_dir] 80 cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] 81 cmd.distribution.packages = [pkg_dir] 82 cmd.distribution.script_name = 'setup.py' 83 84 # get_input should return 2 elements 85 self.assertEqual(len(cmd.get_inputs()), 2) 14 86 15 87 def test_dont_write_bytecode(self): … … 33 105 34 106 if __name__ == "__main__": 35 unittest.main(defaultTest="test_suite")107 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_install_scripts.py
r2 r391 8 8 9 9 from distutils.tests import support 10 from test.test_support import run_unittest 10 11 11 12 … … 24 25 ) 25 26 cmd = install_scripts(dist) 26 self.assert _(not cmd.force)27 self.assert _(not cmd.skip_build)28 self.assert _(cmd.build_dir is None)29 self.assert _(cmd.install_dir is None)27 self.assertTrue(not cmd.force) 28 self.assertTrue(not cmd.skip_build) 29 self.assertTrue(cmd.build_dir is None) 30 self.assertTrue(cmd.install_dir is None) 30 31 31 32 cmd.finalize_options() 32 33 33 self.assert _(cmd.force)34 self.assert _(cmd.skip_build)34 self.assertTrue(cmd.force) 35 self.assertTrue(cmd.skip_build) 35 36 self.assertEqual(cmd.build_dir, "/foo/bar") 36 37 self.assertEqual(cmd.install_dir, "/splat/funk") … … 43 44 expected.append(name) 44 45 f = open(os.path.join(source, name), "w") 45 f.write(text) 46 f.close() 46 try: 47 f.write(text) 48 finally: 49 f.close() 47 50 48 51 write_script("script1.py", ("#! /usr/bin/env python2.3\n" … … 70 73 installed = os.listdir(target) 71 74 for name in expected: 72 self.assert _(name in installed)75 self.assertTrue(name in installed) 73 76 74 77 … … 77 80 78 81 if __name__ == "__main__": 79 unittest.main(defaultTest="test_suite")82 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_msvc9compiler.py
r2 r391 2 2 import sys 3 3 import unittest 4 import os 4 5 5 6 from distutils.errors import DistutilsPlatformError 7 from distutils.tests import support 8 from test.test_support import run_unittest 6 9 7 class msvc9compilerTestCase(unittest.TestCase): 10 # A manifest with the only assembly reference being the msvcrt assembly, so 11 # should have the assembly completely stripped. Note that although the 12 # assembly has a <security> reference the assembly is removed - that is 13 # currently a "feature", not a bug :) 14 _MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\ 15 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 16 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 17 manifestVersion="1.0"> 18 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 19 <security> 20 <requestedPrivileges> 21 <requestedExecutionLevel level="asInvoker" uiAccess="false"> 22 </requestedExecutionLevel> 23 </requestedPrivileges> 24 </security> 25 </trustInfo> 26 <dependency> 27 <dependentAssembly> 28 <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" 29 version="9.0.21022.8" processorArchitecture="x86" 30 publicKeyToken="XXXX"> 31 </assemblyIdentity> 32 </dependentAssembly> 33 </dependency> 34 </assembly> 35 """ 36 37 # A manifest with references to assemblies other than msvcrt. When processed, 38 # this assembly should be returned with just the msvcrt part removed. 39 _MANIFEST_WITH_MULTIPLE_REFERENCES = """\ 40 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 41 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 42 manifestVersion="1.0"> 43 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 44 <security> 45 <requestedPrivileges> 46 <requestedExecutionLevel level="asInvoker" uiAccess="false"> 47 </requestedExecutionLevel> 48 </requestedPrivileges> 49 </security> 50 </trustInfo> 51 <dependency> 52 <dependentAssembly> 53 <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" 54 version="9.0.21022.8" processorArchitecture="x86" 55 publicKeyToken="XXXX"> 56 </assemblyIdentity> 57 </dependentAssembly> 58 </dependency> 59 <dependency> 60 <dependentAssembly> 61 <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" 62 version="9.0.21022.8" processorArchitecture="x86" 63 publicKeyToken="XXXX"></assemblyIdentity> 64 </dependentAssembly> 65 </dependency> 66 </assembly> 67 """ 68 69 _CLEANED_MANIFEST = """\ 70 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 71 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 72 manifestVersion="1.0"> 73 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 74 <security> 75 <requestedPrivileges> 76 <requestedExecutionLevel level="asInvoker" uiAccess="false"> 77 </requestedExecutionLevel> 78 </requestedPrivileges> 79 </security> 80 </trustInfo> 81 <dependency> 82 83 </dependency> 84 <dependency> 85 <dependentAssembly> 86 <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" 87 version="9.0.21022.8" processorArchitecture="x86" 88 publicKeyToken="XXXX"></assemblyIdentity> 89 </dependentAssembly> 90 </dependency> 91 </assembly>""" 92 93 if sys.platform=="win32": 94 from distutils.msvccompiler import get_build_version 95 if get_build_version()>=8.0: 96 SKIP_MESSAGE = None 97 else: 98 SKIP_MESSAGE = "These tests are only for MSVC8.0 or above" 99 else: 100 SKIP_MESSAGE = "These tests are only for win32" 101 102 @unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE) 103 class msvc9compilerTestCase(support.TempdirManager, 104 unittest.TestCase): 8 105 9 106 def test_no_compiler(self): 10 # makes sure query_vcvarsall throws107 # makes sure query_vcvarsall raises 11 108 # a DistutilsPlatformError if the compiler 12 109 # is not found 13 if sys.platform != 'win32':14 # this test is only for win3215 return16 from distutils.msvccompiler import get_build_version17 if get_build_version() < 8.0:18 # this test is only for MSVC8.0 or above19 return20 110 from distutils.msvc9compiler import query_vcvarsall 21 111 def _find_vcvarsall(version): … … 31 121 msvc9compiler.find_vcvarsall = old_find_vcvarsall 32 122 123 def test_reg_class(self): 124 from distutils.msvc9compiler import Reg 125 self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx') 126 127 # looking for values that should exist on all 128 # windows registeries versions. 129 path = r'Control Panel\Desktop' 130 v = Reg.get_value(path, u'dragfullwindows') 131 self.assertTrue(v in (u'0', u'1', u'2')) 132 133 import _winreg 134 HKCU = _winreg.HKEY_CURRENT_USER 135 keys = Reg.read_keys(HKCU, 'xxxx') 136 self.assertEqual(keys, None) 137 138 keys = Reg.read_keys(HKCU, r'Control Panel') 139 self.assertTrue('Desktop' in keys) 140 141 def test_remove_visual_c_ref(self): 142 from distutils.msvc9compiler import MSVCCompiler 143 tempdir = self.mkdtemp() 144 manifest = os.path.join(tempdir, 'manifest') 145 f = open(manifest, 'w') 146 try: 147 f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES) 148 finally: 149 f.close() 150 151 compiler = MSVCCompiler() 152 compiler._remove_visual_c_ref(manifest) 153 154 # see what we got 155 f = open(manifest) 156 try: 157 # removing trailing spaces 158 content = '\n'.join([line.rstrip() for line in f.readlines()]) 159 finally: 160 f.close() 161 162 # makes sure the manifest was properly cleaned 163 self.assertEqual(content, _CLEANED_MANIFEST) 164 165 def test_remove_entire_manifest(self): 166 from distutils.msvc9compiler import MSVCCompiler 167 tempdir = self.mkdtemp() 168 manifest = os.path.join(tempdir, 'manifest') 169 f = open(manifest, 'w') 170 try: 171 f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE) 172 finally: 173 f.close() 174 175 compiler = MSVCCompiler() 176 got = compiler._remove_visual_c_ref(manifest) 177 self.assertIs(got, None) 178 179 33 180 def test_suite(): 34 181 return unittest.makeSuite(msvc9compilerTestCase) 35 182 36 183 if __name__ == "__main__": 37 unittest.main(defaultTest="test_suite")184 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_register.py
r2 r391 1 # -*- encoding: utf8 -*- 1 2 """Tests for distutils.command.register.""" 2 import sys3 3 import os 4 4 import unittest 5 5 import getpass 6 import urllib2 7 import warnings 8 9 from test.test_support import check_warnings, run_unittest 10 11 from distutils.command import register as register_module 6 12 from distutils.command.register import register 7 from distutils.core import Distribution 8 9 from distutils.tests import support 10 from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase 13 from distutils.errors import DistutilsSetupError 14 15 from distutils.tests.test_config import PyPIRCCommandTestCase 16 17 try: 18 import docutils 19 except ImportError: 20 docutils = None 21 22 PYPIRC_NOPASSWORD = """\ 23 [distutils] 24 25 index-servers = 26 server1 27 28 [server1] 29 username:me 30 """ 31 32 WANTED_PYPIRC = """\ 33 [distutils] 34 index-servers = 35 pypi 36 37 [pypi] 38 username:tarek 39 password:password 40 """ 11 41 12 42 class RawInputs(object): … … 22 52 self.index += 1 23 53 24 WANTED_PYPIRC = """\ 25 [distutils] 26 index-servers = 27 pypi 28 29 [pypi] 30 username:tarek 31 password:xxx 32 """ 33 34 class registerTestCase(PyPIRCCommandTestCase): 54 class FakeOpener(object): 55 """Fakes a PyPI server""" 56 def __init__(self): 57 self.reqs = [] 58 59 def __call__(self, *args): 60 return self 61 62 def open(self, req): 63 self.reqs.append(req) 64 return self 65 66 def read(self): 67 return 'xxx' 68 69 class RegisterTestCase(PyPIRCCommandTestCase): 70 71 def setUp(self): 72 super(RegisterTestCase, self).setUp() 73 # patching the password prompt 74 self._old_getpass = getpass.getpass 75 def _getpass(prompt): 76 return 'password' 77 getpass.getpass = _getpass 78 self.old_opener = urllib2.build_opener 79 self.conn = urllib2.build_opener = FakeOpener() 80 81 def tearDown(self): 82 getpass.getpass = self._old_getpass 83 urllib2.build_opener = self.old_opener 84 super(RegisterTestCase, self).tearDown() 85 86 def _get_cmd(self, metadata=None): 87 if metadata is None: 88 metadata = {'url': 'xxx', 'author': 'xxx', 89 'author_email': 'xxx', 90 'name': 'xxx', 'version': 'xxx'} 91 pkg_info, dist = self.create_dist(**metadata) 92 return register(dist) 35 93 36 94 def test_create_pypirc(self): … … 38 96 # is created when requested. 39 97 40 # let's create a fake distribution 41 # and a register instance 42 dist = Distribution() 43 dist.metadata.url = 'xxx' 44 dist.metadata.author = 'xxx' 45 dist.metadata.author_email = 'xxx' 46 dist.metadata.name = 'xxx' 47 dist.metadata.version = 'xxx' 48 cmd = register(dist) 98 # let's create a register instance 99 cmd = self._get_cmd() 49 100 50 101 # we shouldn't have a .pypirc file yet 51 self.assert _(not os.path.exists(self.rc))102 self.assertTrue(not os.path.exists(self.rc)) 52 103 53 104 # patching raw_input and getpass.getpass … … 57 108 # use your existing login (choice 1.) 58 109 # Username : 'tarek' 59 # Password : ' xxx'110 # Password : 'password' 60 111 # Save your login (y/N)? : 'y' 61 112 inputs = RawInputs('1', 'tarek', 'y') 62 from distutils.command import register as register_module 63 register_module.raw_input = inputs.__call__ 64 def _getpass(prompt): 65 return 'xxx' 66 register_module.getpass.getpass = _getpass 67 class FakeServer(object): 68 def __init__(self): 69 self.calls = [] 70 71 def __call__(self, *args): 72 # we want to compare them, so let's store 73 # something comparable 74 els = args[0].items() 75 els.sort() 76 self.calls.append(tuple(els)) 77 return 200, 'OK' 78 79 cmd.post_to_server = pypi_server = FakeServer() 80 81 # let's run the command 82 cmd.run() 113 register_module.raw_input = inputs.__call__ 114 # let's run the command 115 try: 116 cmd.run() 117 finally: 118 del register_module.raw_input 83 119 84 120 # we should have a brand new .pypirc file 85 self.assert _(os.path.exists(self.rc))121 self.assertTrue(os.path.exists(self.rc)) 86 122 87 123 # with the content similar to WANTED_PYPIRC 88 content = open(self.rc).read() 89 self.assertEquals(content, WANTED_PYPIRC) 124 f = open(self.rc) 125 try: 126 content = f.read() 127 self.assertEqual(content, WANTED_PYPIRC) 128 finally: 129 f.close() 90 130 91 131 # now let's make sure the .pypirc file generated … … 96 136 register_module.raw_input = _no_way 97 137 138 cmd.show_response = 1 98 139 cmd.run() 99 140 100 141 # let's see what the server received : we should 101 142 # have 2 similar requests 102 self.assert_(len(pypi_server.calls), 2) 103 self.assert_(pypi_server.calls[0], pypi_server.calls[1]) 143 self.assertEqual(len(self.conn.reqs), 2) 144 req1 = dict(self.conn.reqs[0].headers) 145 req2 = dict(self.conn.reqs[1].headers) 146 self.assertEqual(req2['Content-length'], req1['Content-length']) 147 self.assertTrue('xxx' in self.conn.reqs[1].data) 148 149 def test_password_not_in_file(self): 150 151 self.write_file(self.rc, PYPIRC_NOPASSWORD) 152 cmd = self._get_cmd() 153 cmd._set_config() 154 cmd.finalize_options() 155 cmd.send_metadata() 156 157 # dist.password should be set 158 # therefore used afterwards by other commands 159 self.assertEqual(cmd.distribution.password, 'password') 160 161 def test_registering(self): 162 # this test runs choice 2 163 cmd = self._get_cmd() 164 inputs = RawInputs('2', 'tarek', 'tarek@ziade.org') 165 register_module.raw_input = inputs.__call__ 166 try: 167 # let's run the command 168 cmd.run() 169 finally: 170 del register_module.raw_input 171 172 # we should have send a request 173 self.assertEqual(len(self.conn.reqs), 1) 174 req = self.conn.reqs[0] 175 headers = dict(req.headers) 176 self.assertEqual(headers['Content-length'], '608') 177 self.assertTrue('tarek' in req.data) 178 179 def test_password_reset(self): 180 # this test runs choice 3 181 cmd = self._get_cmd() 182 inputs = RawInputs('3', 'tarek@ziade.org') 183 register_module.raw_input = inputs.__call__ 184 try: 185 # let's run the command 186 cmd.run() 187 finally: 188 del register_module.raw_input 189 190 # we should have send a request 191 self.assertEqual(len(self.conn.reqs), 1) 192 req = self.conn.reqs[0] 193 headers = dict(req.headers) 194 self.assertEqual(headers['Content-length'], '290') 195 self.assertTrue('tarek' in req.data) 196 197 @unittest.skipUnless(docutils is not None, 'needs docutils') 198 def test_strict(self): 199 # testing the script option 200 # when on, the register command stops if 201 # the metadata is incomplete or if 202 # long_description is not reSt compliant 203 204 # empty metadata 205 cmd = self._get_cmd({}) 206 cmd.ensure_finalized() 207 cmd.strict = 1 208 self.assertRaises(DistutilsSetupError, cmd.run) 209 210 # metadata are OK but long_description is broken 211 metadata = {'url': 'xxx', 'author': 'xxx', 212 'author_email': u'éxéxé', 213 'name': 'xxx', 'version': 'xxx', 214 'long_description': 'title\n==\n\ntext'} 215 216 cmd = self._get_cmd(metadata) 217 cmd.ensure_finalized() 218 cmd.strict = 1 219 self.assertRaises(DistutilsSetupError, cmd.run) 220 221 # now something that works 222 metadata['long_description'] = 'title\n=====\n\ntext' 223 cmd = self._get_cmd(metadata) 224 cmd.ensure_finalized() 225 cmd.strict = 1 226 inputs = RawInputs('1', 'tarek', 'y') 227 register_module.raw_input = inputs.__call__ 228 # let's run the command 229 try: 230 cmd.run() 231 finally: 232 del register_module.raw_input 233 234 # strict is not by default 235 cmd = self._get_cmd() 236 cmd.ensure_finalized() 237 inputs = RawInputs('1', 'tarek', 'y') 238 register_module.raw_input = inputs.__call__ 239 # let's run the command 240 try: 241 cmd.run() 242 finally: 243 del register_module.raw_input 244 245 # and finally a Unicode test (bug #12114) 246 metadata = {'url': u'xxx', 'author': u'\u00c9ric', 247 'author_email': u'xxx', u'name': 'xxx', 248 'version': u'xxx', 249 'description': u'Something about esszet \u00df', 250 'long_description': u'More things about esszet \u00df'} 251 252 cmd = self._get_cmd(metadata) 253 cmd.ensure_finalized() 254 cmd.strict = 1 255 inputs = RawInputs('1', 'tarek', 'y') 256 register_module.raw_input = inputs.__call__ 257 # let's run the command 258 try: 259 cmd.run() 260 finally: 261 del register_module.raw_input 262 263 @unittest.skipUnless(docutils is not None, 'needs docutils') 264 def test_register_invalid_long_description(self): 265 description = ':funkie:`str`' # mimic Sphinx-specific markup 266 metadata = {'url': 'xxx', 'author': 'xxx', 267 'author_email': 'xxx', 268 'name': 'xxx', 'version': 'xxx', 269 'long_description': description} 270 cmd = self._get_cmd(metadata) 271 cmd.ensure_finalized() 272 cmd.strict = True 273 inputs = RawInputs('2', 'tarek', 'tarek@ziade.org') 274 register_module.raw_input = inputs 275 self.addCleanup(delattr, register_module, 'raw_input') 276 self.assertRaises(DistutilsSetupError, cmd.run) 277 278 def test_check_metadata_deprecated(self): 279 # makes sure make_metadata is deprecated 280 cmd = self._get_cmd() 281 with check_warnings() as w: 282 warnings.simplefilter("always") 283 cmd.check_metadata() 284 self.assertEqual(len(w.warnings), 1) 104 285 105 286 def test_suite(): 106 return unittest.makeSuite( registerTestCase)287 return unittest.makeSuite(RegisterTestCase) 107 288 108 289 if __name__ == "__main__": 109 unittest.main(defaultTest="test_suite")290 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_sdist.py
r2 r391 1 1 """Tests for distutils.command.sdist.""" 2 2 import os 3 import tarfile 3 4 import unittest 4 import shutil5 import warnings 5 6 import zipfile 6 7 from os.path import join 7 import sys 8 9 from distutils.command.sdist import sdist 8 from textwrap import dedent 9 from test.test_support import captured_stdout, check_warnings, run_unittest 10 11 # zlib is not used here, but if it's not available 12 # the tests that use zipfile may fail 13 try: 14 import zlib 15 except ImportError: 16 zlib = None 17 18 try: 19 import grp 20 import pwd 21 UID_GID_SUPPORT = True 22 except ImportError: 23 UID_GID_SUPPORT = False 24 25 26 from distutils.command.sdist import sdist, show_formats 10 27 from distutils.core import Distribution 11 28 from distutils.tests.test_config import PyPIRCCommandTestCase 12 from distutils.errors import Distutils ExecError29 from distutils.errors import DistutilsOptionError 13 30 from distutils.spawn import find_executable 31 from distutils.log import WARN 32 from distutils.filelist import FileList 33 from distutils.archive_util import ARCHIVE_FORMATS 14 34 15 35 SETUP_PY = """ … … 20 40 """ 21 41 22 MANIFEST_IN = """ 23 recursive-include somecode * 42 MANIFEST = """\ 43 # file GENERATED by distutils, do NOT edit 44 README 45 buildout.cfg 46 inroot.txt 47 setup.py 48 data%(sep)sdata.dt 49 scripts%(sep)sscript.py 50 some%(sep)sfile.txt 51 some%(sep)sother_file.txt 52 somecode%(sep)s__init__.py 53 somecode%(sep)sdoc.dat 54 somecode%(sep)sdoc.txt 24 55 """ 25 56 26 class sdistTestCase(PyPIRCCommandTestCase):57 class SDistTestCase(PyPIRCCommandTestCase): 27 58 28 59 def setUp(self): 29 super(sdistTestCase, self).setUp() 60 # PyPIRCCommandTestCase creates a temp dir already 61 # and put it in self.tmp_dir 62 super(SDistTestCase, self).setUp() 63 # setting up an environment 30 64 self.old_path = os.getcwd() 31 self.temp_pkg = os.path.join(self.mkdtemp(), 'temppkg') 65 os.mkdir(join(self.tmp_dir, 'somecode')) 66 os.mkdir(join(self.tmp_dir, 'dist')) 67 # a package, and a README 68 self.write_file((self.tmp_dir, 'README'), 'xxx') 69 self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#') 70 self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY) 71 os.chdir(self.tmp_dir) 32 72 33 73 def tearDown(self): 74 # back to normal 34 75 os.chdir(self.old_path) 35 super(sdistTestCase, self).tearDown() 36 37 def _init_tmp_pkg(self): 38 if os.path.exists(self.temp_pkg): 39 shutil.rmtree(self.temp_pkg) 40 os.mkdir(self.temp_pkg) 41 os.mkdir(join(self.temp_pkg, 'somecode')) 42 os.mkdir(join(self.temp_pkg, 'dist')) 43 # creating a MANIFEST, a package, and a README 44 self._write(join(self.temp_pkg, 'MANIFEST.in'), MANIFEST_IN) 45 self._write(join(self.temp_pkg, 'README'), 'xxx') 46 self._write(join(self.temp_pkg, 'somecode', '__init__.py'), '#') 47 self._write(join(self.temp_pkg, 'setup.py'), SETUP_PY) 48 os.chdir(self.temp_pkg) 49 50 def _write(self, path, content): 51 f = open(path, 'w') 52 try: 53 f.write(content) 54 finally: 55 f.close() 56 57 def test_prune_file_list(self): 58 # this test creates a package with some vcs dirs in it 59 # and launch sdist to make sure they get pruned 60 # on all systems 61 self._init_tmp_pkg() 62 63 # creating VCS directories with some files in them 64 os.mkdir(join(self.temp_pkg, 'somecode', '.svn')) 65 self._write(join(self.temp_pkg, 'somecode', '.svn', 'ok.py'), 'xxx') 66 67 os.mkdir(join(self.temp_pkg, 'somecode', '.hg')) 68 self._write(join(self.temp_pkg, 'somecode', '.hg', 69 'ok'), 'xxx') 70 71 os.mkdir(join(self.temp_pkg, 'somecode', '.git')) 72 self._write(join(self.temp_pkg, 'somecode', '.git', 73 'ok'), 'xxx') 74 75 # now building a sdist 76 dist = Distribution() 76 super(SDistTestCase, self).tearDown() 77 78 def get_cmd(self, metadata=None): 79 """Returns a cmd""" 80 if metadata is None: 81 metadata = {'name': 'fake', 'version': '1.0', 82 'url': 'xxx', 'author': 'xxx', 83 'author_email': 'xxx'} 84 dist = Distribution(metadata) 77 85 dist.script_name = 'setup.py' 78 dist.metadata.name = 'fake'79 dist.metadata.version = '1.0'80 dist.metadata.url = 'http://xxx'81 dist.metadata.author = dist.metadata.author_email = 'xxx'82 86 dist.packages = ['somecode'] 83 87 dist.include_package_data = True 84 88 cmd = sdist(dist) 85 cmd.manifest = 'MANIFEST'86 cmd.template = 'MANIFEST.in'87 89 cmd.dist_dir = 'dist' 90 return dist, cmd 91 92 @unittest.skipUnless(zlib, "requires zlib") 93 def test_prune_file_list(self): 94 # this test creates a project with some VCS dirs and an NFS rename 95 # file, then launches sdist to check they get pruned on all systems 96 97 # creating VCS directories with some files in them 98 os.mkdir(join(self.tmp_dir, 'somecode', '.svn')) 99 self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx') 100 101 os.mkdir(join(self.tmp_dir, 'somecode', '.hg')) 102 self.write_file((self.tmp_dir, 'somecode', '.hg', 103 'ok'), 'xxx') 104 105 os.mkdir(join(self.tmp_dir, 'somecode', '.git')) 106 self.write_file((self.tmp_dir, 'somecode', '.git', 107 'ok'), 'xxx') 108 109 self.write_file((self.tmp_dir, 'somecode', '.nfs0001'), 'xxx') 110 111 # now building a sdist 112 dist, cmd = self.get_cmd() 88 113 89 114 # zip is available universally 90 115 # (tar might not be installed under win32) 91 116 cmd.formats = ['zip'] 117 118 cmd.ensure_finalized() 92 119 cmd.run() 93 120 94 121 # now let's check what we have 95 dist_folder = join(self.t emp_pkg, 'dist')122 dist_folder = join(self.tmp_dir, 'dist') 96 123 files = os.listdir(dist_folder) 97 self.assertEqual s(files, ['fake-1.0.zip'])124 self.assertEqual(files, ['fake-1.0.zip']) 98 125 99 126 zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) … … 104 131 105 132 # making sure everything has been pruned correctly 106 self.assertEquals(len(content), 4) 107 133 self.assertEqual(len(content), 4) 134 135 @unittest.skipUnless(zlib, "requires zlib") 108 136 def test_make_distribution(self): 109 137 … … 113 141 return 114 142 115 self._init_tmp_pkg()116 117 143 # now building a sdist 118 dist = Distribution() 119 dist.script_name = 'setup.py' 120 dist.metadata.name = 'fake' 121 dist.metadata.version = '1.0' 122 dist.metadata.url = 'http://xxx' 123 dist.metadata.author = dist.metadata.author_email = 'xxx' 124 dist.packages = ['somecode'] 125 dist.include_package_data = True 126 cmd = sdist(dist) 127 cmd.manifest = 'MANIFEST' 128 cmd.template = 'MANIFEST.in' 129 cmd.dist_dir = 'dist' 144 dist, cmd = self.get_cmd() 130 145 131 146 # creating a gztar then a tar 132 147 cmd.formats = ['gztar', 'tar'] 148 cmd.ensure_finalized() 133 149 cmd.run() 134 150 135 151 # making sure we have two files 136 dist_folder = join(self.t emp_pkg, 'dist')152 dist_folder = join(self.tmp_dir, 'dist') 137 153 result = os.listdir(dist_folder) 138 154 result.sort() 139 self.assertEquals(result, 140 ['fake-1.0.tar', 'fake-1.0.tar.gz'] ) 155 self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) 141 156 142 157 os.remove(join(dist_folder, 'fake-1.0.tar')) … … 145 160 # now trying a tar then a gztar 146 161 cmd.formats = ['tar', 'gztar'] 162 163 cmd.ensure_finalized() 147 164 cmd.run() 148 165 149 166 result = os.listdir(dist_folder) 150 167 result.sort() 151 self.assertEquals(result, 152 ['fake-1.0.tar', 'fake-1.0.tar.gz']) 168 self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) 169 170 @unittest.skipUnless(zlib, "requires zlib") 171 def test_unicode_metadata_tgz(self): 172 """ 173 Unicode name or version should not break building to tar.gz format. 174 Reference issue #11638. 175 """ 176 177 # create the sdist command with unicode parameters 178 dist, cmd = self.get_cmd({'name': u'fake', 'version': u'1.0'}) 179 180 # create the sdist as gztar and run the command 181 cmd.formats = ['gztar'] 182 cmd.ensure_finalized() 183 cmd.run() 184 185 # The command should have created the .tar.gz file 186 dist_folder = join(self.tmp_dir, 'dist') 187 result = os.listdir(dist_folder) 188 self.assertEqual(result, ['fake-1.0.tar.gz']) 189 190 os.remove(join(dist_folder, 'fake-1.0.tar.gz')) 191 192 @unittest.skipUnless(zlib, "requires zlib") 193 def test_add_defaults(self): 194 195 # http://bugs.python.org/issue2279 196 197 # add_default should also include 198 # data_files and package_data 199 dist, cmd = self.get_cmd() 200 201 # filling data_files by pointing files 202 # in package_data 203 dist.package_data = {'': ['*.cfg', '*.dat'], 204 'somecode': ['*.txt']} 205 self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') 206 self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#') 207 208 # adding some data in data_files 209 data_dir = join(self.tmp_dir, 'data') 210 os.mkdir(data_dir) 211 self.write_file((data_dir, 'data.dt'), '#') 212 some_dir = join(self.tmp_dir, 'some') 213 os.mkdir(some_dir) 214 # make sure VCS directories are pruned (#14004) 215 hg_dir = join(self.tmp_dir, '.hg') 216 os.mkdir(hg_dir) 217 self.write_file((hg_dir, 'last-message.txt'), '#') 218 # a buggy regex used to prevent this from working on windows (#6884) 219 self.write_file((self.tmp_dir, 'buildout.cfg'), '#') 220 self.write_file((self.tmp_dir, 'inroot.txt'), '#') 221 self.write_file((some_dir, 'file.txt'), '#') 222 self.write_file((some_dir, 'other_file.txt'), '#') 223 224 dist.data_files = [('data', ['data/data.dt', 225 'buildout.cfg', 226 'inroot.txt', 227 'notexisting']), 228 'some/file.txt', 229 'some/other_file.txt'] 230 231 # adding a script 232 script_dir = join(self.tmp_dir, 'scripts') 233 os.mkdir(script_dir) 234 self.write_file((script_dir, 'script.py'), '#') 235 dist.scripts = [join('scripts', 'script.py')] 236 237 cmd.formats = ['zip'] 238 cmd.use_defaults = True 239 240 cmd.ensure_finalized() 241 cmd.run() 242 243 # now let's check what we have 244 dist_folder = join(self.tmp_dir, 'dist') 245 files = os.listdir(dist_folder) 246 self.assertEqual(files, ['fake-1.0.zip']) 247 248 zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) 249 try: 250 content = zip_file.namelist() 251 finally: 252 zip_file.close() 253 254 # making sure everything was added 255 self.assertEqual(len(content), 12) 256 257 # checking the MANIFEST 258 f = open(join(self.tmp_dir, 'MANIFEST')) 259 try: 260 manifest = f.read() 261 finally: 262 f.close() 263 self.assertEqual(manifest, MANIFEST % {'sep': os.sep}) 264 265 @unittest.skipUnless(zlib, "requires zlib") 266 def test_metadata_check_option(self): 267 # testing the `medata-check` option 268 dist, cmd = self.get_cmd(metadata={}) 269 270 # this should raise some warnings ! 271 # with the `check` subcommand 272 cmd.ensure_finalized() 273 cmd.run() 274 warnings = [msg for msg in self.get_logs(WARN) if 275 msg.startswith('warning: check:')] 276 self.assertEqual(len(warnings), 2) 277 278 # trying with a complete set of metadata 279 self.clear_logs() 280 dist, cmd = self.get_cmd() 281 cmd.ensure_finalized() 282 cmd.metadata_check = 0 283 cmd.run() 284 warnings = [msg for msg in self.get_logs(WARN) if 285 msg.startswith('warning: check:')] 286 self.assertEqual(len(warnings), 0) 287 288 def test_check_metadata_deprecated(self): 289 # makes sure make_metadata is deprecated 290 dist, cmd = self.get_cmd() 291 with check_warnings() as w: 292 warnings.simplefilter("always") 293 cmd.check_metadata() 294 self.assertEqual(len(w.warnings), 1) 295 296 def test_show_formats(self): 297 with captured_stdout() as stdout: 298 show_formats() 299 300 # the output should be a header line + one line per format 301 num_formats = len(ARCHIVE_FORMATS.keys()) 302 output = [line for line in stdout.getvalue().split('\n') 303 if line.strip().startswith('--formats=')] 304 self.assertEqual(len(output), num_formats) 305 306 def test_finalize_options(self): 307 dist, cmd = self.get_cmd() 308 cmd.finalize_options() 309 310 # default options set by finalize 311 self.assertEqual(cmd.manifest, 'MANIFEST') 312 self.assertEqual(cmd.template, 'MANIFEST.in') 313 self.assertEqual(cmd.dist_dir, 'dist') 314 315 # formats has to be a string splitable on (' ', ',') or 316 # a stringlist 317 cmd.formats = 1 318 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 319 cmd.formats = ['zip'] 320 cmd.finalize_options() 321 322 # formats has to be known 323 cmd.formats = 'supazipa' 324 self.assertRaises(DistutilsOptionError, cmd.finalize_options) 325 326 @unittest.skipUnless(zlib, "requires zlib") 327 @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support") 328 def test_make_distribution_owner_group(self): 329 330 # check if tar and gzip are installed 331 if (find_executable('tar') is None or 332 find_executable('gzip') is None): 333 return 334 335 # now building a sdist 336 dist, cmd = self.get_cmd() 337 338 # creating a gztar and specifying the owner+group 339 cmd.formats = ['gztar'] 340 cmd.owner = pwd.getpwuid(0)[0] 341 cmd.group = grp.getgrgid(0)[0] 342 cmd.ensure_finalized() 343 cmd.run() 344 345 # making sure we have the good rights 346 archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') 347 archive = tarfile.open(archive_name) 348 try: 349 for member in archive.getmembers(): 350 self.assertEqual(member.uid, 0) 351 self.assertEqual(member.gid, 0) 352 finally: 353 archive.close() 354 355 # building a sdist again 356 dist, cmd = self.get_cmd() 357 358 # creating a gztar 359 cmd.formats = ['gztar'] 360 cmd.ensure_finalized() 361 cmd.run() 362 363 # making sure we have the good rights 364 archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') 365 archive = tarfile.open(archive_name) 366 367 # note that we are not testing the group ownership here 368 # because, depending on the platforms and the container 369 # rights (see #7408) 370 try: 371 for member in archive.getmembers(): 372 self.assertEqual(member.uid, os.getuid()) 373 finally: 374 archive.close() 375 376 # the following tests make sure there is a nice error message instead 377 # of a traceback when parsing an invalid manifest template 378 379 def _check_template(self, content): 380 dist, cmd = self.get_cmd() 381 os.chdir(self.tmp_dir) 382 self.write_file('MANIFEST.in', content) 383 cmd.ensure_finalized() 384 cmd.filelist = FileList() 385 cmd.read_template() 386 warnings = self.get_logs(WARN) 387 self.assertEqual(len(warnings), 1) 388 389 def test_invalid_template_unknown_command(self): 390 self._check_template('taunt knights *') 391 392 def test_invalid_template_wrong_arguments(self): 393 # this manifest command takes one argument 394 self._check_template('prune') 395 396 @unittest.skipIf(os.name != 'nt', 'test relevant for Windows only') 397 def test_invalid_template_wrong_path(self): 398 # on Windows, trailing slashes are not allowed 399 # this used to crash instead of raising a warning: #8286 400 self._check_template('include examples/') 401 402 @unittest.skipUnless(zlib, "requires zlib") 403 def test_get_file_list(self): 404 # make sure MANIFEST is recalculated 405 dist, cmd = self.get_cmd() 406 407 # filling data_files by pointing files in package_data 408 dist.package_data = {'somecode': ['*.txt']} 409 self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') 410 cmd.formats = ['gztar'] 411 cmd.ensure_finalized() 412 cmd.run() 413 414 f = open(cmd.manifest) 415 try: 416 manifest = [line.strip() for line in f.read().split('\n') 417 if line.strip() != ''] 418 finally: 419 f.close() 420 421 self.assertEqual(len(manifest), 5) 422 423 # adding a file 424 self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') 425 426 # make sure build_py is reinitialized, like a fresh run 427 build_py = dist.get_command_obj('build_py') 428 build_py.finalized = False 429 build_py.ensure_finalized() 430 431 cmd.run() 432 433 f = open(cmd.manifest) 434 try: 435 manifest2 = [line.strip() for line in f.read().split('\n') 436 if line.strip() != ''] 437 finally: 438 f.close() 439 440 # do we have the new file in MANIFEST ? 441 self.assertEqual(len(manifest2), 6) 442 self.assertIn('doc2.txt', manifest2[-1]) 443 444 @unittest.skipUnless(zlib, "requires zlib") 445 def test_manifest_marker(self): 446 # check that autogenerated MANIFESTs have a marker 447 dist, cmd = self.get_cmd() 448 cmd.ensure_finalized() 449 cmd.run() 450 451 f = open(cmd.manifest) 452 try: 453 manifest = [line.strip() for line in f.read().split('\n') 454 if line.strip() != ''] 455 finally: 456 f.close() 457 458 self.assertEqual(manifest[0], 459 '# file GENERATED by distutils, do NOT edit') 460 461 @unittest.skipUnless(zlib, 'requires zlib') 462 def test_manifest_comments(self): 463 # make sure comments don't cause exceptions or wrong includes 464 contents = dedent("""\ 465 # bad.py 466 #bad.py 467 good.py 468 """) 469 dist, cmd = self.get_cmd() 470 cmd.ensure_finalized() 471 self.write_file((self.tmp_dir, cmd.manifest), contents) 472 self.write_file((self.tmp_dir, 'good.py'), '# pick me!') 473 self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") 474 self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") 475 cmd.run() 476 self.assertEqual(cmd.filelist.files, ['good.py']) 477 478 @unittest.skipUnless(zlib, "requires zlib") 479 def test_manual_manifest(self): 480 # check that a MANIFEST without a marker is left alone 481 dist, cmd = self.get_cmd() 482 cmd.formats = ['gztar'] 483 cmd.ensure_finalized() 484 self.write_file((self.tmp_dir, cmd.manifest), 'README.manual') 485 self.write_file((self.tmp_dir, 'README.manual'), 486 'This project maintains its MANIFEST file itself.') 487 cmd.run() 488 self.assertEqual(cmd.filelist.files, ['README.manual']) 489 490 f = open(cmd.manifest) 491 try: 492 manifest = [line.strip() for line in f.read().split('\n') 493 if line.strip() != ''] 494 finally: 495 f.close() 496 497 self.assertEqual(manifest, ['README.manual']) 498 499 archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') 500 archive = tarfile.open(archive_name) 501 try: 502 filenames = [tarinfo.name for tarinfo in archive] 503 finally: 504 archive.close() 505 self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO', 506 'fake-1.0/README.manual']) 153 507 154 508 def test_suite(): 155 return unittest.makeSuite( sdistTestCase)509 return unittest.makeSuite(SDistTestCase) 156 510 157 511 if __name__ == "__main__": 158 unittest.main(defaultTest="test_suite")512 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_sysconfig.py
r2 r391 1 """Tests for distutils.dist.""" 2 3 from distutils import sysconfig 1 """Tests for distutils.sysconfig.""" 4 2 import os 5 3 import test 6 4 import unittest 5 import shutil 7 6 7 from distutils import sysconfig 8 from distutils.tests import support 8 9 from test.test_support import TESTFN 9 10 10 class SysconfigTestCase(unittest.TestCase): 11 class SysconfigTestCase(support.EnvironGuard, 12 unittest.TestCase): 11 13 def setUp(self): 12 14 super(SysconfigTestCase, self).setUp() … … 16 18 if self.makefile is not None: 17 19 os.unlink(self.makefile) 20 self.cleanup_testfn() 18 21 super(SysconfigTestCase, self).tearDown() 19 22 20 def test_get_config_h_filename(self): 21 config_h = sysconfig.get_config_h_filename() 22 self.assert_(os.path.isfile(config_h), config_h) 23 def cleanup_testfn(self): 24 path = test.test_support.TESTFN 25 if os.path.isfile(path): 26 os.remove(path) 27 elif os.path.isdir(path): 28 shutil.rmtree(path) 23 29 24 30 def test_get_python_lib(self): 25 31 lib_dir = sysconfig.get_python_lib() 26 32 # XXX doesn't work on Linux when Python was never installed before 27 #self.assert _(os.path.isdir(lib_dir), lib_dir)33 #self.assertTrue(os.path.isdir(lib_dir), lib_dir) 28 34 # test for pythonxx.lib? 29 35 self.assertNotEqual(sysconfig.get_python_lib(), 30 36 sysconfig.get_python_lib(prefix=TESTFN)) 37 _sysconfig = __import__('sysconfig') 38 res = sysconfig.get_python_lib(True, True) 39 self.assertEqual(_sysconfig.get_path('platstdlib'), res) 31 40 32 41 def test_get_python_inc(self): … … 39 48 self.assertTrue(os.path.isfile(python_h), python_h) 40 49 41 def test_get_config_vars(self): 42 cvars = sysconfig.get_config_vars() 43 self.assert_(isinstance(cvars, dict)) 44 self.assert_(cvars) 50 def test_parse_makefile_base(self): 51 self.makefile = test.test_support.TESTFN 52 fd = open(self.makefile, 'w') 53 try: 54 fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=LIB'" '\n') 55 fd.write('VAR=$OTHER\nOTHER=foo') 56 finally: 57 fd.close() 58 d = sysconfig.parse_makefile(self.makefile) 59 self.assertEqual(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", 60 'OTHER': 'foo'}) 45 61 46 62 def test_parse_makefile_literal_dollar(self): 47 63 self.makefile = test.test_support.TESTFN 48 64 fd = open(self.makefile, 'w') 49 fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=\$$LIB'" '\n') 50 fd.write('VAR=$OTHER\nOTHER=foo') 51 fd.close() 65 try: 66 fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=\$$LIB'" '\n') 67 fd.write('VAR=$OTHER\nOTHER=foo') 68 finally: 69 fd.close() 52 70 d = sysconfig.parse_makefile(self.makefile) 53 self.assertEquals(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 54 'OTHER': 'foo'}) 71 self.assertEqual(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", 72 'OTHER': 'foo'}) 73 74 75 def test_sysconfig_module(self): 76 import sysconfig as global_sysconfig 77 self.assertEqual(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS')) 78 self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS')) 79 80 @unittest.skipIf(sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'),'compiler flags customized') 81 def test_sysconfig_compiler_vars(self): 82 # On OS X, binary installers support extension module building on 83 # various levels of the operating system with differing Xcode 84 # configurations. This requires customization of some of the 85 # compiler configuration directives to suit the environment on 86 # the installed machine. Some of these customizations may require 87 # running external programs and, so, are deferred until needed by 88 # the first extension module build. With Python 3.3, only 89 # the Distutils version of sysconfig is used for extension module 90 # builds, which happens earlier in the Distutils tests. This may 91 # cause the following tests to fail since no tests have caused 92 # the global version of sysconfig to call the customization yet. 93 # The solution for now is to simply skip this test in this case. 94 # The longer-term solution is to only have one version of sysconfig. 95 96 import sysconfig as global_sysconfig 97 if sysconfig.get_config_var('CUSTOMIZED_OSX_COMPILER'): 98 return 99 self.assertEqual(global_sysconfig.get_config_var('LDSHARED'), sysconfig.get_config_var('LDSHARED')) 100 self.assertEqual(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC')) 101 55 102 56 103 -
python/trunk/Lib/distutils/tests/test_unixccompiler.py
r2 r391 1 1 """Tests for distutils.unixccompiler.""" 2 import os 2 3 import sys 3 4 import unittest 5 from test.test_support import EnvironmentVarGuard, run_unittest 4 6 5 7 from distutils import sysconfig … … 122 124 self.assertEqual(self.cc.rpath_foo(), '-R/foo') 123 125 126 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for OS X') 127 def test_osx_cc_overrides_ldshared(self): 128 # Issue #18080: 129 # ensure that setting CC env variable also changes default linker 130 def gcv(v): 131 if v == 'LDSHARED': 132 return 'gcc-4.2 -bundle -undefined dynamic_lookup ' 133 return 'gcc-4.2' 134 sysconfig.get_config_var = gcv 135 with EnvironmentVarGuard() as env: 136 env['CC'] = 'my_cc' 137 del env['LDSHARED'] 138 sysconfig.customize_compiler(self.cc) 139 self.assertEqual(self.cc.linker_so[0], 'my_cc') 140 141 @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for OS X') 142 def test_osx_explict_ldshared(self): 143 # Issue #18080: 144 # ensure that setting CC env variable does not change 145 # explicit LDSHARED setting for linker 146 def gcv(v): 147 if v == 'LDSHARED': 148 return 'gcc-4.2 -bundle -undefined dynamic_lookup ' 149 return 'gcc-4.2' 150 sysconfig.get_config_var = gcv 151 with EnvironmentVarGuard() as env: 152 env['CC'] = 'my_cc' 153 env['LDSHARED'] = 'my_ld -bundle -dynamic' 154 sysconfig.customize_compiler(self.cc) 155 self.assertEqual(self.cc.linker_so[0], 'my_ld') 156 124 157 125 158 def test_suite(): … … 127 160 128 161 if __name__ == "__main__": 129 unittest.main(defaultTest="test_suite")162 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_upload.py
r2 r391 1 # -*- encoding: utf8 -*- 1 2 """Tests for distutils.command.upload.""" 2 # -*- encoding: utf8 -*-3 import sys4 3 import os 5 4 import unittest 6 import httplib 5 from test.test_support import run_unittest 7 6 7 from distutils.command import upload as upload_mod 8 8 from distutils.command.upload import upload 9 9 from distutils.core import Distribution 10 10 11 from distutils.tests import support12 11 from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase 13 12 … … 30 29 """ 31 30 32 class _Resp(object):33 def __init__(self, status):34 self.status = status35 self.reason = 'OK'36 31 37 _CONNECTIONS = [] 32 PYPIRC_NOPASSWORD = """\ 33 [distutils] 38 34 39 class _FakeHTTPConnection(object): 40 def __init__(self, netloc): 41 self.requests = [] 42 self.headers = {} 43 self.body = None 44 self.netloc = netloc 45 _CONNECTIONS.append(self) 35 index-servers = 36 server1 46 37 47 def connect(self): 48 pass 49 endheaders = connect 38 [server1] 39 username:me 40 """ 50 41 51 def send(self, body): 52 self.body = body 42 class FakeOpen(object): 53 43 54 def putrequest(self, type_, data): 55 self.requests.append((type_, data)) 44 def __init__(self, url): 45 self.url = url 46 if not isinstance(url, str): 47 self.req = url 48 else: 49 self.req = None 50 self.msg = 'OK' 56 51 57 def putheader(self, name, value):58 self.headers[name] = value52 def getcode(self): 53 return 200 59 54 60 def getresponse(self):61 return _Resp(200)62 55 63 56 class uploadTestCase(PyPIRCCommandTestCase): … … 65 58 def setUp(self): 66 59 super(uploadTestCase, self).setUp() 67 self.old_klass = httplib.HTTPConnection 68 httplib.HTTPConnection = _FakeHTTPConnection 60 self.old_open = upload_mod.urlopen 61 upload_mod.urlopen = self._urlopen 62 self.last_open = None 69 63 70 64 def tearDown(self): 71 httplib.HTTPConnection = self.old_klass65 upload_mod.urlopen = self.old_open 72 66 super(uploadTestCase, self).tearDown() 67 68 def _urlopen(self, url): 69 self.last_open = FakeOpen(url) 70 return self.last_open 73 71 74 72 def test_finalize_options(self): 75 73 76 74 # new format 77 f = open(self.rc, 'w') 78 f.write(PYPIRC) 79 f.close() 80 75 self.write_file(self.rc, PYPIRC) 81 76 dist = Distribution() 82 77 cmd = upload(dist) … … 85 80 ('realm', 'pypi'), 86 81 ('repository', 'http://pypi.python.org/pypi')): 87 self.assertEqual s(getattr(cmd, attr), waited)82 self.assertEqual(getattr(cmd, attr), waited) 88 83 84 def test_saved_password(self): 85 # file with no password 86 self.write_file(self.rc, PYPIRC_NOPASSWORD) 87 88 # make sure it passes 89 dist = Distribution() 90 cmd = upload(dist) 91 cmd.finalize_options() 92 self.assertEqual(cmd.password, None) 93 94 # make sure we get it as well, if another command 95 # initialized it at the dist level 96 dist.password = 'xxx' 97 cmd = upload(dist) 98 cmd.finalize_options() 99 self.assertEqual(cmd.password, 'xxx') 89 100 90 101 def test_upload(self): … … 103 114 104 115 # what did we send ? 105 res = _CONNECTIONS[-1] 106 107 headers = res.headers 108 self.assert_('dédé' in res.body) 109 self.assertEquals(headers['Content-length'], '2085') 116 self.assertIn('dédé', self.last_open.req.data) 117 headers = dict(self.last_open.req.headers) 118 self.assertEqual(headers['Content-length'], '2085') 110 119 self.assertTrue(headers['Content-type'].startswith('multipart/form-data')) 111 112 method, request = res.requests[-1]113 self.assertEquals(method, 'POST')114 self.assert Equals(res.netloc, 'pypi.python.org')115 self.assertTrue('xxx' in res.body)116 self.assertFalse('\n' in headers['Authorization'])120 self.assertEqual(self.last_open.req.get_method(), 'POST') 121 self.assertEqual(self.last_open.req.get_full_url(), 122 'http://pypi.python.org/pypi') 123 self.assertTrue('xxx' in self.last_open.req.data) 124 auth = self.last_open.req.headers['Authorization'] 125 self.assertFalse('\n' in auth) 117 126 118 127 def test_suite(): … … 120 129 121 130 if __name__ == "__main__": 122 unittest.main(defaultTest="test_suite")131 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_util.py
r2 r391 2 2 import sys 3 3 import unittest 4 from test.test_support import run_unittest 4 5 5 6 from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError … … 22 23 23 24 if __name__ == "__main__": 24 unittest.main(defaultTest="test_suite")25 run_unittest(test_suite()) -
python/trunk/Lib/distutils/tests/test_versionpredicate.py
r2 r391 5 5 import distutils.versionpredicate 6 6 import doctest 7 from test.test_support import run_unittest 7 8 8 9 def test_suite(): 9 10 return doctest.DocTestSuite(distutils.versionpredicate) 11 12 if __name__ == '__main__': 13 run_unittest(test_suite())
Note:
See TracChangeset
for help on using the changeset viewer.