Commit b1c6f59d authored by Éric Araujo's avatar Éric Araujo

Branch merge

parents e2618f34 2a7cc534
......@@ -126,7 +126,7 @@ class bdist(Command):
# Reinitialize and run each command.
for i in range(len(self.formats)):
cmd_name = commands[i]
sub_cmd = self.get_reinitialized_command(cmd_name)
sub_cmd = self.reinitialize_command(cmd_name)
sub_cmd.format = self.formats[i]
# passing the owner and group names for tar archiving
......
......@@ -80,7 +80,7 @@ class bdist_dumb(Command):
if not self.skip_build:
self.run_command('build')
install = self.get_reinitialized_command('install_dist',
install = self.reinitialize_command('install_dist',
reinit_subcommands=True)
install.root = self.bdist_dir
install.skip_build = self.skip_build
......
......@@ -183,13 +183,13 @@ class bdist_msi(Command):
if not self.skip_build:
self.run_command('build')
install = self.get_reinitialized_command('install_dist',
install = self.reinitialize_command('install_dist',
reinit_subcommands=True)
install.prefix = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = False
install_lib = self.get_reinitialized_command('install_lib')
install_lib = self.reinitialize_command('install_lib')
# we do not want to include pyc or pyo files
install_lib.compile = False
install_lib.optimize = 0
......
......@@ -115,14 +115,13 @@ class bdist_wininst(Command):
if not self.skip_build:
self.run_command('build')
install = self.get_reinitialized_command('install',
reinit_subcommands=True)
install = self.reinitialize_command('install', reinit_subcommands=True)
install.root = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = False
install.plat_name = self.plat_name
install_lib = self.get_reinitialized_command('install_lib')
install_lib = self.reinitialize_command('install_lib')
# we do not want to include pyc or pyo files
install_lib.compile = False
install_lib.optimize = 0
......
......@@ -318,8 +318,8 @@ class Command:
cmd_obj.ensure_finalized()
return cmd_obj
def get_reinitialized_command(self, command, reinit_subcommands=False):
return self.distribution.get_reinitialized_command(
def reinitialize_command(self, command, reinit_subcommands=False):
return self.distribution.reinitialize_command(
command, reinit_subcommands)
def run_command(self, command):
......
......@@ -55,9 +55,7 @@ class install_dist(Command):
('install-data=', None,
"installation directory for data files"),
# Byte-compilation options -- see install_lib.py for details, as
# these are duplicated from there (but only install_lib does
# anything with them).
# Byte-compilation options -- see install_lib for details
('compile', 'c', "compile .py to .pyc [default]"),
('no-compile', None, "don't compile .py files"),
('optimize=', 'O',
......
......@@ -16,8 +16,8 @@ class install_distinfo(Command):
description = 'create a .dist-info directory for the distribution'
user_options = [
('distinfo-dir=', None,
"directory where the the .dist-info directory will be installed"),
('install-dir=', None,
"directory where the the .dist-info directory will be created"),
('installer=', None,
"the name of the installer"),
('requested', None,
......@@ -35,7 +35,7 @@ class install_distinfo(Command):
negative_opt = {'no-requested': 'requested'}
def initialize_options(self):
self.distinfo_dir = None
self.install_dir = None
self.installer = None
self.requested = None
self.no_record = None
......@@ -46,8 +46,7 @@ class install_distinfo(Command):
self.set_undefined_options('install_dist',
'installer', 'requested', 'no_record')
self.set_undefined_options('install_lib',
('install_dir', 'distinfo_dir'))
self.set_undefined_options('install_lib', 'install_dir')
if self.installer is None:
# FIXME distutils or packaging?
......@@ -64,26 +63,26 @@ class install_distinfo(Command):
basename = metadata.get_fullname(filesafe=True) + ".dist-info"
self.distinfo_dir = os.path.join(self.distinfo_dir, basename)
self.install_dir = os.path.join(self.install_dir, basename)
def run(self):
target = self.distinfo_dir
target = self.install_dir
if os.path.isdir(target) and not os.path.islink(target):
if not self.dry_run:
rmtree(target)
elif os.path.exists(target):
self.execute(os.unlink, (self.distinfo_dir,),
self.execute(os.unlink, (self.install_dir,),
"removing " + target)
self.execute(os.makedirs, (target,), "creating " + target)
metadata_path = os.path.join(self.distinfo_dir, 'METADATA')
metadata_path = os.path.join(self.install_dir, 'METADATA')
self.execute(self.distribution.metadata.write, (metadata_path,),
"creating " + metadata_path)
self.outfiles.append(metadata_path)
installer_path = os.path.join(self.distinfo_dir, 'INSTALLER')
installer_path = os.path.join(self.install_dir, 'INSTALLER')
logger.info('creating %s', installer_path)
if not self.dry_run:
with open(installer_path, 'w') as f:
......@@ -91,7 +90,7 @@ class install_distinfo(Command):
self.outfiles.append(installer_path)
if self.requested:
requested_path = os.path.join(self.distinfo_dir, 'REQUESTED')
requested_path = os.path.join(self.install_dir, 'REQUESTED')
logger.info('creating %s', requested_path)
if not self.dry_run:
open(requested_path, 'wb').close()
......@@ -100,7 +99,7 @@ class install_distinfo(Command):
if not self.no_resources:
install_data = self.get_finalized_command('install_data')
if install_data.get_resources_out() != []:
resources_path = os.path.join(self.distinfo_dir,
resources_path = os.path.join(self.install_dir,
'RESOURCES')
logger.info('creating %s', resources_path)
if not self.dry_run:
......@@ -114,7 +113,7 @@ class install_distinfo(Command):
self.outfiles.append(resources_path)
if not self.no_record:
record_path = os.path.join(self.distinfo_dir, 'RECORD')
record_path = os.path.join(self.install_dir, 'RECORD')
logger.info('creating %s', record_path)
if not self.dry_run:
with open(record_path, 'w', encoding='utf-8') as f:
......
......@@ -56,7 +56,7 @@ class test(Command):
prev_syspath = sys.path[:]
try:
# build release
build = self.get_reinitialized_command('build')
build = self.reinitialize_command('build')
self.run_command('build')
sys.path.insert(0, build.build_lib)
......
......@@ -30,6 +30,7 @@ from textwrap import dedent
from tokenize import detect_encoding
from configparser import RawConfigParser
from packaging import logger
# importing this with an underscore as it should be replaced by the
# dict form or another structures for all purposes
from packaging._trove import all_classifiers as _CLASSIFIERS_LIST
......@@ -124,7 +125,7 @@ def ask_yn(question, default=None, helptext=None):
if answer and answer[0].lower() in ('y', 'n'):
return answer[0].lower()
print('\nERROR: You must select "Y" or "N".\n')
logger.error('You must select "Y" or "N".')
# XXX use util.ask
......@@ -147,10 +148,7 @@ def ask(question, default=None, helptext=None, required=True,
helptext = helptext.strip("\n")
while True:
sys.stdout.write(prompt)
sys.stdout.flush()
line = sys.stdin.readline().strip()
line = input(prompt).strip()
if line == '?':
print('=' * 70)
print(helptext)
......@@ -271,9 +269,10 @@ class MainProgram:
def _write_cfg(self):
if os.path.exists(_FILENAME):
if os.path.exists('%s.old' % _FILENAME):
print("ERROR: %(name)s.old backup exists, please check that "
"current %(name)s is correct and remove %(name)s.old" %
{'name': _FILENAME})
message = ("ERROR: %(name)s.old backup exists, please check "
"that current %(name)s is correct and remove "
"%(name)s.old" % {'name': _FILENAME})
logger.error(message)
return
shutil.move(_FILENAME, '%s.old' % _FILENAME)
......@@ -320,7 +319,7 @@ class MainProgram:
fp.write('\n')
os.chmod(_FILENAME, 0o644)
print('Wrote "%s".' % _FILENAME)
logger.info('Wrote "%s".' % _FILENAME)
def convert_py_to_cfg(self):
"""Generate a setup.cfg from an existing setup.py.
......@@ -614,7 +613,7 @@ class MainProgram:
break
if len(found_list) == 0:
print('ERROR: Could not find a matching license for "%s"' %
logger.error('Could not find a matching license for "%s"' %
license)
continue
......@@ -636,8 +635,8 @@ class MainProgram:
try:
index = found_list[int(choice) - 1]
except ValueError:
print("ERROR: Invalid selection, type a number from the list "
"above.")
logger.error(
"Invalid selection, type a number from the list above.")
classifiers.add(_CLASSIFIERS_LIST[index])
......@@ -660,8 +659,8 @@ class MainProgram:
classifiers.add(key)
return
except (IndexError, ValueError):
print("ERROR: Invalid selection, type a single digit "
"number.")
logger.error(
"Invalid selection, type a single digit number.")
def main():
......@@ -675,7 +674,3 @@ def main():
# program.write_setup_script()
# packaging.util.cfg_to_args()
program()
if __name__ == '__main__':
main()
......@@ -224,6 +224,7 @@ def dependent_dists(dists, dist):
def main():
# XXX move to run._graph
from packaging.database import get_distributions
tempout = StringIO()
try:
......@@ -267,7 +268,3 @@ def main():
else:
print('Supported option: -d [filename]')
sys.exit(1)
if __name__ == '__main__':
main()
......@@ -636,9 +636,9 @@ Common commands: (see '--help-commands' for more)
except ValueError as msg:
raise PackagingOptionError(msg)
def get_reinitialized_command(self, command, reinit_subcommands=False):
def reinitialize_command(self, command, reinit_subcommands=False):
"""Reinitializes a command to the state it was in when first
returned by 'get_command_obj()': ie., initialized but not yet
returned by 'get_command_obj()': i.e., initialized but not yet
finalized. This provides the opportunity to sneak option
values in programmatically, overriding or supplementing
user-supplied values from the config files and command line.
......@@ -650,10 +650,11 @@ Common commands: (see '--help-commands' for more)
'reinit_subcommands' is true, also reinitializes the command's
sub-commands, as declared by the 'sub_commands' class attribute (if
it has one). See the "install_dist" command for an example. Only
reinitializes the sub-commands that actually matter, ie. those
whose test predicates return true.
reinitializes the sub-commands that actually matter, i.e. those
whose test predicate return true.
Returns the reinitialized command object.
Returns the reinitialized command object. It will be the same
object as the one stored in the self.command_obj attribute.
"""
if not isinstance(command, Command):
command_name = command
......@@ -671,7 +672,7 @@ Common commands: (see '--help-commands' for more)
if reinit_subcommands:
for sub in command.get_sub_commands():
self.get_reinitialized_command(sub, reinit_subcommands)
self.reinitialize_command(sub, reinit_subcommands)
return command
......
......@@ -527,12 +527,3 @@ def install(project):
logger.info('%r conflicts with %s', project, ','.join(projects))
return True
def _main(**attrs):
if 'script_args' not in attrs:
attrs['requirements'] = sys.argv[1]
get_infos(**attrs)
if __name__ == '__main__':
_main()
......@@ -41,6 +41,9 @@ import tempfile
import sysconfig
from packaging.dist import Distribution
from packaging.util import resolve_name
from packaging.command import set_command, _COMMANDS
from packaging.tests import unittest
from test.support import requires_zlib, unlink
......@@ -49,9 +52,10 @@ __all__ = [
# TestCase mixins
'LoggingCatcher', 'TempdirManager', 'EnvironRestorer',
# mocks
'DummyCommand', 'TestDistribution',
'DummyCommand', 'TestDistribution', 'Inputs',
# misc. functions and decorators
'fake_dec', 'create_distribution', 'copy_xxmodule_c', 'fixup_build_ext',
'fake_dec', 'create_distribution', 'use_command',
'copy_xxmodule_c', 'fixup_build_ext',
# imported from this module for backport purposes
'unittest', 'requires_zlib', 'skip_2to3_optimize', 'skip_unless_symlink',
]
......@@ -247,7 +251,7 @@ class DummyCommand:
Useful for mocking one dependency command in the tests for another
command, see e.g. the dummy build command in test_build_scripts.
"""
# XXX does not work with dist.get_reinitialized_command, which typechecks
# XXX does not work with dist.reinitialize_command, which typechecks
# and wants a finalized attribute
def __init__(self, **kwargs):
......@@ -270,6 +274,22 @@ class TestDistribution(Distribution):
return self._config_files
class Inputs:
"""Fakes user inputs."""
# TODO document usage
# TODO use context manager or something for auto cleanup
def __init__(self, *answers):
self.answers = answers
self.index = 0
def __call__(self, prompt=''):
try:
return self.answers[self.index]
finally:
self.index += 1
def create_distribution(configfiles=()):
"""Prepares a distribution with given config files parsed."""
d = TestDistribution()
......@@ -280,6 +300,15 @@ def create_distribution(configfiles=()):
return d
def use_command(testcase, fullname):
"""Register command at *fullname* for the duration of a test."""
set_command(fullname)
# XXX maybe set_command should return the class object
name = resolve_name(fullname).get_command_name()
# XXX maybe we need a public API to remove commands
testcase.addCleanup(_COMMANDS.__delitem__, name)
def fake_dec(*args, **kw):
"""Fake decorator"""
def _wrap(func):
......
......@@ -3,7 +3,6 @@ import sys
import site
import sysconfig
import textwrap
from io import StringIO
from packaging.dist import Distribution
from packaging.errors import (UnknownFileError, CompileError,
PackagingPlatformError)
......@@ -11,7 +10,7 @@ from packaging.command.build_ext import build_ext
from packaging.compiler.extension import Extension
from test.script_helper import assert_python_ok
from packaging.tests import support, unittest, verbose
from packaging.tests import support, unittest
class BuildExtTestCase(support.TempdirManager,
......@@ -37,18 +36,10 @@ class BuildExtTestCase(support.TempdirManager,
support.fixup_build_ext(cmd)
cmd.build_lib = self.tmp_dir
cmd.build_temp = self.tmp_dir
old_stdout = sys.stdout
if not verbose:
# silence compiler output
sys.stdout = StringIO()
try:
cmd.ensure_finalized()
cmd.run()
finally:
sys.stdout = old_stdout
code = """if 1:
code = textwrap.dedent("""\
import sys
sys.path.insert(0, %r)
......@@ -63,7 +54,8 @@ class BuildExtTestCase(support.TempdirManager,
doc = 'This is a template module just for instruction.'
assert xx.__doc__ == doc
assert isinstance(xx.Null(), xx.Null)
assert isinstance(xx.Str(), xx.Str)"""
assert isinstance(xx.Str(), xx.Str)
""")
code = code % self.tmp_dir
assert_python_ok('-c', code)
......@@ -387,17 +379,9 @@ class BuildExtTestCase(support.TempdirManager,
cmd.build_lib = self.tmp_dir
cmd.build_temp = self.tmp_dir
try:
old_stdout = sys.stdout
if not verbose:
# silence compiler output
sys.stdout = StringIO()
try:
cmd.ensure_finalized()
cmd.run()
finally:
sys.stdout = old_stdout
except CompileError:
self.fail("Wrong deployment target during compilation")
......
......@@ -67,8 +67,6 @@ class BuildPyTestCase(support.TempdirManager,
def test_empty_package_dir(self):
# See SF 1668596/1720897.
cwd = os.getcwd()
# create the distribution files.
sources = self.mkdtemp()
pkg = os.path.join(sources, 'pkg')
......@@ -79,10 +77,6 @@ class BuildPyTestCase(support.TempdirManager,
open(os.path.join(testdir, "testfile"), "wb").close()
os.chdir(sources)
old_stdout = sys.stdout
#sys.stdout = StringIO.StringIO()
try:
dist = Distribution({"packages": ["pkg"],
"package_dir": sources,
"package_data": {"pkg": ["doc/*"]}})
......@@ -93,10 +87,6 @@ class BuildPyTestCase(support.TempdirManager,
dist.run_commands()
except PackagingFileError:
self.fail("failed package_data test when package_dir is ''")
finally:
# Restore state.
os.chdir(cwd)
sys.stdout = old_stdout
def test_byte_compile(self):
project_dir, dist = self.create_dist(py_modules=['boiledeggs'])
......
......@@ -36,8 +36,6 @@ class cleanTestCase(support.TempdirManager, support.LoggingCatcher,
'%r was not removed' % path)
# let's run the command again (should spit warnings but succeed)
cmd.all = True
cmd.ensure_finalized()
cmd.run()
......
......@@ -62,6 +62,7 @@ class InstallDataTestCase(support.TempdirManager,
# let's try with warn_dir one
cmd.warn_dir = True
cmd.finalized = False
cmd.ensure_finalized()
cmd.run()
......@@ -80,6 +81,7 @@ class InstallDataTestCase(support.TempdirManager,
cmd.data_files = {one: '{inst}/one', two: '{inst2}/two',
three: '{inst3}/three'}
cmd.finalized = False
cmd.ensure_finalized()
cmd.run()
......
......@@ -49,7 +49,7 @@ class InstallDistinfoTestCase(support.TempdirManager,
cmd = install_distinfo(dist)
dist.command_obj['install_distinfo'] = cmd
cmd.distinfo_dir = install_dir
cmd.install_dir = install_dir
cmd.ensure_finalized()
cmd.run()
......@@ -76,7 +76,7 @@ class InstallDistinfoTestCase(support.TempdirManager,
cmd = install_distinfo(dist)
dist.command_obj['install_distinfo'] = cmd
cmd.distinfo_dir = install_dir
cmd.install_dir = install_dir
cmd.installer = 'bacon-python'
cmd.ensure_finalized()
cmd.run()
......@@ -96,7 +96,7 @@ class InstallDistinfoTestCase(support.TempdirManager,
cmd = install_distinfo(dist)
dist.command_obj['install_distinfo'] = cmd
cmd.distinfo_dir = install_dir
cmd.install_dir = install_dir
cmd.requested = False
cmd.ensure_finalized()
cmd.run()
......@@ -116,7 +116,7 @@ class InstallDistinfoTestCase(support.TempdirManager,
cmd = install_distinfo(dist)
dist.command_obj['install_distinfo'] = cmd
cmd.distinfo_dir = install_dir
cmd.install_dir = install_dir
cmd.no_record = True
cmd.ensure_finalized()
cmd.run()
......@@ -214,7 +214,7 @@ class InstallDistinfoTestCase(support.TempdirManager,
cmd = install_distinfo(dist)
dist.command_obj['install_distinfo'] = cmd
cmd.distinfo_dir = install_dir
cmd.install_dir = install_dir
cmd.ensure_finalized()
cmd.run()
......
......@@ -12,6 +12,7 @@ except ImportError:
DOCUTILS_SUPPORT = False
from packaging.tests import unittest, support
from packaging.tests.support import Inputs
from packaging.command import register as register_module
from packaging.command.register import register
from packaging.errors import PackagingSetupError
......@@ -38,19 +39,6 @@ password:password
"""
class Inputs:
"""Fakes user inputs."""
def __init__(self, *answers):
self.answers = answers
self.index = 0
def __call__(self, prompt=''):
try:
return self.answers[self.index]
finally:
self.index += 1
class FakeOpener:
"""Fakes a PyPI server"""
def __init__(self):
......@@ -143,6 +131,7 @@ class RegisterTestCase(support.TempdirManager,
register_module.input = _no_way
cmd.show_response = True
cmd.finalized = False
cmd.ensure_finalized()
cmd.run()
......
......@@ -140,7 +140,7 @@ class SDistTestCase(support.TempdirManager,
# now trying a tar then a gztar
cmd.formats = ['tar', 'gztar']
cmd.finalized = False
cmd.ensure_finalized()
cmd.run()
......
"""Tests for packaging.config."""
import os
import sys
from io import StringIO
from packaging import command
from packaging.dist import Distribution
......@@ -183,13 +182,14 @@ class FooBarBazTest:
def __init__(self, dist):
self.distribution = dist
self._record = []
@classmethod
def get_command_name(cls):
return 'foo'
def run(self):
self.distribution.foo_was_here = True
self._record.append('foo has run')
def nothing(self):
pass
......@@ -209,21 +209,11 @@ class ConfigTestCase(support.TempdirManager,
def setUp(self):
super(ConfigTestCase, self).setUp()
self.addCleanup(setattr, sys, 'stdout', sys.stdout)
self.addCleanup(setattr, sys, 'stderr', sys.stderr)
sys.stdout = StringIO()
sys.stderr = StringIO()
self.addCleanup(os.chdir, os.getcwd())
tempdir = self.mkdtemp()
self.working_dir = os.getcwd()
os.chdir(tempdir)
self.tempdir = tempdir
def tearDown(self):
os.chdir(self.working_dir)
super(ConfigTestCase, self).tearDown()
def write_setup(self, kwargs=None):
opts = {'description-file': 'README', 'extra-files': '',
'setup-hooks': 'packaging.tests.test_config.version_hook'}
......@@ -378,7 +368,7 @@ class ConfigTestCase(support.TempdirManager,
self.assertIn('hooks', sys.modules)
def test_missing_setup_hook_warns(self):
self.write_setup({'setup-hooks': 'this.does._not.exist'})
self.write_setup({'setup-hooks': 'does._not.exist'})
self.write_file('README', 'yeah')
self.get_dist()
logs = self.get_logs()
......@@ -491,10 +481,12 @@ class ConfigTestCase(support.TempdirManager,
self.write_file((pkg, '__init__.py'), '#')
# try to run the install command to see if foo is called
self.addCleanup(command._COMMANDS.__delitem__, 'foo')
dist = self.get_dist()
self.assertIn('foo', command.get_command_names())
self.assertEqual('FooBarBazTest',
dist.get_command_obj('foo').__class__.__name__)
dist.run_command('install_dist')
cmd = dist.get_command_obj('foo')
self.assertEqual(cmd.__class__.__name__, 'FooBarBazTest')
self.assertEqual(cmd._record, ['foo has run'])
def test_suite():
......
......@@ -2,15 +2,17 @@
import os
import sys
import sysconfig
from io import StringIO
from textwrap import dedent
from packaging import create
from packaging.create import MainProgram, ask_yn, ask, main
from packaging.tests import support, unittest
from packaging.tests.support import Inputs
class CreateTestCase(support.TempdirManager,
support.EnvironRestorer,
support.LoggingCatcher,
unittest.TestCase):
maxDiff = None
......@@ -18,11 +20,6 @@ class CreateTestCase(support.TempdirManager,
def setUp(self):
super(CreateTestCase, self).setUp()
self._stdin = sys.stdin # TODO use Inputs
self._stdout = sys.stdout
sys.stdin = StringIO()
sys.stdout = StringIO()
self._cwd = os.getcwd()
self.wdir = self.mkdtemp()
os.chdir(self.wdir)
# patch sysconfig
......@@ -32,29 +29,24 @@ class CreateTestCase(support.TempdirManager,
'doc': sys.prefix + '/share/doc/pyxfoil', }
def tearDown(self):
sys.stdin = self._stdin
sys.stdout = self._stdout
os.chdir(self._cwd)
sysconfig.get_paths = self._old_get_paths
if hasattr(create, 'input'):
del create.input
super(CreateTestCase, self).tearDown()
def test_ask_yn(self):
sys.stdin.write('y\n')
sys.stdin.seek(0)
create.input = Inputs('y')
self.assertEqual('y', ask_yn('is this a test'))
def test_ask(self):
sys.stdin.write('a\n')
sys.stdin.write('b\n')
sys.stdin.seek(0)
create.input = Inputs('a', 'b')
self.assertEqual('a', ask('is this a test'))
self.assertEqual('b', ask(str(list(range(0, 70))), default='c',
lengthy=True))
def test_set_multi(self):
mainprogram = MainProgram()
sys.stdin.write('aaaaa\n')
sys.stdin.seek(0)
create.input = Inputs('aaaaa')
mainprogram.data['author'] = []
mainprogram._set_multi('_set_multi test', 'author')
self.assertEqual(['aaaaa'], mainprogram.data['author'])
......@@ -130,8 +122,7 @@ class CreateTestCase(support.TempdirManager,
scripts=['my_script', 'bin/run'],
)
"""), encoding='utf-8')
sys.stdin.write('y\n')
sys.stdin.seek(0)
create.input = Inputs('y')
main()
path = os.path.join(self.wdir, 'setup.cfg')
......@@ -206,9 +197,7 @@ My super Death-scription
barbar is now in the public domain,
ho, baby!
'''))
sys.stdin.write('y\n')
sys.stdin.seek(0)
# FIXME Out of memory error.
create.input = Inputs('y')
main()
path = os.path.join(self.wdir, 'setup.cfg')
......
......@@ -6,30 +6,32 @@ import textwrap
import packaging.dist
from packaging.dist import Distribution
from packaging.command import set_command, _COMMANDS
from packaging.command.cmd import Command
from packaging.errors import PackagingModuleError, PackagingOptionError
from packaging.tests import captured_stdout
from packaging.tests import support, unittest
from packaging.tests.support import create_distribution
from packaging.tests.support import create_distribution, use_command
from test.support import unload
class test_dist(Command):
"""Sample packaging extension command."""
"""Custom command used for testing."""
user_options = [
("sample-option=", "S", "help text"),
('sample-option=', 'S',
"help text"),
]
def initialize_options(self):
self.sample_option = None
self._record = []
def finalize_options(self):
pass
if self.sample_option is None:
self.sample_option = 'default value'
def run(self):
pass
self._record.append('test_dist has run')
class DistributionTestCase(support.TempdirManager,
......@@ -45,14 +47,10 @@ class DistributionTestCase(support.TempdirManager,
# (defaulting to sys.argv)
self.argv = sys.argv, sys.argv[:]
del sys.argv[1:]
self._commands = _COMMANDS.copy()
def tearDown(self):
sys.argv = self.argv[0]
sys.argv[:] = self.argv[1]
# XXX maybe we need a public API to remove commands
_COMMANDS.clear()
_COMMANDS.update(self._commands)
super(DistributionTestCase, self).tearDown()
@unittest.skip('needs to be updated')
......@@ -181,7 +179,8 @@ class DistributionTestCase(support.TempdirManager,
self.write_file((temp_home, "config2.cfg"),
'[test_dist]\npre-hook.b = type')
set_command('packaging.tests.test_dist.test_dist')
use_command(self, 'packaging.tests.test_dist.test_dist')
dist = create_distribution(config_files)
cmd = dist.get_command_obj("test_dist")
self.assertEqual(cmd.pre_hook, {"a": 'type', "b": 'type'})
......@@ -209,7 +208,7 @@ class DistributionTestCase(support.TempdirManager,
record.append('post-%s' % cmd.get_command_name())
'''))
set_command('packaging.tests.test_dist.test_dist')
use_command(self, 'packaging.tests.test_dist.test_dist')
d = create_distribution([config_file])
cmd = d.get_command_obj("test_dist")
......@@ -236,7 +235,7 @@ class DistributionTestCase(support.TempdirManager,
[test_dist]
pre-hook.test = nonexistent.dotted.name'''))
set_command('packaging.tests.test_dist.test_dist')
use_command(self, 'packaging.tests.test_dist.test_dist')
d = create_distribution([config_file])
cmd = d.get_command_obj("test_dist")
cmd.ensure_finalized()
......@@ -251,7 +250,7 @@ class DistributionTestCase(support.TempdirManager,
[test_dist]
pre-hook.test = packaging.tests.test_dist.__doc__'''))
set_command('packaging.tests.test_dist.test_dist')
use_command(self, 'packaging.tests.test_dist.test_dist')
d = create_distribution([config_file])
cmd = d.get_command_obj("test_dist")
cmd.ensure_finalized()
......
......@@ -33,11 +33,9 @@ class RunTestCase(support.TempdirManager,
def setUp(self):
super(RunTestCase, self).setUp()
self.old_stdout = sys.stdout
self.old_argv = sys.argv, sys.argv[:]
def tearDown(self):
sys.stdout = self.old_stdout
sys.argv = self.old_argv[0]
sys.argv[:] = self.old_argv[1]
super(RunTestCase, self).tearDown()
......
"""Tests for the packaging.uninstall module."""
import os
import sys
import logging
import packaging.util
......@@ -31,16 +30,12 @@ class UninstallTestCase(support.TempdirManager,
def setUp(self):
super(UninstallTestCase, self).setUp()
self.addCleanup(setattr, sys, 'stdout', sys.stdout)
self.addCleanup(setattr, sys, 'stderr', sys.stderr)
self.addCleanup(os.chdir, os.getcwd())
self.addCleanup(enable_cache)
self.root_dir = self.mkdtemp()
self.cwd = os.getcwd()
disable_cache()
def tearDown(self):
os.chdir(self.cwd)
packaging.util._path_created.clear()
super(UninstallTestCase, self).tearDown()
......
......@@ -170,8 +170,8 @@ class UtilTestCase(support.EnvironRestorer,
def unmock_popen(self):
util.find_executable = self.old_find_executable
subprocess.Popen = self.old_popen
sys.old_stdout = self.old_stdout
sys.old_stderr = self.old_stderr
sys.stdout = self.old_stdout
sys.stderr = self.old_stderr
def test_convert_path(self):
# linux/mac
......
......@@ -488,7 +488,6 @@ def get_config_vars(*args):
# Setting 'userbase' is done below the call to the
# init function to enable using 'get_config_var' in
# the init-function.
if sys.version >= '2.6':
_CONFIG_VARS['userbase'] = _getuserbase()
if 'srcdir' not in _CONFIG_VARS:
......
......@@ -172,6 +172,7 @@ import io
import json
import logging
import os
import packaging.command
import packaging.database
import platform
import random
......@@ -967,7 +968,7 @@ class saved_test_environment:
'sys.warnoptions', 'threading._dangling',
'multiprocessing.process._dangling',
'sysconfig._CONFIG_VARS', 'sysconfig._SCHEMES',
'packaging.database_caches',
'packaging.command._COMMANDS', 'packaging.database_caches',
)
def get_sys_argv(self):
......@@ -1055,6 +1056,22 @@ class saved_test_environment:
# Can't easily revert the logging state
pass
def get_packaging_command__COMMANDS(self):
# registry mapping command names to full dotted path or to the actual
# class (resolved on demand); this check only looks at the names, not
# the types of the values (IOW, if a value changes from a string
# (dotted path) to a class it's okay but if a key (i.e. command class)
# is added we complain)
id_ = id(packaging.command._COMMANDS)
keys = set(packaging.command._COMMANDS)
return id_, keys
def restore_packaging_command__COMMANDS(self, saved):
# if command._COMMANDS was bound to another dict obhect, we can't
# restore the previous object and contents, because the get_ method
# above does not return the dict object (to ignore changes in values)
for key in packaging.command._COMMANDS.keys() - saved[1]:
del packaging.command._COMMANDS[key]
def get_packaging_database_caches(self):
# caching system used by the PEP 376 implementation
# we have one boolean and four dictionaries, initially empty
......
......@@ -294,8 +294,6 @@ Core and Builtins
- Issue #11320: fix bogus memory management in Modules/getpath.c, leading to
a possible crash when calling Py_SetPath().
- _ast.__version__ is now a Mercurial hex revision.
- Issue #11432: A bug was introduced in subprocess.Popen on posix systems with
3.2.0 where the stdout or stderr file descriptor being the same as the stdin
file descriptor would raise an exception. webbrowser.open would fail. fixed.
......@@ -1555,8 +1553,6 @@ Extension Modules
signature. Without this, architectures where sizeof void* != sizeof int are
broken. Patch given by Hallvard B Furuseth.
- Issue #12221: Replace pyexpat.__version__ with the Python version.
- Issue #12051: Fix segfault in json.dumps() while encoding highly-nested
objects using the C accelerations.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment