diff options
Diffstat (limited to 'distutils2/tests')
29 files changed, 613 insertions, 435 deletions
diff --git a/distutils2/tests/__main__.py b/distutils2/tests/__main__.py index 3609c64..6ee5434 100644 --- a/distutils2/tests/__main__.py +++ b/distutils2/tests/__main__.py @@ -3,7 +3,6 @@ # Ripped from importlib tests, thanks Brett! import os -import sys from test.support import reap_children, reap_threads, run_unittest from distutils2.tests import unittest diff --git a/distutils2/tests/pypi_server.py b/distutils2/tests/pypi_server.py index 710e055..6e77e40 100644 --- a/distutils2/tests/pypi_server.py +++ b/distutils2/tests/pypi_server.py @@ -33,7 +33,6 @@ import os import queue import select import threading -import socketserver from functools import wraps from http.server import HTTPServer, SimpleHTTPRequestHandler from xmlrpc.server import SimpleXMLRPCServer @@ -103,7 +102,7 @@ class PyPIServer(threading.Thread): """ # we want to launch the server in a new dedicated thread, to not freeze # tests. - threading.Thread.__init__(self) + super(PyPIServer, self).__init__() self._run = True self._serve_xmlrpc = serve_xmlrpc if static_filesystem_paths is None: @@ -270,7 +269,7 @@ class PyPIRequestHandler(SimpleHTTPRequestHandler): class PyPIXMLRPCServer(SimpleXMLRPCServer): def server_bind(self): """Override server_bind to store the server name.""" - socketserver.TCPServer.server_bind(self) + super(PyPIXMLRPCServer, self).server_bind() host, port = self.socket.getsockname()[:2] self.server_port = port @@ -371,12 +370,13 @@ class MockDist: 'requires_python': self.requires_python, 'classifiers': [], 'name': self.name, - 'licence': self.licence, + 'licence': self.licence, # XXX licence or license? 'summary': self.summary, 'home_page': self.homepage, 'stable_version': self.stable_version, - 'provides_dist': self.provides_dist or "%s (%s)" % (self.name, - self.version), + # FIXME doesn't that reproduce the bug from 6527d3106e9f? + 'provides_dist': (self.provides_dist or + "%s (%s)" % (self.name, self.version)), 'requires': self.requires, 'cheesecake_installability_id': self.cheesecake_installability_id, } diff --git a/distutils2/tests/support.py b/distutils2/tests/support.py index 961780d..cacda42 100644 --- a/distutils2/tests/support.py +++ b/distutils2/tests/support.py @@ -36,7 +36,6 @@ import os import re import sys import errno -import codecs import shutil import logging import logging.handlers @@ -49,6 +48,9 @@ except ImportError: zlib = None from distutils2.dist import Distribution +from distutils2.util import resolve_name +from distutils2.command import set_command, _COMMANDS + from distutils2.tests import unittest from distutils2._backport import sysconfig @@ -57,11 +59,12 @@ __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_unless_symlink', + 'unittest', 'requires_zlib', 'skip_2to3_optimize', 'skip_unless_symlink', ] @@ -73,7 +76,7 @@ class _TestHandler(logging.handlers.BufferingHandler): # stolen and adapted from test.support def __init__(self): - logging.handlers.BufferingHandler.__init__(self, 0) + super(_TestHandler, self).__init__(0) self.setLevel(logging.DEBUG) def shouldFlush(self): @@ -90,10 +93,13 @@ class LoggingCatcher: configured to record all messages logged to the 'distutils2' logger. Use get_logs to retrieve messages and self.loghandler.flush to discard - them. get_logs automatically flushes the logs; if you test code that - generates logging messages but don't use get_logs, you have to flush - manually before doing other checks on logging message, otherwise you - will get irrelevant results. See example in test_command_check. + them. get_logs automatically flushes the logs, unless you pass + *flush=False*, for example to make multiple calls to the method with + different level arguments. If your test calls some code that generates + logging message and then you don't call get_logs, you will need to flush + manually before testing other code in the same test_* method, otherwise + get_logs in the next lines will see messages from the previous lines. + See example in test_command_check. """ def setUp(self): @@ -117,25 +123,23 @@ class LoggingCatcher: logger2to3.setLevel(self._old_levels[1]) super(LoggingCatcher, self).tearDown() - def get_logs(self, *levels): - """Return all log messages with level in *levels*. + def get_logs(self, level=logging.WARNING, flush=True): + """Return all log messages with given level. - Without explicit levels given, returns all messages. *levels* defaults - to all levels. For log calls with arguments (i.e. - logger.info('bla bla %r', arg)), the messages will be formatted before - being returned (e.g. "bla bla 'thing'"). + *level* defaults to logging.WARNING. - Returns a list. Automatically flushes the loghandler after being - called. + For log calls with arguments (i.e. logger.info('bla bla %r', arg)), + the messages will be formatted before being returned (e.g. "bla bla + 'thing'"). - Example: self.get_logs(logging.WARN, logging.DEBUG). + Returns a list. Automatically flushes the loghandler after being + called, unless *flush* is False (this is useful to get e.g. all + warnings then all info messages). """ - if not levels: - messages = [log.getMessage() for log in self.loghandler.buffer] - else: - messages = [log.getMessage() for log in self.loghandler.buffer - if log.levelno in levels] - self.loghandler.flush() + messages = [log.getMessage() for log in self.loghandler.buffer + if log.levelno == level] + if flush: + self.loghandler.flush() return messages @@ -254,7 +258,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): @@ -277,6 +281,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() @@ -287,6 +307,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): @@ -369,6 +398,10 @@ except ImportError: 'requires test.support.skip_unless_symlink') +skip_2to3_optimize = unittest.skipIf(sys.flags.optimize, + "2to3 doesn't work under -O") + + requires_zlib = unittest.skipUnless(zlib, 'requires zlib') diff --git a/distutils2/tests/test_command_bdist_dumb.py b/distutils2/tests/test_command_bdist_dumb.py index a31d14e..f77e279 100644 --- a/distutils2/tests/test_command_bdist_dumb.py +++ b/distutils2/tests/test_command_bdist_dumb.py @@ -1,6 +1,9 @@ """Tests for distutils.command.bdist_dumb.""" import os +import imp +import sys +import zipfile import distutils2.util from distutils2.dist import Distribution @@ -49,15 +52,27 @@ class BuildDumbTestCase(support.TempdirManager, # see what we have dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) - base = "%s.%s" % (dist.get_fullname(), cmd.plat_name) + base = "%s.%s.zip" % (dist.get_fullname(), cmd.plat_name) if os.name == 'os2': base = base.replace(':', '-') - wanted = ['%s.zip' % base] - self.assertEqual(dist_created, wanted) + self.assertEqual(dist_created, [base]) # now let's check what we have in the zip file - # XXX to be done + fp = zipfile.ZipFile(os.path.join('dist', base)) + try: + contents = fp.namelist() + finally: + fp.close + + if sys.version_info[1] == 1: + pyc = 'foo.pyc' + else: + pyc = 'foo.%s.pyc' % imp.get_tag() + contents = sorted(os.path.basename(fn) for fn in contents) + wanted = ['foo.py', pyc, + 'METADATA', 'INSTALLER', 'REQUESTED', 'RECORD'] + self.assertEqual(contents, sorted(wanted)) def test_finalize_options(self): pkg_dir, dist = self.create_dist() diff --git a/distutils2/tests/test_command_build_ext.py b/distutils2/tests/test_command_build_ext.py index 06b5992..b9f8cc2 100644 --- a/distutils2/tests/test_command_build_ext.py +++ b/distutils2/tests/test_command_build_ext.py @@ -1,9 +1,7 @@ import os import sys import site -import shutil import textwrap -from io import StringIO from distutils2.dist import Distribution from distutils2.errors import (UnknownFileError, CompileError, PackagingPlatformError) @@ -11,7 +9,7 @@ from distutils2.command.build_ext import build_ext from distutils2.compiler.extension import Extension from distutils2._backport import sysconfig -from distutils2.tests import support, unittest, verbose +from distutils2.tests import support, unittest from distutils2.tests.support import assert_python_ok @@ -38,18 +36,10 @@ class BuildExtTestCase(support.TempdirManager, support.fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir + cmd.ensure_finalized() + cmd.run() - 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) @@ -64,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) @@ -389,16 +380,8 @@ class BuildExtTestCase(support.TempdirManager, 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 - + cmd.ensure_finalized() + cmd.run() except CompileError: self.fail("Wrong deployment target during compilation") diff --git a/distutils2/tests/test_command_build_py.py b/distutils2/tests/test_command_build_py.py index fa152ec..4b6c6aa 100644 --- a/distutils2/tests/test_command_build_py.py +++ b/distutils2/tests/test_command_build_py.py @@ -55,30 +55,20 @@ class BuildPyTestCase(support.TempdirManager, # This makes sure the list of outputs includes byte-compiled # files for Python modules but not for package data files # (there shouldn't *be* byte-code files for those!). - # self.assertEqual(len(cmd.get_outputs()), 3) pkgdest = os.path.join(destination, "pkg") files = os.listdir(pkgdest) - pycache_dir = os.path.join(pkgdest, "__pycache__") self.assertIn("__init__.py", files) self.assertIn("README.txt", files) - if sys.dont_write_bytecode: - if sys.version_info[1] == 1: - self.assertNotIn("__init__.pyc", files) - else: - self.assertFalse(os.path.exists(pycache_dir)) + if sys.version_info[1] == 1: + self.assertIn("__init__.pyc", files) else: - # XXX even with -O, distutils2 writes pyc, not pyo; bug? - if sys.version_info[1] == 1: - self.assertIn("__init__.pyc", files) - else: - pyc_files = os.listdir(pycache_dir) - self.assertIn("__init__.%s.pyc" % imp.get_tag(), pyc_files) + pycache_dir = os.path.join(pkgdest, "__pycache__") + pyc_files = os.listdir(pycache_dir) + self.assertIn("__init__.%s.pyc" % imp.get_tag(), pyc_files) 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') @@ -89,40 +79,66 @@ class BuildPyTestCase(support.TempdirManager, open(os.path.join(testdir, "testfile"), "wb").close() os.chdir(sources) - old_stdout = sys.stdout - #sys.stdout = StringIO.StringIO() + dist = Distribution({"packages": ["pkg"], + "package_dir": sources, + "package_data": {"pkg": ["doc/*"]}}) + dist.script_args = ["build"] + dist.parse_command_line() try: - dist = Distribution({"packages": ["pkg"], - "package_dir": sources, - "package_data": {"pkg": ["doc/*"]}}) - dist.script_args = ["build"] - dist.parse_command_line() - - try: - 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 + dist.run_commands() + except PackagingFileError: + self.fail("failed package_data test when package_dir is ''") + + def test_byte_compile(self): + project_dir, dist = self.create_dist(py_modules=['boiledeggs']) + os.chdir(project_dir) + self.write_file('boiledeggs.py', 'import antigravity') + cmd = build_py(dist) + cmd.compile = True + cmd.build_lib = 'here' + cmd.finalize_options() + cmd.run() - def test_dont_write_bytecode(self): - # makes sure byte_compile is not used - pkg_dir, dist = self.create_dist() + found = os.listdir(cmd.build_lib) + if sys.version_info[1] == 1: + self.assertEqual(sorted(found), + ['boiledeggs.py', 'boiledeggs.pyc']) + else: + self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py']) + found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) + self.assertEqual(found, ['boiledeggs.%s.pyc' % imp.get_tag()]) + + def test_byte_compile_optimized(self): + project_dir, dist = self.create_dist(py_modules=['boiledeggs']) + os.chdir(project_dir) + self.write_file('boiledeggs.py', 'import antigravity') cmd = build_py(dist) cmd.compile = True cmd.optimize = 1 + cmd.build_lib = 'here' + cmd.finalize_options() + cmd.run() - old_dont_write_bytecode = sys.dont_write_bytecode + found = os.listdir(cmd.build_lib) + if sys.version_info[1] == 1: + self.assertEqual(sorted(found), ['boiledeggs.py', 'boiledeggs.pyc', + 'boiledeggs.pyo']) + else: + self.assertEqual(sorted(found), ['__pycache__', 'boiledeggs.py']) + found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) + self.assertEqual(sorted(found), + ['boiledeggs.%s.pyc' % imp.get_tag(), + 'boiledeggs.%s.pyo' % imp.get_tag()]) + + def test_byte_compile_under_B(self): + # make sure byte compilation works under -B (dont_write_bytecode) + self.addCleanup(setattr, sys, 'dont_write_bytecode', + sys.dont_write_bytecode) sys.dont_write_bytecode = True - try: - cmd.byte_compile([]) - finally: - sys.dont_write_bytecode = old_dont_write_bytecode + self.test_byte_compile() + self.test_byte_compile_optimized() - self.assertIn('byte-compiling is disabled', self.get_logs()[0]) def test_suite(): return unittest.makeSuite(BuildPyTestCase) diff --git a/distutils2/tests/test_command_check.py b/distutils2/tests/test_command_check.py index 638bdaf..e4413b3 100644 --- a/distutils2/tests/test_command_check.py +++ b/distutils2/tests/test_command_check.py @@ -1,6 +1,5 @@ """Tests for distutils.command.check.""" -import logging from distutils2.command.check import check from distutils2.metadata import _HAS_DOCUTILS from distutils2.errors import PackagingSetupError, MetadataMissingError @@ -27,11 +26,11 @@ class CheckTestCase(support.LoggingCatcher, # let's run the command with no metadata at all # by default, check is checking the metadata # should have some warnings - cmd = self._run() + self._run() # trick: using assertNotEqual with an empty list will give us a more # useful error message than assertGreater(.., 0) when the code change # and the test fails - self.assertNotEqual([], self.get_logs(logging.WARNING)) + self.assertNotEqual(self.get_logs(), []) # now let's add the required fields # and run it again, to make sure we don't get @@ -40,8 +39,8 @@ class CheckTestCase(support.LoggingCatcher, 'author_email': 'xxx', 'name': 'xxx', 'version': '4.2', } - cmd = self._run(metadata) - self.assertEqual([], self.get_logs(logging.WARNING)) + self._run(metadata) + self.assertEqual(self.get_logs(), []) # now with the strict mode, we should # get an error if there are missing metadata @@ -53,8 +52,8 @@ class CheckTestCase(support.LoggingCatcher, self.loghandler.flush() # and of course, no error when all metadata fields are present - cmd = self._run(metadata, strict=True) - self.assertEqual([], self.get_logs(logging.WARNING)) + self._run(metadata, strict=True) + self.assertEqual(self.get_logs(), []) # now a test with non-ASCII characters metadata = {'home_page': 'xxx', 'author': '\u00c9ric', @@ -62,15 +61,15 @@ class CheckTestCase(support.LoggingCatcher, 'version': '1.2', 'summary': 'Something about esszet \u00df', 'description': 'More things about esszet \u00df'} - cmd = self._run(metadata) - self.assertEqual([], self.get_logs(logging.WARNING)) + self._run(metadata) + self.assertEqual(self.get_logs(), []) def test_check_metadata_1_2(self): # let's run the command with no metadata at all # by default, check is checking the metadata # should have some warnings - cmd = self._run() - self.assertNotEqual([], self.get_logs(logging.WARNING)) + self._run() + self.assertNotEqual(self.get_logs(), []) # now let's add the required fields and run it again, to make sure we # don't get any warning anymore let's use requires_python as a marker @@ -80,8 +79,8 @@ class CheckTestCase(support.LoggingCatcher, 'name': 'xxx', 'version': '4.2', 'requires_python': '2.4', } - cmd = self._run(metadata) - self.assertEqual([], self.get_logs(logging.WARNING)) + self._run(metadata) + self.assertEqual(self.get_logs(), []) # now with the strict mode, we should # get an error if there are missing metadata @@ -99,8 +98,8 @@ class CheckTestCase(support.LoggingCatcher, # now with correct version format again metadata['version'] = '4.2' - cmd = self._run(metadata, strict=True) - self.assertEqual([], self.get_logs(logging.WARNING)) + self._run(metadata, strict=True) + self.assertEqual(self.get_logs(), []) @unittest.skipUnless(_HAS_DOCUTILS, "requires docutils") def test_check_restructuredtext(self): @@ -109,9 +108,7 @@ class CheckTestCase(support.LoggingCatcher, pkg_info, dist = self.create_dist(description=broken_rest) cmd = check(dist) cmd.check_restructuredtext() - self.assertEqual(len(self.get_logs(logging.WARNING)), 1) - # clear warnings from the previous call - self.loghandler.flush() + self.assertEqual(len(self.get_logs()), 1) # let's see if we have an error with strict=1 metadata = {'home_page': 'xxx', 'author': 'xxx', @@ -126,7 +123,7 @@ class CheckTestCase(support.LoggingCatcher, dist = self.create_dist(description='title\n=====\n\ntest \u00df')[1] cmd = check(dist) cmd.check_restructuredtext() - self.assertEqual([], self.get_logs(logging.WARNING)) + self.assertEqual(self.get_logs(), []) def test_check_all(self): self.assertRaises(PackagingSetupError, self._run, @@ -143,18 +140,18 @@ class CheckTestCase(support.LoggingCatcher, } cmd = check(dist) cmd.check_hooks_resolvable() - self.assertEqual(len(self.get_logs(logging.WARNING)), 1) + self.assertEqual(len(self.get_logs()), 1) def test_warn(self): _, dist = self.create_dist() cmd = check(dist) - self.assertEqual([], self.get_logs()) + self.assertEqual(self.get_logs(), []) cmd.warn('hello') - self.assertEqual(['check: hello'], self.get_logs()) + self.assertEqual(self.get_logs(), ['check: hello']) cmd.warn('hello %s', 'world') - self.assertEqual(['check: hello world'], self.get_logs()) + self.assertEqual(self.get_logs(), ['check: hello world']) cmd.warn('hello %s %s', 'beautiful', 'world') - self.assertEqual(['check: hello beautiful world'], self.get_logs()) + self.assertEqual(self.get_logs(), ['check: hello beautiful world']) def test_suite(): diff --git a/distutils2/tests/test_command_clean.py b/distutils2/tests/test_command_clean.py index 7b8effa..910628a 100644 --- a/distutils2/tests/test_command_clean.py +++ b/distutils2/tests/test_command_clean.py @@ -5,7 +5,8 @@ from distutils2.command.clean import clean from distutils2.tests import unittest, support -class cleanTestCase(support.TempdirManager, support.LoggingCatcher, +class CleanTestCase(support.TempdirManager, + support.LoggingCatcher, unittest.TestCase): def test_simple_run(self): @@ -23,7 +24,7 @@ class cleanTestCase(support.TempdirManager, support.LoggingCatcher, if name == 'build_base': continue for f in ('one', 'two', 'three'): - self.write_file(os.path.join(path, f)) + self.write_file((path, f)) # let's run the command cmd.all = True @@ -36,13 +37,11 @@ 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() def test_suite(): - return unittest.makeSuite(cleanTestCase) + return unittest.makeSuite(CleanTestCase) if __name__ == "__main__": unittest.main(defaultTest="test_suite") diff --git a/distutils2/tests/test_command_cmd.py b/distutils2/tests/test_command_cmd.py index 1b0f622..c29f0de 100644 --- a/distutils2/tests/test_command_cmd.py +++ b/distutils2/tests/test_command_cmd.py @@ -1,5 +1,6 @@ """Tests for distutils.cmd.""" import os +import logging from distutils2.command.cmd import Command from distutils2.dist import Distribution @@ -43,7 +44,7 @@ class CommandTestCase(support.LoggingCatcher, wanted = ["command options for 'MyCmd':", ' option1 = 1', ' option2 = 1'] - msgs = self.get_logs() + msgs = self.get_logs(logging.INFO) self.assertEqual(msgs, wanted) def test_ensure_string(self): diff --git a/distutils2/tests/test_command_install_data.py b/distutils2/tests/test_command_install_data.py index ba93cce..c169b87 100644 --- a/distutils2/tests/test_command_install_data.py +++ b/distutils2/tests/test_command_install_data.py @@ -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() @@ -125,22 +127,16 @@ class InstallDataTestCase(support.TempdirManager, # now the real test fn = os.path.join(install_dir, 'Spamlib-0.1.dist-info', 'RESOURCES') - fp = open(fn) - try: + with open(fn, encoding='utf-8') as fp: content = fp.read().strip() - finally: - fp.close() expected = 'spamd,%s' % os.path.join(scripts_dir, 'spamd') self.assertEqual(content, expected) # just to be sure, we also test that get_file works here, even though # packaging.database has its own test file - fp = distutils2.database.get_file('Spamlib', 'spamd') - try: + with distutils2.database.get_file('Spamlib', 'spamd') as fp: content = fp.read() - finally: - fp.close() self.assertEqual('# Python script', content) diff --git a/distutils2/tests/test_command_install_dist.py b/distutils2/tests/test_command_install_dist.py index c477299..597e10a 100644 --- a/distutils2/tests/test_command_install_dist.py +++ b/distutils2/tests/test_command_install_dist.py @@ -1,6 +1,7 @@ """Tests for distutils2.command.install.""" import os +import imp import sys from distutils2.command.build_ext import build_ext @@ -92,21 +93,20 @@ class InstallTestCase(support.TempdirManager, self.old_expand = os.path.expanduser os.path.expanduser = _expanduser - try: - # this is the actual test - self._test_user_site() - finally: + def cleanup(): _CONFIG_VARS['userbase'] = self.old_user_base _SCHEMES.set(scheme, 'purelib', self.old_user_site) os.path.expanduser = self.old_expand - def _test_user_site(self): + self.addCleanup(cleanup) + schemes = get_scheme_names() for key in ('nt_user', 'posix_user', 'os2_home'): self.assertIn(key, schemes) dist = Distribution({'name': 'xx'}) cmd = install_dist(dist) + # making sure the user option is there options = [name for name, short, lable in cmd.user_options] @@ -181,9 +181,11 @@ class InstallTestCase(support.TempdirManager, def test_old_record(self): # test pre-PEP 376 --record option (outside dist-info dir) install_dir = self.mkdtemp() - project_dir, dist = self.create_dist(scripts=['hello']) + project_dir, dist = self.create_dist(py_modules=['hello'], + scripts=['sayhi']) os.chdir(project_dir) - self.write_file('hello', "print('o hai')") + self.write_file('hello.py', "def main(): print('o hai')") + self.write_file('sayhi', 'from hello import main; main()') cmd = install_dist(dist) dist.command_obj['install_dist'] = cmd @@ -195,9 +197,14 @@ class InstallTestCase(support.TempdirManager, with open(cmd.record) as f: content = f.read() + if sys.version_info[1] == 1: + pyc = 'hello.pyc' + else: + pyc = 'hello.%s.pyc' % imp.get_tag() found = [os.path.basename(line) for line in content.splitlines()] - expected = ['hello', 'METADATA', 'INSTALLER', 'REQUESTED', 'RECORD'] - self.assertEqual(found, expected) + expected = ['hello.py', pyc, 'sayhi', + 'METADATA', 'INSTALLER', 'REQUESTED', 'RECORD'] + self.assertEqual(sorted(found), sorted(expected)) # XXX test that fancy_getopt is okay with options named # record and no-record but unrelated diff --git a/distutils2/tests/test_command_install_distinfo.py b/distutils2/tests/test_command_install_distinfo.py index 9898c2f..3985e0b 100644 --- a/distutils2/tests/test_command_install_distinfo.py +++ b/distutils2/tests/test_command_install_distinfo.py @@ -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() @@ -60,6 +60,7 @@ class InstallDistinfoTestCase(support.TempdirManager, ['METADATA', 'RECORD', 'REQUESTED', 'INSTALLER']) with open(os.path.join(dist_info, 'INSTALLER')) as fp: self.assertEqual(fp.read(), 'distutils') + with open(os.path.join(dist_info, 'REQUESTED')) as fp: self.assertEqual(fp.read(), '') meta_path = os.path.join(dist_info, 'METADATA') @@ -76,7 +77,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 +97,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 +117,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 +215,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() diff --git a/distutils2/tests/test_command_install_lib.py b/distutils2/tests/test_command_install_lib.py index 78b539c..160e62e 100644 --- a/distutils2/tests/test_command_install_lib.py +++ b/distutils2/tests/test_command_install_lib.py @@ -17,7 +17,7 @@ class InstallLibTestCase(support.TempdirManager, restore_environ = ['PYTHONPATH'] def test_finalize_options(self): - pkg_dir, dist = self.create_dist() + dist = self.create_dist()[1] cmd = install_lib(dist) cmd.finalize_options() @@ -34,75 +34,77 @@ class InstallLibTestCase(support.TempdirManager, cmd.finalize_options() self.assertEqual(cmd.optimize, 2) - @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled') def test_byte_compile(self): - pkg_dir, dist = self.create_dist() - os.chdir(pkg_dir) + project_dir, dist = self.create_dist() + os.chdir(project_dir) cmd = install_lib(dist) cmd.compile = True cmd.optimize = 1 - f = os.path.join(pkg_dir, 'foo.py') + f = os.path.join(project_dir, 'foo.py') self.write_file(f, '# python file') cmd.byte_compile([f]) if sys.version_info[1] == 1: pyc_file = 'foo.pyc' pyo_file = 'foo.pyo' else: - pyc_file = imp.cache_from_source('foo.py') - pyo_file = imp.cache_from_source('foo.py', debug_override=False) + pyc_file = imp.cache_from_source('foo.py', True) + pyo_file = imp.cache_from_source('foo.py', False) self.assertTrue(os.path.exists(pyc_file)) self.assertTrue(os.path.exists(pyo_file)) + def test_byte_compile_under_B(self): + # make sure byte compilation works under -B (dont_write_bytecode) + self.addCleanup(setattr, sys, 'dont_write_bytecode', + sys.dont_write_bytecode) + sys.dont_write_bytecode = True + self.test_byte_compile() + def test_get_outputs(self): - pkg_dir, dist = self.create_dist() + project_dir, dist = self.create_dist() + os.chdir(project_dir) + os.mkdir('spam') cmd = install_lib(dist) # setting up a dist environment cmd.compile = True cmd.optimize = 1 - cmd.install_dir = pkg_dir - f = os.path.join(pkg_dir, '__init__.py') + cmd.install_dir = self.mkdtemp() + f = os.path.join(project_dir, 'spam', '__init__.py') self.write_file(f, '# python package') cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] - cmd.distribution.packages = [pkg_dir] + cmd.distribution.packages = ['spam'] - # make sure the build_lib is set the temp dir - build_dir = os.path.split(pkg_dir)[0] + # make sure the build_lib is set the temp dir # XXX what? this is not + # needed in the same distutils test and should work without manual + # intervention + build_dir = os.path.split(project_dir)[0] cmd.get_finalized_command('build_py').build_lib = build_dir - # get_output should return 4 elements - self.assertEqual(len(cmd.get_outputs()), 4) + # get_outputs should return 4 elements: spam/__init__.py, .pyc and + # .pyo, foo*.so / foo.pyd + outputs = cmd.get_outputs() + self.assertEqual(len(outputs), 4, outputs) def test_get_inputs(self): - pkg_dir, dist = self.create_dist() + project_dir, dist = self.create_dist() + os.chdir(project_dir) + os.mkdir('spam') cmd = install_lib(dist) # setting up a dist environment cmd.compile = True cmd.optimize = 1 - cmd.install_dir = pkg_dir - f = os.path.join(pkg_dir, '__init__.py') + cmd.install_dir = self.mkdtemp() + f = os.path.join(project_dir, 'spam', '__init__.py') self.write_file(f, '# python package') cmd.distribution.ext_modules = [Extension('foo', ['xxx'])] - cmd.distribution.packages = [pkg_dir] - - # get_input should return 2 elements - self.assertEqual(len(cmd.get_inputs()), 2) - - def test_dont_write_bytecode(self): - # makes sure byte_compile is not used - pkg_dir, dist = self.create_dist() - cmd = install_lib(dist) - cmd.compile = True - cmd.optimize = 1 - - self.addCleanup(setattr, sys, 'dont_write_bytecode', - sys.dont_write_bytecode) - sys.dont_write_bytecode = True - cmd.byte_compile([]) + cmd.distribution.packages = ['spam'] - self.assertIn('byte-compiling is disabled', self.get_logs()[0]) + # get_inputs should return 2 elements: spam/__init__.py and + # foo*.so / foo.pyd + inputs = cmd.get_inputs() + self.assertEqual(len(inputs), 2, inputs) def test_suite(): diff --git a/distutils2/tests/test_command_register.py b/distutils2/tests/test_command_register.py index 2cc9f70..4e6c1de 100644 --- a/distutils2/tests/test_command_register.py +++ b/distutils2/tests/test_command_register.py @@ -12,6 +12,7 @@ except ImportError: DOCUTILS_SUPPORT = False from distutils2.tests import unittest, support +from distutils2.tests.support import Inputs from distutils2.command import register as register_module from distutils2.command.register import register from distutils2.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() @@ -200,12 +189,10 @@ class RegisterTestCase(support.TempdirManager, @unittest.skipUnless(DOCUTILS_SUPPORT, 'needs docutils') def test_strict(self): - # testing the script option - # when on, the register command stops if - # the metadata is incomplete or if - # long_description is not reSt compliant + # testing the strict option: when on, the register command stops if the + # metadata is incomplete or if description contains bad reST - # empty metadata + # empty metadata # XXX this is not really empty.. cmd = self._get_cmd({'name': 'xxx', 'version': 'xxx'}) cmd.ensure_finalized() cmd.strict = True @@ -213,16 +200,15 @@ class RegisterTestCase(support.TempdirManager, register_module.input = inputs self.assertRaises(PackagingSetupError, cmd.run) - # metadata is OK but long_description is broken + # metadata is OK but description is broken metadata = {'home_page': 'xxx', 'author': 'xxx', 'author_email': 'éxéxé', - 'name': 'xxx', 'version': 'xxx', + 'name': 'xxx', 'version': '4.2', 'description': 'title\n==\n\ntext'} cmd = self._get_cmd(metadata) cmd.ensure_finalized() cmd.strict = True - self.assertRaises(PackagingSetupError, cmd.run) # now something that works diff --git a/distutils2/tests/test_command_sdist.py b/distutils2/tests/test_command_sdist.py index 9bf1fcf..0df3728 100644 --- a/distutils2/tests/test_command_sdist.py +++ b/distutils2/tests/test_command_sdist.py @@ -1,9 +1,6 @@ """Tests for distutils2.command.sdist.""" import os import zipfile -import logging - -from distutils2.tests.support import requires_zlib try: import grp @@ -13,17 +10,17 @@ except ImportError: UID_GID_SUPPORT = False from os.path import join -from distutils2.tests import captured_stdout -from distutils2.command.sdist import sdist -from distutils2.command.sdist import show_formats from distutils2.dist import Distribution -from distutils2.tests import unittest -from distutils2.errors import PackagingOptionError from distutils2.util import find_executable -from distutils2.tests import support +from distutils2.errors import PackagingOptionError +from distutils2.command.sdist import sdist, show_formats from distutils2._backport import tarfile from distutils2._backport.shutil import get_archive_formats +from distutils2.tests import support, unittest +from distutils2.tests import captured_stdout +from distutils2.tests.support import requires_zlib + MANIFEST = """\ # file GENERATED by distutils2, do NOT edit @@ -89,7 +86,6 @@ class SDistTestCase(support.TempdirManager, # creating VCS directories with some files in them os.mkdir(join(self.tmp_dir, 'somecode', '.svn')) - self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx') os.mkdir(join(self.tmp_dir, 'somecode', '.hg')) @@ -147,7 +143,7 @@ class SDistTestCase(support.TempdirManager, # now trying a tar then a gztar cmd.formats = ['tar', 'gztar'] - + cmd.finalized = False cmd.ensure_finalized() cmd.run() @@ -223,12 +219,14 @@ class SDistTestCase(support.TempdirManager, # testing the `check-metadata` option dist, cmd = self.get_cmd(metadata={'name': 'xxx', 'version': 'xxx'}) - # this should raise some warnings - # with the check subcommand + # this should cause the check subcommand to log two warnings: + # version is invalid, home-page and author are missing cmd.ensure_finalized() cmd.run() - warnings = self.get_logs(logging.WARN) - self.assertEqual(len(warnings), 4) + warnings = self.get_logs() + check_warnings = [msg for msg in warnings if + not msg.startswith('sdist:')] + self.assertEqual(len(check_warnings), 2, warnings) # trying with a complete set of metadata self.loghandler.flush() @@ -236,13 +234,10 @@ class SDistTestCase(support.TempdirManager, cmd.ensure_finalized() cmd.metadata_check = False cmd.run() - warnings = self.get_logs(logging.WARN) - # removing manifest generated warnings - warnings = [warn for warn in warnings if - not warn.endswith('-- skipping')] - # the remaining warnings are about the use of the default file list and - # the absence of setup.cfg + warnings = self.get_logs() self.assertEqual(len(warnings), 2) + self.assertIn('using default file list', warnings[0]) + self.assertIn("'setup.cfg' file not found", warnings[1]) def test_show_formats(self): __, stdout = captured_stdout(show_formats) @@ -254,7 +249,6 @@ class SDistTestCase(support.TempdirManager, self.assertEqual(len(output), num_formats) def test_finalize_options(self): - dist, cmd = self.get_cmd() cmd.finalize_options() @@ -274,6 +268,18 @@ class SDistTestCase(support.TempdirManager, self.assertRaises(PackagingOptionError, cmd.finalize_options) @requires_zlib + def test_template(self): + dist, cmd = self.get_cmd() + dist.extra_files = ['include yeah'] + cmd.ensure_finalized() + self.write_file((self.tmp_dir, 'yeah'), 'xxx') + cmd.run() + with open(cmd.manifest) as f: + content = f.read() + + self.assertIn('yeah', content) + + @requires_zlib @unittest.skipUnless(UID_GID_SUPPORT, "requires grp and pwd support") @unittest.skipIf(find_executable('tar') is None or find_executable('gzip') is None, @@ -291,13 +297,10 @@ class SDistTestCase(support.TempdirManager, # making sure we have the good rights archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') - archive = tarfile.open(archive_name) - try: + with tarfile.open(archive_name) as archive: for member in archive.getmembers(): self.assertEqual(member.uid, 0) self.assertEqual(member.gid, 0) - finally: - archive.close() # building a sdist again dist, cmd = self.get_cmd() @@ -309,15 +312,12 @@ class SDistTestCase(support.TempdirManager, # making sure we have the good rights archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') - archive = tarfile.open(archive_name) - try: + with tarfile.open(archive_name) as archive: # note that we are not testing the group ownership here # because, depending on the platforms and the container # rights (see #7408) for member in archive.getmembers(): self.assertEqual(member.uid, os.getuid()) - finally: - archive.close() @requires_zlib def test_get_file_list(self): @@ -383,18 +383,6 @@ class SDistTestCase(support.TempdirManager, self.assertEqual(manifest, ['README.manual']) @requires_zlib - def test_template(self): - dist, cmd = self.get_cmd() - dist.extra_files = ['include yeah'] - cmd.ensure_finalized() - self.write_file((self.tmp_dir, 'yeah'), 'xxx') - cmd.run() - with open(cmd.manifest) as f: - content = f.read() - - self.assertIn('yeah', content) - - @requires_zlib def test_manifest_builder(self): dist, cmd = self.get_cmd() cmd.manifest_builders = 'distutils2.tests.test_command_sdist.builder' diff --git a/distutils2/tests/test_command_test.py b/distutils2/tests/test_command_test.py index 9fb6fb9..f2dcd22 100644 --- a/distutils2/tests/test_command_test.py +++ b/distutils2/tests/test_command_test.py @@ -2,7 +2,6 @@ import os import re import sys import shutil -import logging import unittest as ut1 import distutils2.database @@ -140,7 +139,8 @@ class TestTest(TempdirManager, cmd.run() self.assertEqual(['build has run'], record) - def _test_works_with_2to3(self): + @unittest.skip('needs to be written') + def test_works_with_2to3(self): pass def test_checks_requires(self): @@ -149,7 +149,7 @@ class TestTest(TempdirManager, phony_project = 'ohno_ohno-impossible_1234-name_stop-that!' cmd.tests_require = [phony_project] cmd.ensure_finalized() - logs = self.get_logs(logging.WARNING) + logs = self.get_logs() self.assertIn(phony_project, logs[-1]) def prepare_a_module(self): diff --git a/distutils2/tests/test_command_upload.py b/distutils2/tests/test_command_upload.py index 5c58879..61c6654 100644 --- a/distutils2/tests/test_command_upload.py +++ b/distutils2/tests/test_command_upload.py @@ -129,7 +129,7 @@ class UploadTestCase(support.TempdirManager, support.EnvironRestorer, dist_files = [(command, pyversion, filename)] docs_path = os.path.join(self.tmp_dir, "build", "docs") os.makedirs(docs_path) - self.write_file(os.path.join(docs_path, "index.html"), "yellow") + self.write_file((docs_path, "index.html"), "yellow") self.write_file(self.rc, PYPIRC) # let's run it diff --git a/distutils2/tests/test_command_upload_docs.py b/distutils2/tests/test_command_upload_docs.py index cf69af9..95eec0c 100644 --- a/distutils2/tests/test_command_upload_docs.py +++ b/distutils2/tests/test_command_upload_docs.py @@ -1,6 +1,7 @@ """Tests for distutils2.command.upload_docs.""" import os import shutil +import logging import zipfile try: import _ssl @@ -70,9 +71,8 @@ class UploadDocsTestCase(support.TempdirManager, if sample_dir is None: sample_dir = self.mkdtemp() os.mkdir(os.path.join(sample_dir, "docs")) - self.write_file(os.path.join(sample_dir, "docs", "index.html"), - "Ce mortel ennui") - self.write_file(os.path.join(sample_dir, "index.html"), "Oh la la") + self.write_file((sample_dir, "docs", "index.html"), "Ce mortel ennui") + self.write_file((sample_dir, "index.html"), "Oh la la") return sample_dir def test_zip_dir(self): @@ -141,13 +141,16 @@ class UploadDocsTestCase(support.TempdirManager, self.pypi.default_response_status = '403 Forbidden' self.prepare_command() self.cmd.run() - self.assertIn('Upload failed (403): Forbidden', self.get_logs()[-1]) + errors = self.get_logs(logging.ERROR) + self.assertEqual(len(errors), 1) + self.assertIn('Upload failed (403): Forbidden', errors[0]) self.pypi.default_response_status = '301 Moved Permanently' self.pypi.default_response_headers.append( ("Location", "brand_new_location")) self.cmd.run() - self.assertIn('brand_new_location', self.get_logs()[-1]) + lastlog = self.get_logs(logging.INFO)[-1] + self.assertIn('brand_new_location', lastlog) def test_reads_pypirc_data(self): self.write_file(self.rc, PYPIRC % self.pypi.full_address) @@ -171,7 +174,7 @@ class UploadDocsTestCase(support.TempdirManager, self.prepare_command() self.cmd.show_response = True self.cmd.run() - record = self.get_logs()[-1] + record = self.get_logs(logging.INFO)[-1] self.assertTrue(record, "should report the response") self.assertIn(self.pypi.default_response_data, record) diff --git a/distutils2/tests/test_config.py b/distutils2/tests/test_config.py index 7c913ee..dc61daa 100644 --- a/distutils2/tests/test_config.py +++ b/distutils2/tests/test_config.py @@ -1,8 +1,6 @@ """Tests for distutils2.config.""" import os import sys -import logging -from io import StringIO from distutils2 import command from distutils2.dist import Distribution @@ -184,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 @@ -210,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': 'distutils2.tests.test_config.version_hook'} @@ -375,15 +364,14 @@ class ConfigTestCase(support.TempdirManager, self.write_file('README', 'yeah') self.write_file('hooks.py', HOOKS_MODULE) self.get_dist() - logs = self.get_logs(logging.WARNING) - self.assertEqual(['logging_hook called'], logs) + self.assertEqual(['logging_hook called'], self.get_logs()) 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(logging.WARNING) + logs = self.get_logs() self.assertEqual(1, len(logs)) self.assertIn('cannot find setup hook', logs[0]) @@ -397,7 +385,7 @@ class ConfigTestCase(support.TempdirManager, dist = self.get_dist() self.assertEqual(['haven', 'first', 'third'], dist.py_modules) - logs = self.get_logs(logging.WARNING) + logs = self.get_logs() self.assertEqual(1, len(logs)) self.assertIn('cannot find setup hook', logs[0]) @@ -493,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(): diff --git a/distutils2/tests/test_create.py b/distutils2/tests/test_create.py index 7a0aa0d..83d2f50 100644 --- a/distutils2/tests/test_create.py +++ b/distutils2/tests/test_create.py @@ -1,16 +1,18 @@ """Tests for distutils2.create.""" import os import sys -from io import StringIO from textwrap import dedent +from distutils2 import create from distutils2.create import MainProgram, ask_yn, ask, main from distutils2._backport import sysconfig from distutils2.tests import support, unittest +from distutils2.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']) @@ -80,8 +72,7 @@ class CreateTestCase(support.TempdirManager, os.mkdir(os.path.join(tempdir, dir_)) for file_ in files: - path = os.path.join(tempdir, file_) - self.write_file(path, 'xxx') + self.write_file((tempdir, file_), 'xxx') mainprogram._find_files() mainprogram.data['packages'].sort() @@ -131,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') @@ -207,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') diff --git a/distutils2/tests/test_dist.py b/distutils2/tests/test_dist.py index 22fd37b..1e9eb9c 100644 --- a/distutils2/tests/test_dist.py +++ b/distutils2/tests/test_dist.py @@ -1,33 +1,37 @@ """Tests for distutils2.dist.""" import os import sys -import logging import textwrap import distutils2.dist from distutils2.dist import Distribution -from distutils2.command import set_command from distutils2.command.cmd import Command from distutils2.errors import PackagingModuleError, PackagingOptionError from distutils2.tests import captured_stdout from distutils2.tests import support, unittest -from distutils2.tests.support import create_distribution +from distutils2.tests.support import create_distribution, use_command from distutils2.tests.support import unload class test_dist(Command): - """Sample distutils2 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): + self._record.append('test_dist has run') class DistributionTestCase(support.TempdirManager, @@ -39,6 +43,8 @@ class DistributionTestCase(support.TempdirManager, def setUp(self): super(DistributionTestCase, self).setUp() + # XXX this is ugly, we should fix the functions to accept args + # (defaulting to sys.argv) self.argv = sys.argv, sys.argv[:] del sys.argv[1:] @@ -74,7 +80,7 @@ class DistributionTestCase(support.TempdirManager, 'version': '1.2', 'home_page': 'xxxx', 'badoptname': 'xxx'}) - logs = self.get_logs(logging.WARNING) + logs = self.get_logs() self.assertEqual(len(logs), 1) self.assertIn('unknown argument', logs[0]) @@ -85,7 +91,7 @@ class DistributionTestCase(support.TempdirManager, 'version': '1.2', 'home_page': 'xxxx', 'options': {}}) - self.assertEqual([], self.get_logs(logging.WARNING)) + self.assertEqual(self.get_logs(), []) self.assertNotIn('options', dir(dist)) def test_non_empty_options(self): @@ -173,7 +179,8 @@ class DistributionTestCase(support.TempdirManager, self.write_file((temp_home, "config2.cfg"), '[test_dist]\npre-hook.b = type') - set_command('distutils2.tests.test_dist.test_dist') + use_command(self, 'distutils2.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'}) @@ -201,7 +208,7 @@ class DistributionTestCase(support.TempdirManager, record.append('post-%s' % cmd.get_command_name()) ''')) - set_command('distutils2.tests.test_dist.test_dist') + use_command(self, 'distutils2.tests.test_dist.test_dist') d = create_distribution([config_file]) cmd = d.get_command_obj("test_dist") @@ -228,7 +235,7 @@ class DistributionTestCase(support.TempdirManager, [test_dist] pre-hook.test = nonexistent.dotted.name''')) - set_command('distutils2.tests.test_dist.test_dist') + use_command(self, 'distutils2.tests.test_dist.test_dist') d = create_distribution([config_file]) cmd = d.get_command_obj("test_dist") cmd.ensure_finalized() @@ -243,7 +250,7 @@ class DistributionTestCase(support.TempdirManager, [test_dist] pre-hook.test = distutils2.tests.test_dist.__doc__''')) - set_command('distutils2.tests.test_dist.test_dist') + use_command(self, 'distutils2.tests.test_dist.test_dist') d = create_distribution([config_file]) cmd = d.get_command_obj("test_dist") cmd.ensure_finalized() diff --git a/distutils2/tests/test_manifest.py b/distutils2/tests/test_manifest.py index 24f0510..e829fa4 100644 --- a/distutils2/tests/test_manifest.py +++ b/distutils2/tests/test_manifest.py @@ -1,8 +1,9 @@ """Tests for distutils2.manifest.""" import os -import logging +import re from io import StringIO -from distutils2.manifest import Manifest +from distutils2.errors import PackagingTemplateError +from distutils2.manifest import Manifest, _translate_pattern, _glob_to_re from distutils2.tests import unittest, support @@ -26,13 +27,11 @@ class ManifestTestCase(support.TempdirManager, support.LoggingCatcher, unittest.TestCase): - def setUp(self): - super(ManifestTestCase, self).setUp() - self.cwd = os.getcwd() + def assertNoWarnings(self): + self.assertEqual(self.get_logs(), []) - def tearDown(self): - os.chdir(self.cwd) - super(ManifestTestCase, self).tearDown() + def assertWarnings(self): + self.assertNotEqual(self.get_logs(), []) def test_manifest_reader(self): tmpdir = self.mkdtemp() @@ -43,7 +42,7 @@ class ManifestTestCase(support.TempdirManager, manifest = Manifest() manifest.read_template(MANIFEST) - warnings = self.get_logs(logging.WARNING) + warnings = self.get_logs() # the manifest should have been read and 3 warnings issued # (we didn't provide the files) self.assertEqual(3, len(warnings)) @@ -69,6 +68,193 @@ class ManifestTestCase(support.TempdirManager, manifest.read_template(content) self.assertEqual(['README', 'file1'], manifest.files) + def test_glob_to_re(self): + # simple cases + self.assertEqual(_glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)') + self.assertEqual(_glob_to_re('foo?'), 'foo[^/]\\Z(?ms)') + self.assertEqual(_glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)') + + # special cases + self.assertEqual(_glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)') + self.assertEqual(_glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)') + self.assertEqual(_glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)') + self.assertEqual(_glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)') + + def test_remove_duplicates(self): + manifest = Manifest() + manifest.files = ['a', 'b', 'a', 'g', 'c', 'g'] + # files must be sorted beforehand + manifest.sort() + manifest.remove_duplicates() + self.assertEqual(manifest.files, ['a', 'b', 'c', 'g']) + + def test_translate_pattern(self): + # blackbox test of a private function + + # not regex + pattern = _translate_pattern('a', anchor=True, is_regex=False) + self.assertTrue(hasattr(pattern, 'search')) + + # is a regex + regex = re.compile('a') + pattern = _translate_pattern(regex, anchor=True, is_regex=True) + self.assertEqual(pattern, regex) + + # plain string flagged as regex + pattern = _translate_pattern('a', anchor=True, is_regex=True) + self.assertTrue(hasattr(pattern, 'search')) + + # glob support + pattern = _translate_pattern('*.py', anchor=True, is_regex=False) + self.assertTrue(pattern.search('filelist.py')) + + def test_exclude_pattern(self): + # return False if no match + manifest = Manifest() + self.assertFalse(manifest.exclude_pattern('*.py')) + + # return True if files match + manifest = Manifest() + manifest.files = ['a.py', 'b.py'] + self.assertTrue(manifest.exclude_pattern('*.py')) + + # test excludes + manifest = Manifest() + manifest.files = ['a.py', 'a.txt'] + manifest.exclude_pattern('*.py') + self.assertEqual(manifest.files, ['a.txt']) + + def test_include_pattern(self): + # return False if no match + manifest = Manifest() + manifest.allfiles = [] + self.assertFalse(manifest._include_pattern('*.py')) + + # return True if files match + manifest = Manifest() + manifest.allfiles = ['a.py', 'b.txt'] + self.assertTrue(manifest._include_pattern('*.py')) + + # test * matches all files + manifest = Manifest() + self.assertIsNone(manifest.allfiles) + manifest.allfiles = ['a.py', 'b.txt'] + manifest._include_pattern('*') + self.assertEqual(manifest.allfiles, ['a.py', 'b.txt']) + + def test_process_template(self): + # invalid lines + manifest = Manifest() + for action in ('include', 'exclude', 'global-include', + 'global-exclude', 'recursive-include', + 'recursive-exclude', 'graft', 'prune'): + self.assertRaises(PackagingTemplateError, + manifest._process_template_line, action) + + # implicit include + manifest = Manifest() + manifest.allfiles = ['a.py', 'b.txt', 'd/c.py'] + + manifest._process_template_line('*.py') + self.assertEqual(manifest.files, ['a.py']) + self.assertNoWarnings() + + # include + manifest = Manifest() + manifest.allfiles = ['a.py', 'b.txt', 'd/c.py'] + + manifest._process_template_line('include *.py') + self.assertEqual(manifest.files, ['a.py']) + self.assertNoWarnings() + + manifest._process_template_line('include *.rb') + self.assertEqual(manifest.files, ['a.py']) + self.assertWarnings() + + # exclude + manifest = Manifest() + manifest.files = ['a.py', 'b.txt', 'd/c.py'] + + manifest._process_template_line('exclude *.py') + self.assertEqual(manifest.files, ['b.txt', 'd/c.py']) + self.assertNoWarnings() + + manifest._process_template_line('exclude *.rb') + self.assertEqual(manifest.files, ['b.txt', 'd/c.py']) + self.assertWarnings() + + # global-include + manifest = Manifest() + manifest.allfiles = ['a.py', 'b.txt', 'd/c.py'] + + manifest._process_template_line('global-include *.py') + self.assertEqual(manifest.files, ['a.py', 'd/c.py']) + self.assertNoWarnings() + + manifest._process_template_line('global-include *.rb') + self.assertEqual(manifest.files, ['a.py', 'd/c.py']) + self.assertWarnings() + + # global-exclude + manifest = Manifest() + manifest.files = ['a.py', 'b.txt', 'd/c.py'] + + manifest._process_template_line('global-exclude *.py') + self.assertEqual(manifest.files, ['b.txt']) + self.assertNoWarnings() + + manifest._process_template_line('global-exclude *.rb') + self.assertEqual(manifest.files, ['b.txt']) + self.assertWarnings() + + # recursive-include + manifest = Manifest() + manifest.allfiles = ['a.py', 'd/b.py', 'd/c.txt', 'd/d/e.py'] + + manifest._process_template_line('recursive-include d *.py') + self.assertEqual(manifest.files, ['d/b.py', 'd/d/e.py']) + self.assertNoWarnings() + + manifest._process_template_line('recursive-include e *.py') + self.assertEqual(manifest.files, ['d/b.py', 'd/d/e.py']) + self.assertWarnings() + + # recursive-exclude + manifest = Manifest() + manifest.files = ['a.py', 'd/b.py', 'd/c.txt', 'd/d/e.py'] + + manifest._process_template_line('recursive-exclude d *.py') + self.assertEqual(manifest.files, ['a.py', 'd/c.txt']) + self.assertNoWarnings() + + manifest._process_template_line('recursive-exclude e *.py') + self.assertEqual(manifest.files, ['a.py', 'd/c.txt']) + self.assertWarnings() + + # graft + manifest = Manifest() + manifest.allfiles = ['a.py', 'd/b.py', 'd/d/e.py', 'f/f.py'] + + manifest._process_template_line('graft d') + self.assertEqual(manifest.files, ['d/b.py', 'd/d/e.py']) + self.assertNoWarnings() + + manifest._process_template_line('graft e') + self.assertEqual(manifest.files, ['d/b.py', 'd/d/e.py']) + self.assertWarnings() + + # prune + manifest = Manifest() + manifest.files = ['a.py', 'd/b.py', 'd/d/e.py', 'f/f.py'] + + manifest._process_template_line('prune d') + self.assertEqual(manifest.files, ['a.py', 'f/f.py']) + self.assertNoWarnings() + + manifest._process_template_line('prune e') + self.assertEqual(manifest.files, ['a.py', 'f/f.py']) + self.assertWarnings() + def test_suite(): return unittest.makeSuite(ManifestTestCase) diff --git a/distutils2/tests/test_metadata.py b/distutils2/tests/test_metadata.py index 82f5212..e19af0d 100644 --- a/distutils2/tests/test_metadata.py +++ b/distutils2/tests/test_metadata.py @@ -1,7 +1,6 @@ """Tests for distutils2.metadata.""" import os import sys -import logging from textwrap import dedent from io import StringIO @@ -302,7 +301,7 @@ class MetadataTestCase(LoggingCatcher, 'name': 'xxx', 'version': 'xxx', 'home_page': 'xxxx'}) - logs = self.get_logs(logging.WARNING) + logs = self.get_logs() self.assertEqual(1, len(logs)) self.assertIn('not a valid version', logs[0]) @@ -418,7 +417,7 @@ class MetadataTestCase(LoggingCatcher, # XXX check PEP and see if 3 == 3.0 metadata['Requires-Python'] = '>=2.6, <3.0' metadata['Requires-Dist'] = ['Foo (>=2.6, <3.0)'] - self.assertEqual([], self.get_logs(logging.WARNING)) + self.assertEqual(self.get_logs(), []) @unittest.skip('needs to be implemented') def test_requires_illegal(self): diff --git a/distutils2/tests/test_mixin2to3.py b/distutils2/tests/test_mixin2to3.py index 4d1584b..76e14d6 100644 --- a/distutils2/tests/test_mixin2to3.py +++ b/distutils2/tests/test_mixin2to3.py @@ -1,4 +1,3 @@ -import sys import textwrap from distutils2.tests import unittest, support @@ -9,6 +8,7 @@ class Mixin2to3TestCase(support.TempdirManager, support.LoggingCatcher, unittest.TestCase): + @support.skip_2to3_optimize def test_convert_code_only(self): # used to check if code gets converted properly. code = "print 'test'" diff --git a/distutils2/tests/test_pypi_simple.py b/distutils2/tests/test_pypi_simple.py index c587701..70c3ba3 100644 --- a/distutils2/tests/test_pypi_simple.py +++ b/distutils2/tests/test_pypi_simple.py @@ -87,7 +87,7 @@ class SimpleCrawlerTestCase(TempdirManager, try: crawler._open_url(url) except Exception as v: - if sys.version_info[:2] < (3, 3): + if sys.version_info[:2] < (3, 2, 3): wanted = 'nonnumeric port' else: wanted = 'Download error' diff --git a/distutils2/tests/test_run.py b/distutils2/tests/test_run.py index 8645f63..7433731 100644 --- a/distutils2/tests/test_run.py +++ b/distutils2/tests/test_run.py @@ -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() @@ -67,7 +65,7 @@ class RunTestCase(support.TempdirManager, pythonpath = os.environ.get('PYTHONPATH') d2parent = os.path.dirname(os.path.dirname(__file__)) if pythonpath is not None: - pythonpath = os.pathsep.join((pythonpath, d2parent)) + pythonpath = os.pathsep.join((pythonpath, d2parent)) else: pythonpath = d2parent diff --git a/distutils2/tests/test_uninstall.py b/distutils2/tests/test_uninstall.py index fc664a3..4b66f03 100644 --- a/distutils2/tests/test_uninstall.py +++ b/distutils2/tests/test_uninstall.py @@ -1,6 +1,5 @@ """Tests for the distutils2.uninstall module.""" import os -import sys import logging import distutils2.util @@ -31,19 +30,10 @@ 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() + self.addCleanup(distutils2.util._path_created.clear) disable_cache() - def tearDown(self): - os.chdir(self.cwd) - distutils2.util._path_created.clear() - super(UninstallTestCase, self).tearDown() - def get_path(self, dist, name): # the dist argument must contain an install_dist command correctly # initialized with a prefix option and finalized befored this method @@ -61,8 +51,7 @@ class UninstallTestCase(support.TempdirManager, kw['pkg'] = pkg pkg_dir = os.path.join(project_dir, pkg) - os.mkdir(pkg_dir) - os.mkdir(os.path.join(pkg_dir, 'sub')) + os.makedirs(os.path.join(pkg_dir, 'sub')) self.write_file((project_dir, 'setup.cfg'), SETUP_CFG % kw) self.write_file((pkg_dir, '__init__.py'), '#') @@ -85,7 +74,7 @@ class UninstallTestCase(support.TempdirManager, dist.parse_config_files() dist.finalize_options() dist.run_command('install_dist', - {'prefix': ('command line', self.root_dir)}) + {'prefix': ('command line', self.mkdtemp())}) site_packages = self.get_path(dist, 'purelib') return dist, site_packages diff --git a/distutils2/tests/test_util.py b/distutils2/tests/test_util.py index f3432ab..0edb402 100644 --- a/distutils2/tests/test_util.py +++ b/distutils2/tests/test_util.py @@ -10,7 +10,7 @@ import subprocess from io import StringIO from distutils2.errors import ( - PackagingPlatformError, PackagingByteCompileError, PackagingFileError, + PackagingPlatformError, PackagingFileError, PackagingExecError, InstallationException) from distutils2 import util from distutils2.dist import Distribution @@ -138,15 +138,8 @@ class UtilTestCase(support.EnvironRestorer, self._uname = None os.uname = self._get_uname - # patching POpen - self.old_find_executable = util.find_executable - util.find_executable = self._find_executable - self._exes = {} - self.old_popen = subprocess.Popen - self.old_stdout = sys.stdout - self.old_stderr = sys.stderr - FakePopen.test_class = self - subprocess.Popen = FakePopen + def _get_uname(self): + return self._uname def tearDown(self): # getting back the environment @@ -161,17 +154,24 @@ class UtilTestCase(support.EnvironRestorer, os.uname = self.uname else: del os.uname - util.find_executable = self.old_find_executable - subprocess.Popen = self.old_popen - sys.old_stdout = self.old_stdout - sys.old_stderr = self.old_stderr super(UtilTestCase, self).tearDown() - def _set_uname(self, uname): - self._uname = uname + def mock_popen(self): + self.old_find_executable = util.find_executable + util.find_executable = self._find_executable + self._exes = {} + self.old_popen = subprocess.Popen + self.old_stdout = sys.stdout + self.old_stderr = sys.stderr + FakePopen.test_class = self + subprocess.Popen = FakePopen + self.addCleanup(self.unmock_popen) - def _get_uname(self): - return self._uname + def unmock_popen(self): + util.find_executable = self.old_find_executable + subprocess.Popen = self.old_popen + sys.stdout = self.old_stdout + sys.stderr = self.old_stderr def test_convert_path(self): # linux/mac @@ -283,6 +283,7 @@ class UtilTestCase(support.EnvironRestorer, return None def test_get_compiler_versions(self): + self.mock_popen() # get_versions calls distutils.spawn.find_executable on # 'gcc', 'ld' and 'dllwrap' self.assertEqual(get_compiler_versions(), (None, None, None)) @@ -323,15 +324,12 @@ class UtilTestCase(support.EnvironRestorer, res = get_compiler_versions() self.assertEqual(res[2], None) - def test_dont_write_bytecode(self): - # makes sure byte_compile raise a PackagingError - # if sys.dont_write_bytecode is True - old_dont_write_bytecode = sys.dont_write_bytecode + def test_byte_compile_under_B(self): + # make sure byte compilation works under -B (dont_write_bytecode) + self.addCleanup(setattr, sys, 'dont_write_bytecode', + sys.dont_write_bytecode) sys.dont_write_bytecode = True - try: - self.assertRaises(PackagingByteCompileError, byte_compile, []) - finally: - sys.dont_write_bytecode = old_dont_write_bytecode + byte_compile([]) def test_newer(self): self.assertRaises(PackagingFileError, util.newer, 'xxx', 'xxx') @@ -359,56 +357,66 @@ class UtilTestCase(support.EnvironRestorer, # root = self.mkdtemp() pkg1 = os.path.join(root, 'pkg1') - os.mkdir(pkg1) - self.write_file(os.path.join(pkg1, '__init__.py')) - os.mkdir(os.path.join(pkg1, 'pkg2')) - self.write_file(os.path.join(pkg1, 'pkg2', '__init__.py')) - os.mkdir(os.path.join(pkg1, 'pkg3')) - self.write_file(os.path.join(pkg1, 'pkg3', '__init__.py')) - os.mkdir(os.path.join(pkg1, 'pkg3', 'pkg6')) - self.write_file(os.path.join(pkg1, 'pkg3', 'pkg6', '__init__.py')) - os.mkdir(os.path.join(pkg1, 'pkg4')) - os.mkdir(os.path.join(pkg1, 'pkg4', 'pkg8')) - self.write_file(os.path.join(pkg1, 'pkg4', 'pkg8', '__init__.py')) - pkg5 = os.path.join(root, 'pkg5') - os.mkdir(pkg5) - self.write_file(os.path.join(pkg5, '__init__.py')) + os.makedirs(os.path.join(pkg1, 'pkg2')) + os.makedirs(os.path.join(pkg1, 'pkg3', 'pkg6')) + os.makedirs(os.path.join(pkg1, 'pkg4', 'pkg8')) + os.makedirs(os.path.join(root, 'pkg5')) + self.write_file((pkg1, '__init__.py')) + self.write_file((pkg1, 'pkg2', '__init__.py')) + self.write_file((pkg1, 'pkg3', '__init__.py')) + self.write_file((pkg1, 'pkg3', 'pkg6', '__init__.py')) + self.write_file((pkg1, 'pkg4', 'pkg8', '__init__.py')) + self.write_file((root, 'pkg5', '__init__.py')) res = find_packages([root], ['pkg1.pkg2']) - self.assertEqual(set(res), set(['pkg1', 'pkg5', 'pkg1.pkg3', - 'pkg1.pkg3.pkg6'])) + self.assertEqual(sorted(res), + ['pkg1', 'pkg1.pkg3', 'pkg1.pkg3.pkg6', 'pkg5']) def test_resolve_name(self): - self.assertIs(str, resolve_name('builtins.str')) - self.assertEqual( - UtilTestCase.__name__, - resolve_name("distutils2.tests.test_util.UtilTestCase").__name__) - self.assertEqual( - UtilTestCase.test_resolve_name.__name__, - resolve_name("distutils2.tests.test_util.UtilTestCase." - "test_resolve_name").__name__) - - self.assertRaises(ImportError, resolve_name, - "distutils2.tests.test_util.UtilTestCaseNot") - self.assertRaises(ImportError, resolve_name, - "distutils2.tests.test_util.UtilTestCase." - "nonexistent_attribute") - - def test_import_nested_first_time(self): - tmp_dir = self.mkdtemp() - os.makedirs(os.path.join(tmp_dir, 'a', 'b')) - self.write_file(os.path.join(tmp_dir, 'a', '__init__.py'), '') - self.write_file(os.path.join(tmp_dir, 'a', 'b', '__init__.py'), '') - self.write_file(os.path.join(tmp_dir, 'a', 'b', 'c.py'), - 'class Foo: pass') - - try: - sys.path.append(tmp_dir) - resolve_name("a.b.c.Foo") - # assert nothing raised - finally: - sys.path.remove(tmp_dir) - + # test raw module name + tmpdir = self.mkdtemp() + sys.path.append(tmpdir) + self.addCleanup(sys.path.remove, tmpdir) + self.write_file((tmpdir, 'hello.py'), '') + + os.makedirs(os.path.join(tmpdir, 'a', 'b')) + self.write_file((tmpdir, 'a', '__init__.py'), '') + self.write_file((tmpdir, 'a', 'b', '__init__.py'), '') + self.write_file((tmpdir, 'a', 'b', 'c.py'), 'class Foo: pass') + self.write_file((tmpdir, 'a', 'b', 'd.py'), textwrap.dedent("""\ + class FooBar: + class Bar: + def baz(self): + pass + """)) + + # check Python, C and built-in module + self.assertEqual(resolve_name('hello').__name__, 'hello') + self.assertEqual(resolve_name('_csv').__name__, '_csv') + self.assertEqual(resolve_name('sys').__name__, 'sys') + + # test module.attr + self.assertIs(resolve_name('builtins.str'), str) + self.assertIsNone(resolve_name('hello.__doc__')) + self.assertEqual(resolve_name('a.b.c.Foo').__name__, 'Foo') + self.assertEqual(resolve_name('a.b.d.FooBar.Bar.baz').__name__, 'baz') + + # error if module not found + self.assertRaises(ImportError, resolve_name, 'nonexistent') + self.assertRaises(ImportError, resolve_name, 'non.existent') + self.assertRaises(ImportError, resolve_name, 'a.no') + self.assertRaises(ImportError, resolve_name, 'a.b.no') + self.assertRaises(ImportError, resolve_name, 'a.b.no.no') + self.assertRaises(ImportError, resolve_name, 'inva-lid') + + # looking up built-in names is not supported + self.assertRaises(ImportError, resolve_name, 'str') + + # error if module found but not attr + self.assertRaises(ImportError, resolve_name, 'a.b.Spam') + self.assertRaises(ImportError, resolve_name, 'a.b.c.Spam') + + @support.skip_2to3_optimize def test_run_2to3_on_code(self): content = "print 'test'" converted_content = "print('test')" @@ -422,6 +430,7 @@ class UtilTestCase(support.EnvironRestorer, file_handle.close() self.assertEqual(new_content, converted_content) + @support.skip_2to3_optimize def test_run_2to3_on_doctests(self): # to check if text files containing doctests only get converted. content = ">>> print 'test'\ntest\n" @@ -439,8 +448,6 @@ class UtilTestCase(support.EnvironRestorer, @unittest.skipUnless(os.name in ('nt', 'posix'), 'runs only under posix or nt') def test_spawn(self): - # no patching of Popen here - subprocess.Popen = self.old_popen tmpdir = self.mkdtemp() # creating something executable @@ -538,8 +545,6 @@ class UtilTestCase(support.EnvironRestorer, self.assertEqual(args['py_modules'], dist.py_modules) def test_generate_setup_py(self): - # undo subprocess.Popen monkey-patching before using assert_python_* - subprocess.Popen = self.old_popen os.chdir(self.mkdtemp()) self.write_file('setup.cfg', textwrap.dedent("""\ [metadata] @@ -599,14 +604,6 @@ class GlobTestCaseBase(support.TempdirManager, class GlobTestCase(GlobTestCaseBase): - def setUp(self): - super(GlobTestCase, self).setUp() - self.cwd = os.getcwd() - - def tearDown(self): - os.chdir(self.cwd) - super(GlobTestCase, self).tearDown() - def assertGlobMatch(self, glob, spec): tempdir = self.build_files_tree(spec) expected = self.clean_tree(spec) diff --git a/distutils2/tests/test_version.py b/distutils2/tests/test_version.py index 1928bbd..ab4ab58 100644 --- a/distutils2/tests/test_version.py +++ b/distutils2/tests/test_version.py @@ -1,6 +1,5 @@ """Tests for distutils2.version.""" import doctest -import os from distutils2.version import NormalizedVersion as V from distutils2.version import HugeMajorVersionNumError, IrrationalVersionError @@ -46,7 +45,6 @@ class VersionTestCase(unittest.TestCase): def test_from_parts(self): for v, s in self.versions: - parts = v.parts v2 = V.from_parts(*v.parts) self.assertEqual(v, v2) self.assertEqual(str(v), str(v2)) @@ -192,7 +190,7 @@ class VersionTestCase(unittest.TestCase): 'Hey (>=2.5,<2.7)') for predicate in predicates: - v = VersionPredicate(predicate) + VersionPredicate(predicate) self.assertTrue(VersionPredicate('Hey (>=2.5,<2.7)').match('2.6')) self.assertTrue(VersionPredicate('Ho').match('2.6')) |
