diff options
| author | ?ric Araujo <merwok@netwok.org> | 2012-05-21 17:03:13 -0400 |
|---|---|---|
| committer | ?ric Araujo <merwok@netwok.org> | 2012-05-21 17:03:13 -0400 |
| commit | 7e12306509188e264a99b529d16cc5f80839b2f6 (patch) | |
| tree | 2a8b797e061e4d2c26a5319d5f9d93895e3e569a /distutils2/tests | |
| parent | 273927821682f7abba2c961671e26d3274bb9b02 (diff) | |
| parent | ee6fb9f7f0863a1d0020d57f224947f7b795df6d (diff) | |
| download | disutils2-7e12306509188e264a99b529d16cc5f80839b2f6.tar.gz | |
Merge from default
Diffstat (limited to 'distutils2/tests')
42 files changed, 634 insertions, 800 deletions
diff --git a/distutils2/tests/__main__.py b/distutils2/tests/__main__.py index f9b9494..6ee5434 100644 --- a/distutils2/tests/__main__.py +++ b/distutils2/tests/__main__.py @@ -3,7 +3,7 @@ # Ripped from importlib tests, thanks Brett! import os -from test.test_support import reap_children, reap_threads, run_unittest +from test.support import reap_children, reap_threads, run_unittest from distutils2.tests import unittest diff --git a/distutils2/tests/fixer/fix_echo.py b/distutils2/tests/fixer/fix_echo.py index ed60a50..8daae3e 100644 --- a/distutils2/tests/fixer/fix_echo.py +++ b/distutils2/tests/fixer/fix_echo.py @@ -13,4 +13,4 @@ class FixEcho(fixer_base.BaseFix): def transform(self, node, results): name = results['name'] - name.replace(Name(u'print', prefix=name.prefix)) + name.replace(Name('print', prefix=name.prefix)) diff --git a/distutils2/tests/fixer/fix_echo2.py b/distutils2/tests/fixer/fix_echo2.py index fc96a66..1b92891 100644 --- a/distutils2/tests/fixer/fix_echo2.py +++ b/distutils2/tests/fixer/fix_echo2.py @@ -13,4 +13,4 @@ class FixEcho2(fixer_base.BaseFix): def transform(self, node, results): name = results['name'] - name.replace(Name(u'print', prefix=name.prefix)) + name.replace(Name('print', prefix=name.prefix)) diff --git a/distutils2/tests/pypi_server.py b/distutils2/tests/pypi_server.py index ad4ce14..6e77e40 100644 --- a/distutils2/tests/pypi_server.py +++ b/distutils2/tests/pypi_server.py @@ -30,15 +30,14 @@ implementations (static HTTP and XMLRPC over HTTP). """ import os -import Queue +import queue import select import threading -from BaseHTTPServer import HTTPServer -from SimpleHTTPServer import SimpleHTTPRequestHandler -from SimpleXMLRPCServer import SimpleXMLRPCServer +from functools import wraps +from http.server import HTTPServer, SimpleHTTPRequestHandler +from xmlrpc.server import SimpleXMLRPCServer from distutils2.tests import unittest -from distutils2._backport.misc import wraps PYPI_DEFAULT_STATIC_PATH = os.path.join( @@ -114,7 +113,7 @@ class PyPIServer(threading.Thread): self.server = HTTPServer(('127.0.0.1', 0), PyPIRequestHandler) self.server.RequestHandlerClass.pypi_server = self - self.request_queue = Queue.Queue() + self.request_queue = queue.Queue() self._requests = [] self.default_response_status = 404 self.default_response_headers = [('Content-type', 'text/plain')] @@ -151,7 +150,7 @@ class PyPIServer(threading.Thread): def stop(self): """self shutdown is not supported for python < 2.6""" self._run = False - if self.isAlive(): + if self.is_alive(): self.join() self.server.server_close() @@ -168,7 +167,7 @@ class PyPIServer(threading.Thread): while True: try: self._requests.append(self.request_queue.get_nowait()) - except Queue.Empty: + except queue.Empty: break return self._requests @@ -220,18 +219,12 @@ class PyPIRequestHandler(SimpleHTTPRequestHandler): relative_path += "index.html" if relative_path.endswith('.tar.gz'): - file = open(fs_path + relative_path, 'rb') - try: + with open(fs_path + relative_path, 'rb') as file: data = file.read() - finally: - file.close() headers = [('Content-type', 'application/x-gtar')] else: - file = open(fs_path + relative_path) - try: + with open(fs_path + relative_path) as file: data = file.read().encode() - finally: - file.close() headers = [('Content-type', 'text/html')] headers.append(('Content-Length', len(data))) @@ -267,13 +260,13 @@ class PyPIRequestHandler(SimpleHTTPRequestHandler): self.send_header(header, value) self.end_headers() - if isinstance(data, unicode): + if isinstance(data, str): data = data.encode('utf-8') self.wfile.write(data) -class PyPIXMLRPCServer(SimpleXMLRPCServer, object): +class PyPIXMLRPCServer(SimpleXMLRPCServer): def server_bind(self): """Override server_bind to store the server name.""" super(PyPIXMLRPCServer, self).server_bind() @@ -281,7 +274,7 @@ class PyPIXMLRPCServer(SimpleXMLRPCServer, object): self.server_port = port -class MockDist(object): +class MockDist: """Fake distribution, used in the Mock PyPI Server""" def __init__(self, name, version="1.0", hidden=False, url="http://url/", @@ -397,7 +390,7 @@ class MockDist(object): } -class XMLRPCMockIndex(object): +class XMLRPCMockIndex: """Mock XMLRPC server""" def __init__(self, dists=[]): diff --git a/distutils2/tests/pypi_test_server.py b/distutils2/tests/pypi_test_server.py index 516e058..8c8c641 100644 --- a/distutils2/tests/pypi_test_server.py +++ b/distutils2/tests/pypi_test_server.py @@ -40,7 +40,7 @@ class PyPIServerTestCase(unittest.TestCase): self.addCleanup(self.pypi.stop) -class PyPIServer(object): +class PyPIServer: """Shim to access testpypi.python.org, for testing a real server.""" def __init__(self, test_static_path=None, diff --git a/distutils2/tests/support.py b/distutils2/tests/support.py index c970b90..ecc7534 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 logging import logging.handlers import subprocess @@ -67,7 +66,7 @@ __all__ = [ # misc. functions and decorators 'fake_dec', 'create_distribution', 'use_command', 'copy_xxmodule_c', 'fixup_build_ext', - 'requires_py26_min', 'skip_2to3_optimize', 'requires_docutils', + 'skip_2to3_optimize', 'requires_docutils', # imported from this module for backport purposes 'unittest', 'requires_zlib', 'skip_unless_symlink', ] @@ -77,7 +76,7 @@ logger = logging.getLogger('distutils2') logger2to3 = logging.getLogger('RefactoringTool') -class _TestHandler(logging.handlers.BufferingHandler, object): +class _TestHandler(logging.handlers.BufferingHandler): # stolen and adapted from test.support def __init__(self): @@ -91,7 +90,7 @@ class _TestHandler(logging.handlers.BufferingHandler, object): self.buffer.append(record) -class LoggingCatcher(object): +class LoggingCatcher: """TestCase-compatible mixin to receive logging calls. Upon setUp, instances of this classes get a BufferingHandler that's @@ -148,7 +147,7 @@ class LoggingCatcher(object): return messages -class TempdirManager(object): +class TempdirManager: """TestCase-compatible mixin to create temporary directories and files. Directories and files created in a test_* method will be removed after it @@ -191,11 +190,8 @@ class TempdirManager(object): """ if isinstance(path, (list, tuple)): path = os.path.join(*path) - f = codecs.open(path, 'w', encoding=encoding) - try: + with open(path, 'w', encoding=encoding) as f: f.write(content) - finally: - f.close() def create_dist(self, **kw): """Create a stub distribution object and files. @@ -233,7 +229,7 @@ class TempdirManager(object): self.assertFalse(os.path.isfile(path), "%r exists" % path) -class EnvironRestorer(object): +class EnvironRestorer: """TestCase-compatible mixin to restore or delete environment variables. The variables to restore (or delete if they were not originally present) @@ -260,7 +256,7 @@ class EnvironRestorer(object): super(EnvironRestorer, self).tearDown() -class DummyCommand(object): +class DummyCommand: """Class to store options for retrieval via set_undefined_options(). Useful for mocking one dependency command in the tests for another @@ -289,7 +285,7 @@ class TestDistribution(Distribution): return self._config_files -class Inputs(object): +class Inputs: """Fakes user inputs.""" # TODO document usage # TODO use context manager or something for auto cleanup @@ -402,16 +398,13 @@ def fixup_build_ext(cmd): try: - from test.test_support import skip_unless_symlink + from test.support import skip_unless_symlink except ImportError: skip_unless_symlink = unittest.skip( - 'requires test.test_support.skip_unless_symlink') - -skip_2to3_optimize = unittest.skipUnless(__debug__, - "2to3 doesn't work under -O") + 'requires test.support.skip_unless_symlink') -requires_py26_min = unittest.skipIf(sys.version_info[:2] < (2, 6), - 'requires Python 2.6 or higher') +skip_2to3_optimize = unittest.skipIf(sys.flags.optimize, + "2to3 doesn't work under -O") requires_zlib = unittest.skipUnless(zlib, 'requires zlib') @@ -421,7 +414,7 @@ requires_docutils = unittest.skipUnless(docutils, 'requires docutils') def unlink(filename): try: os.unlink(filename) - except OSError, error: + except OSError as error: # The filename need not exist. if error.errno not in (errno.ENOENT, errno.ENOTDIR): raise @@ -434,7 +427,7 @@ def strip_python_stderr(stderr): This will typically be run on the result of the communicate() method of a subprocess.Popen object. """ - stderr = re.sub(r"\[\d+ refs\]\r?\n?$", "", stderr).strip() + stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip() return stderr diff --git a/distutils2/tests/test_command_bdist.py b/distutils2/tests/test_command_bdist.py index a222d0f..852b2a7 100644 --- a/distutils2/tests/test_command_bdist.py +++ b/distutils2/tests/test_command_bdist.py @@ -1,10 +1,9 @@ """Tests for distutils.command.bdist.""" import os -import sys -from StringIO import StringIO from distutils2.errors import PackagingPlatformError from distutils2.command.bdist import bdist, show_formats +from test.support import captured_stdout from distutils2.tests import unittest, support @@ -57,13 +56,9 @@ class BuildTestCase(support.TempdirManager, os.name = _os_name def test_show_formats(self): - saved = sys.stdout - sys.stdout = StringIO() - try: + with captured_stdout() as stdout: show_formats() - stdout = sys.stdout.getvalue() - finally: - sys.stdout = saved + stdout = stdout.getvalue() # the output should be a header line + one line per format num_formats = len(bdist.format_commands) diff --git a/distutils2/tests/test_command_bdist_dumb.py b/distutils2/tests/test_command_bdist_dumb.py index 1097c54..2196139 100644 --- a/distutils2/tests/test_command_bdist_dumb.py +++ b/distutils2/tests/test_command_bdist_dumb.py @@ -1,6 +1,8 @@ """Tests for distutils.command.bdist_dumb.""" import os +import imp +import sys import zipfile import distutils2.util @@ -61,10 +63,14 @@ class BuildDumbTestCase(support.TempdirManager, try: contents = fp.namelist() finally: - fp.close() + fp.close + if sys.version_info[:2] == (3, 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', 'foo.pyc', + wanted = ['foo.py', pyc, 'METADATA', 'INSTALLER', 'REQUESTED', 'RECORD'] self.assertEqual(contents, sorted(wanted)) diff --git a/distutils2/tests/test_command_build_clib.py b/distutils2/tests/test_command_build_clib.py index da306e7..9c1eb04 100644 --- a/distutils2/tests/test_command_build_clib.py +++ b/distutils2/tests/test_command_build_clib.py @@ -68,7 +68,7 @@ class BuildCLibTestCase(support.TempdirManager, pkg_dir, dist = self.create_dist() cmd = build_clib(dist) - class FakeCompiler(object): + class FakeCompiler: def compile(*args, **kw): pass create_static_lib = compile diff --git a/distutils2/tests/test_command_build_ext.py b/distutils2/tests/test_command_build_ext.py index 1717d46..9a191c1 100644 --- a/distutils2/tests/test_command_build_ext.py +++ b/distutils2/tests/test_command_build_ext.py @@ -19,18 +19,13 @@ class BuildExtTestCase(support.TempdirManager, def setUp(self): super(BuildExtTestCase, self).setUp() self.tmp_dir = self.mkdtemp() - if sys.version_info[:2] >= (2, 6): - self.old_user_base = site.USER_BASE - site.USER_BASE = self.mkdtemp() + self.old_user_base = site.USER_BASE + site.USER_BASE = self.mkdtemp() def tearDown(self): - if sys.version_info[:2] >= (2, 6): - site.USER_BASE = self.old_user_base - + site.USER_BASE = self.old_user_base super(BuildExtTestCase, self).tearDown() - @unittest.skipIf(sys.version_info[:2] < (2, 6), - "can't compile xxmodule successfully") def test_build_ext(self): support.copy_xxmodule_c(self.tmp_dir) xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') @@ -85,7 +80,6 @@ class BuildExtTestCase(support.TempdirManager, # make sure we get some library dirs under solaris self.assertGreater(len(cmd.library_dirs), 0) - @support.requires_py26_min def test_user_site(self): dist = Distribution({'name': 'xx'}) cmd = build_ext(dist) @@ -354,8 +348,7 @@ class BuildExtTestCase(support.TempdirManager, deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c') - fp = open(deptarget_c, 'w') - try: + with open(deptarget_c, 'w') as fp: fp.write(textwrap.dedent('''\ #include <AvailabilityMacros.h> @@ -367,8 +360,6 @@ class BuildExtTestCase(support.TempdirManager, #endif ''' % operator)) - finally: - fp.close() # get the deployment target that the interpreter was built with target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') diff --git a/distutils2/tests/test_command_build_py.py b/distutils2/tests/test_command_build_py.py index 501a2ab..b6b7fd8 100644 --- a/distutils2/tests/test_command_build_py.py +++ b/distutils2/tests/test_command_build_py.py @@ -2,6 +2,7 @@ import os import sys +import imp from distutils2.command.build_py import build_py from distutils2.dist import Distribution @@ -67,8 +68,16 @@ class BuildPyTestCase(support.TempdirManager, self.assertEqual(len(outputs), 4, outputs) pkgdest = os.path.join(destination, "pkg") files = os.listdir(pkgdest) - self.assertEqual(sorted(files), ["HACKING.txt", "README.txt", - "__init__.py", "__init__.pyc"]) + wanted = ["__init__.py", "HACKING.txt", "README.txt"] + if sys.version_info[:2] == (3, 1): + wanted.append("__init__.pyc") + else: + wanted.append("__pycache__") + self.assertEqual(sorted(files), sorted(wanted)) + if sys.version_info[:2] >= (3, 2): + pycache_dir = os.path.join(pkgdest, "__pycache__") + pyc_files = os.listdir(pycache_dir) + self.assertEqual(["__init__.%s.pyc" % imp.get_tag()], pyc_files) def test_empty_package_dir(self): # See SF 1668596/1720897. @@ -104,7 +113,13 @@ class BuildPyTestCase(support.TempdirManager, cmd.run() found = os.listdir(cmd.build_lib) - self.assertEqual(sorted(found), ['boiledeggs.py', 'boiledeggs.pyc']) + if sys.version_info[:2] == (3, 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']) @@ -118,11 +133,16 @@ class BuildPyTestCase(support.TempdirManager, cmd.run() found = os.listdir(cmd.build_lib) - self.assertEqual(sorted(found), - ['boiledeggs.py', 'boiledeggs.pyc', 'boiledeggs.pyo']) + if sys.version_info[:2] == (3, 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()]) - @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'), - 'sys.dont_write_bytecode not supported') def test_byte_compile_under_B(self): # make sure byte compilation works under -B (dont_write_bytecode) self.addCleanup(setattr, sys, 'dont_write_bytecode', diff --git a/distutils2/tests/test_command_build_scripts.py b/distutils2/tests/test_command_build_scripts.py index 5d7930b..f96a34c 100644 --- a/distutils2/tests/test_command_build_scripts.py +++ b/distutils2/tests/test_command_build_scripts.py @@ -72,11 +72,8 @@ class BuildScriptsTestCase(support.TempdirManager, return expected def write_script(self, dir, name, text): - f = open(os.path.join(dir, name), "w") - try: + with open(os.path.join(dir, name), "w") as f: f.write(text) - finally: - f.close() def test_version_int(self): source = self.mkdtemp() diff --git a/distutils2/tests/test_command_check.py b/distutils2/tests/test_command_check.py index 7cdd2c1..3bd55c5 100644 --- a/distutils2/tests/test_command_check.py +++ b/distutils2/tests/test_command_check.py @@ -55,11 +55,11 @@ class CheckTestCase(support.LoggingCatcher, self.assertEqual(self.get_logs(), []) # now a test with non-ASCII characters - metadata = {'home_page': u'xxx', 'author': u'\u00c9ric', - 'author_email': u'xxx', 'name': u'xxx', - 'version': u'1.2', - 'summary': u'Something about esszet \u00df', - 'description': u'More things about esszet \u00df'} + metadata = {'home_page': 'xxx', 'author': '\u00c9ric', + 'author_email': 'xxx', 'name': 'xxx', + 'version': '1.2', + 'summary': 'Something about esszet \u00df', + 'description': 'More things about esszet \u00df'} self._run(metadata) self.assertEqual(self.get_logs(), []) @@ -119,7 +119,7 @@ class CheckTestCase(support.LoggingCatcher, self.loghandler.flush() # and non-broken rest, including a non-ASCII character to test #12114 - dist = self.create_dist(description=u'title\n=====\n\ntest \u00df')[1] + dist = self.create_dist(description='title\n=====\n\ntest \u00df')[1] cmd = check(dist) cmd.check_restructuredtext() self.assertEqual(self.get_logs(), []) diff --git a/distutils2/tests/test_command_config.py b/distutils2/tests/test_command_config.py index 5bb27e3..97304a6 100644 --- a/distutils2/tests/test_command_config.py +++ b/distutils2/tests/test_command_config.py @@ -13,11 +13,8 @@ class ConfigTestCase(support.LoggingCatcher, def test_dump_file(self): this_file = __file__.rstrip('co') - f = open(this_file) - try: + with open(this_file) as f: numlines = len(f.readlines()) - finally: - f.close() dump_file(this_file, 'I am the header') diff --git a/distutils2/tests/test_command_install_data.py b/distutils2/tests/test_command_install_data.py index 3143341..c169b87 100644 --- a/distutils2/tests/test_command_install_data.py +++ b/distutils2/tests/test_command_install_data.py @@ -127,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 02f962b..079d3cf 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 @@ -72,7 +73,6 @@ class InstallTestCase(support.TempdirManager, check_path(cmd.install_scripts, os.path.join(destination, "bin")) check_path(cmd.install_data, destination) - @support.requires_py26_min def test_user_site(self): # test install with --user # preparing the environment for the test @@ -172,12 +172,11 @@ class InstallTestCase(support.TempdirManager, cmd.home = 'home' self.assertRaises(PackagingOptionError, cmd.finalize_options) - if sys.version_info[:2] >= (2, 6): - # can't combine user with with prefix/exec_prefix/home or - # install_(plat)base - cmd.prefix = None - cmd.user = 'user' - self.assertRaises(PackagingOptionError, cmd.finalize_options) + # can't combine user with with prefix/exec_prefix/home or + # install_(plat)base + cmd.prefix = None + cmd.user = 'user' + self.assertRaises(PackagingOptionError, cmd.finalize_options) def test_old_record(self): # test pre-PEP 376 --record option (outside dist-info dir) @@ -185,7 +184,7 @@ class InstallTestCase(support.TempdirManager, project_dir, dist = self.create_dist(py_modules=['hello'], scripts=['sayhi']) os.chdir(project_dir) - self.write_file('hello.py', "def main(): 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) @@ -195,22 +194,21 @@ class InstallTestCase(support.TempdirManager, cmd.ensure_finalized() cmd.run() - f = open(cmd.record) - try: + with open(cmd.record) as f: content = f.read() - finally: - f.close() + if sys.version_info[:2] == (3, 1): + pyc = 'hello.pyc' + else: + pyc = 'hello.%s.pyc' % imp.get_tag() found = [os.path.basename(line) for line in content.splitlines()] - expected = ['hello.py', 'hello.pyc', 'sayhi', + 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 - @unittest.skipIf(sys.version_info[:2] < (2, 6), - "can't compile xxmodule successfully") def test_old_record_extensions(self): # test pre-PEP 376 --record option with ext modules install_dir = self.mkdtemp() @@ -231,11 +229,8 @@ class InstallTestCase(support.TempdirManager, cmd.ensure_finalized() cmd.run() - f = open(cmd.record) - try: + with open(cmd.record) as f: content = f.read() - finally: - f.close() found = [os.path.basename(line) for line in content.splitlines()] expected = [_make_ext_name('xx'), diff --git a/distutils2/tests/test_command_install_distinfo.py b/distutils2/tests/test_command_install_distinfo.py index b298c21..3985e0b 100644 --- a/distutils2/tests/test_command_install_distinfo.py +++ b/distutils2/tests/test_command_install_distinfo.py @@ -5,7 +5,7 @@ Writing of the RESOURCES file is tested in test_command_install_data. import os import csv -import codecs +import hashlib from distutils2.command.install_distinfo import install_distinfo from distutils2.command.cmd import Command @@ -13,10 +13,6 @@ from distutils2.compiler.extension import Extension from distutils2.metadata import Metadata from distutils2.tests import unittest, support from distutils2._backport import sysconfig -try: - import hashlib -except: - from distutils2._backport import hashlib class DummyInstallCmd(Command): @@ -62,18 +58,11 @@ class InstallDistinfoTestCase(support.TempdirManager, dist_info = os.path.join(install_dir, 'foo-1.0.dist-info') self.checkLists(os.listdir(dist_info), ['METADATA', 'RECORD', 'REQUESTED', 'INSTALLER']) - fp = open(os.path.join(dist_info, 'INSTALLER')) - try: + with open(os.path.join(dist_info, 'INSTALLER')) as fp: self.assertEqual(fp.read(), 'distutils') - finally: - fp.close() - fp = open(os.path.join(dist_info, 'REQUESTED')) - try: + with open(os.path.join(dist_info, 'REQUESTED')) as fp: self.assertEqual(fp.read(), '') - finally: - fp.close() - meta_path = os.path.join(dist_info, 'METADATA') self.assertTrue(Metadata(path=meta_path).check()) @@ -94,11 +83,8 @@ class InstallDistinfoTestCase(support.TempdirManager, cmd.run() dist_info = os.path.join(install_dir, 'foo-1.0.dist-info') - fp = open(os.path.join(dist_info, 'INSTALLER')) - try: + with open(os.path.join(dist_info, 'INSTALLER')) as fp: self.assertEqual(fp.read(), 'bacon-python') - finally: - fp.close() def test_requested(self): pkg_dir, dist = self.create_dist(name='foo', @@ -174,21 +160,15 @@ class InstallDistinfoTestCase(support.TempdirManager, # platform-dependent (line endings) metadata = os.path.join(modules_dest, 'Spamlib-0.1.dist-info', 'METADATA') - fp = open(metadata, 'rb') - try: + with open(metadata, 'rb') as fp: content = fp.read() - finally: - fp.close() metadata_size = str(len(content)) metadata_md5 = hashlib.md5(content).hexdigest() record = os.path.join(modules_dest, 'Spamlib-0.1.dist-info', 'RECORD') - fp = codecs.open(record, encoding='utf-8') - try: + with open(record, encoding='utf-8') as fp: content = fp.read() - finally: - fp.close() found = [] for line in content.splitlines(): @@ -243,29 +223,23 @@ class InstallDistinfoTestCase(support.TempdirManager, expected = [] for f in install.get_outputs(): - if (f.endswith('.pyc') or f.endswith('.pyo') or f == os.path.join( + if (f.endswith(('.pyc', '.pyo')) or f == os.path.join( install_dir, 'foo-1.0.dist-info', 'RECORD')): expected.append([f, '', '']) else: size = os.path.getsize(f) md5 = hashlib.md5() - fp = open(f, 'rb') - try: + with open(f, 'rb') as fp: md5.update(fp.read()) - finally: - fp.close() hash = md5.hexdigest() expected.append([f, hash, str(size)]) parsed = [] - f = open(os.path.join(dist_info, 'RECORD'), 'r') - try: + with open(os.path.join(dist_info, 'RECORD'), 'r') as f: reader = csv.reader(f, delimiter=',', lineterminator=os.linesep, quotechar='"') parsed = list(reader) - finally: - f.close() self.maxDiff = None self.checkLists(parsed, expected) diff --git a/distutils2/tests/test_command_install_lib.py b/distutils2/tests/test_command_install_lib.py index 88368c9..fcc28c4 100644 --- a/distutils2/tests/test_command_install_lib.py +++ b/distutils2/tests/test_command_install_lib.py @@ -1,6 +1,7 @@ """Tests for distutils2.command.install_data.""" import os import sys +import imp from distutils2.tests import unittest, support from distutils2.command.install_lib import install_lib @@ -43,11 +44,15 @@ class InstallLibTestCase(support.TempdirManager, f = os.path.join(project_dir, 'foo.py') self.write_file(f, '# python file') cmd.byte_compile([f]) - self.assertTrue(os.path.exists(f + 'c')) - self.assertTrue(os.path.exists(f + 'o')) + if sys.version_info[:2] == (3, 1): + pyc_file = 'foo.pyc' + pyo_file = 'foo.pyo' + else: + 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)) - @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'), - 'sys.dont_write_bytecode not supported') def test_byte_compile_under_B(self): # make sure byte compilation works under -B (dont_write_bytecode) self.addCleanup(setattr, sys, 'dont_write_bytecode', @@ -77,7 +82,7 @@ class InstallLibTestCase(support.TempdirManager, cmd.get_finalized_command('build_py').build_lib = build_dir # get_outputs should return 4 elements: spam/__init__.py, .pyc and - # .pyo, foo.so / foo.pyd + # .pyo, foo*.so / foo.pyd outputs = cmd.get_outputs() self.assertEqual(len(outputs), 4, outputs) @@ -97,7 +102,7 @@ class InstallLibTestCase(support.TempdirManager, cmd.distribution.packages = ['spam'] # get_inputs should return 2 elements: spam/__init__.py and - # foo.so / foo.pyd + # foo*.so / foo.pyd inputs = cmd.get_inputs() self.assertEqual(len(inputs), 2, inputs) diff --git a/distutils2/tests/test_command_install_scripts.py b/distutils2/tests/test_command_install_scripts.py index da5ad94..551cd8c 100644 --- a/distutils2/tests/test_command_install_scripts.py +++ b/distutils2/tests/test_command_install_scripts.py @@ -38,11 +38,8 @@ class InstallScriptsTestCase(support.TempdirManager, def write_script(name, text): expected.append(name) - f = open(os.path.join(source, name), "w") - try: + with open(os.path.join(source, name), "w") as f: f.write(text) - finally: - f.close() write_script("script1.py", ("#! /usr/bin/env python2.3\n" "# bogus script w/ Python sh-bang\n" diff --git a/distutils2/tests/test_command_register.py b/distutils2/tests/test_command_register.py index 7cdb6ce..034f4d1 100644 --- a/distutils2/tests/test_command_register.py +++ b/distutils2/tests/test_command_register.py @@ -1,8 +1,9 @@ -# encoding: utf-8 """Tests for distutils2.command.register.""" import os import getpass -import urllib2 +import urllib.request +import urllib.error +import urllib.parse from distutils2.tests import unittest, support from distutils2.tests.support import Inputs, requires_docutils @@ -32,7 +33,7 @@ password:password """ -class FakeOpener(object): +class FakeOpener: """Fakes a PyPI server""" def __init__(self): self.reqs = [] @@ -68,12 +69,12 @@ class RegisterTestCase(support.TempdirManager, return 'password' getpass.getpass = _getpass - self.old_opener = urllib2.build_opener - self.conn = urllib2.build_opener = FakeOpener() + self.old_opener = urllib.request.build_opener + self.conn = urllib.request.build_opener = FakeOpener() def tearDown(self): getpass.getpass = self._old_getpass - urllib2.build_opener = self.old_opener + urllib.request.build_opener = self.old_opener if hasattr(register_module, 'input'): del register_module.input super(RegisterTestCase, self).tearDown() @@ -104,7 +105,7 @@ class RegisterTestCase(support.TempdirManager, # Password : 'password' # Save your login (y/N)? : 'y' inputs = Inputs('1', 'tarek', 'y') - register_module.raw_input = inputs + register_module.input = inputs cmd.ensure_finalized() cmd.run() @@ -112,11 +113,8 @@ class RegisterTestCase(support.TempdirManager, self.assertTrue(os.path.exists(self.rc)) # with the content similar to WANTED_PYPIRC - fp = open(self.rc) - try: + with open(self.rc) as fp: content = fp.read() - finally: - fp.close() self.assertEqual(content, WANTED_PYPIRC) # now let's make sure the .pypirc file generated @@ -137,7 +135,7 @@ class RegisterTestCase(support.TempdirManager, req1 = dict(self.conn.reqs[0].headers) req2 = dict(self.conn.reqs[1].headers) self.assertEqual(req2['Content-length'], req1['Content-length']) - self.assertIn('xxx', self.conn.reqs[1].data) + self.assertIn(b'xxx', self.conn.reqs[1].data) def test_password_not_in_file(self): @@ -155,7 +153,7 @@ class RegisterTestCase(support.TempdirManager, # this test runs choice 2 cmd = self._get_cmd() inputs = Inputs('2', 'tarek', 'tarek@ziade.org') - register_module.raw_input = inputs + register_module.input = inputs # let's run the command # FIXME does this send a real request? use a mock server cmd.ensure_finalized() @@ -166,13 +164,13 @@ class RegisterTestCase(support.TempdirManager, req = self.conn.reqs[0] headers = dict(req.headers) self.assertEqual(headers['Content-length'], '628') - self.assertIn('tarek', req.data) + self.assertIn(b'tarek', req.data) def test_password_reset(self): # this test runs choice 3 cmd = self._get_cmd() inputs = Inputs('3', 'tarek@ziade.org') - register_module.raw_input = inputs + register_module.input = inputs cmd.ensure_finalized() cmd.run() @@ -181,19 +179,19 @@ class RegisterTestCase(support.TempdirManager, req = self.conn.reqs[0] headers = dict(req.headers) self.assertEqual(headers['Content-length'], '298') - self.assertIn('tarek', req.data) + self.assertIn(b'tarek', req.data) @requires_docutils def test_strict(self): # 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 inputs = Inputs('1', 'tarek', 'y') - register_module.raw_input = inputs + register_module.input = inputs self.assertRaises(PackagingSetupError, cmd.run) # metadata is OK but description is broken @@ -213,7 +211,7 @@ class RegisterTestCase(support.TempdirManager, cmd.ensure_finalized() cmd.strict = True inputs = Inputs('1', 'tarek', 'y') - register_module.raw_input = inputs + register_module.input = inputs cmd.ensure_finalized() cmd.run() @@ -221,22 +219,22 @@ class RegisterTestCase(support.TempdirManager, cmd = self._get_cmd() cmd.ensure_finalized() inputs = Inputs('1', 'tarek', 'y') - register_module.raw_input = inputs + register_module.input = inputs cmd.ensure_finalized() cmd.run() # and finally a Unicode test (bug #12114) - metadata = {'home_page': u'xxx', 'author': u'\u00c9ric', - 'author_email': u'xxx', 'name': u'xxx', - 'version': u'xxx', - 'summary': u'Something about esszet \u00df', - 'description': u'More things about esszet \u00df'} + metadata = {'home_page': 'xxx', 'author': '\u00c9ric', + 'author_email': 'xxx', 'name': 'xxx', + 'version': 'xxx', + 'summary': 'Something about esszet \u00df', + 'description': 'More things about esszet \u00df'} cmd = self._get_cmd(metadata) cmd.ensure_finalized() cmd.strict = True inputs = Inputs('1', 'tarek', 'y') - register_module.raw_input = inputs + register_module.input = inputs cmd.ensure_finalized() cmd.run() @@ -259,7 +257,7 @@ class RegisterTestCase(support.TempdirManager, cmd.ensure_finalized() cmd.strict = True inputs = Inputs('2', 'tarek', 'tarek@ziade.org') - register_module.raw_input = inputs + register_module.input = inputs with self.assertRaises(PackagingSetupError) as e: cmd.run() self.assertIn('funkie', str(e.exception)) diff --git a/distutils2/tests/test_command_sdist.py b/distutils2/tests/test_command_sdist.py index a90bc10..f059db4 100644 --- a/distutils2/tests/test_command_sdist.py +++ b/distutils2/tests/test_command_sdist.py @@ -11,7 +11,6 @@ except ImportError: UID_GID_SUPPORT = False from os.path import join -from StringIO import StringIO from distutils2.dist import Distribution from distutils2.util import find_executable from distutils2.errors import PackagingOptionError @@ -19,6 +18,7 @@ from distutils2.command.sdist import sdist, show_formats from distutils2._backport import tarfile from distutils2._backport.shutil import get_archive_formats +from test.support import captured_stdout from distutils2.tests import support, unittest from distutils2.tests.support import requires_zlib @@ -210,11 +210,8 @@ class SDistTestCase(support.TempdirManager, self.assertEqual(len(content), 10) # Checking the MANIFEST - fp = open(join(self.tmp_dir, 'MANIFEST')) - try: + with open(join(self.tmp_dir, 'MANIFEST')) as fp: manifest = fp.read() - finally: - fp.close() self.assertEqual(manifest, MANIFEST % {'sep': os.sep}) @requires_zlib @@ -243,13 +240,9 @@ class SDistTestCase(support.TempdirManager, self.assertIn("'setup.cfg' file not found", warnings[1]) def test_show_formats(self): - saved = sys.stdout - sys.stdout = StringIO() - try: + with captured_stdout() as stdout: show_formats() - stdout = sys.stdout.getvalue() - finally: - sys.stdout = saved + stdout = stdout.getvalue() # the output should be a header line + one line per format num_formats = len(get_archive_formats()) @@ -283,11 +276,8 @@ class SDistTestCase(support.TempdirManager, cmd.ensure_finalized() self.write_file((self.tmp_dir, 'yeah'), 'xxx') cmd.run() - f = open(cmd.manifest) - try: + with open(cmd.manifest) as f: content = f.read() - finally: - f.close() self.assertIn('yeah', content) @@ -309,13 +299,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() @@ -327,15 +314,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): @@ -349,12 +333,9 @@ class SDistTestCase(support.TempdirManager, # Should produce four lines. Those lines are one comment, one default # (README) and two package files. - f = open(cmd.manifest) - try: + with open(cmd.manifest) as f: manifest = [line.strip() for line in f.read().split('\n') if line.strip() != ''] - finally: - f.close() self.assertEqual(len(manifest), 3) # Adding a file @@ -367,12 +348,9 @@ class SDistTestCase(support.TempdirManager, cmd.run() - f = open(cmd.manifest) - try: + with open(cmd.manifest) as f: manifest2 = [line.strip() for line in f.read().split('\n') if line.strip() != ''] - finally: - f.close() # Do we have the new file in MANIFEST? self.assertEqual(len(manifest2), 4) @@ -385,12 +363,9 @@ class SDistTestCase(support.TempdirManager, cmd.ensure_finalized() cmd.run() - f = open(cmd.manifest) - try: + with open(cmd.manifest) as f: manifest = [line.strip() for line in f.read().split('\n') if line.strip() != ''] - finally: - f.close() self.assertEqual(manifest[0], '# file GENERATED by distutils2, do NOT edit') @@ -403,12 +378,9 @@ class SDistTestCase(support.TempdirManager, self.write_file((self.tmp_dir, cmd.manifest), 'README.manual') cmd.run() - f = open(cmd.manifest) - try: + with open(cmd.manifest) as f: manifest = [line.strip() for line in f.read().split('\n') if line.strip() != ''] - finally: - f.close() self.assertEqual(manifest, ['README.manual']) diff --git a/distutils2/tests/test_command_test.py b/distutils2/tests/test_command_test.py index 176df14..97d6de8 100644 --- a/distutils2/tests/test_command_test.py +++ b/distutils2/tests/test_command_test.py @@ -112,7 +112,7 @@ class TestTest(TempdirManager, record = [] a_module.recorder = lambda *args: record.append("suite") - class MockTextTestRunner(object): + class MockTextTestRunner: def __init__(*_, **__): pass @@ -177,7 +177,7 @@ class TestTest(TempdirManager, self.assertEqual(["runner called"], record) def prepare_mock_ut2(self): - class MockUTClass(object): + class MockUTClass: def __init__(*_, **__): pass @@ -187,7 +187,7 @@ class TestTest(TempdirManager, def run(self, _): pass - class MockUTModule(object): + class MockUTModule: TestLoader = MockUTClass TextTestRunner = MockUTClass diff --git a/distutils2/tests/test_command_upload.py b/distutils2/tests/test_command_upload.py index ac1ec54..61c6654 100644 --- a/distutils2/tests/test_command_upload.py +++ b/distutils2/tests/test_command_upload.py @@ -1,4 +1,3 @@ -# encoding: utf-8 """Tests for distutils2.command.upload.""" import os @@ -44,7 +43,7 @@ repository:http://another.pypi/ """ -#@skip if no threading, see end of file +@unittest.skipIf(threading is None, 'needs threading') class UploadTestCase(support.TempdirManager, support.EnvironRestorer, support.LoggingCatcher, PyPIServerTestCase): @@ -113,8 +112,8 @@ class UploadTestCase(support.TempdirManager, support.EnvironRestorer, # what did we send? handler, request_data = self.pypi.requests[-1] headers = handler.headers - self.assertIn('dédé', request_data) - self.assertIn('xxx', request_data) + self.assertIn('dédé'.encode('utf-8'), request_data) + self.assertIn(b'xxx', request_data) self.assertEqual(int(headers['content-length']), len(request_data)) self.assertLess(int(headers['content-length']), 2500) @@ -149,12 +148,8 @@ class UploadTestCase(support.TempdirManager, support.EnvironRestorer, "----------------GHSKFJDLGDS7543FJKLFHRE75642756743254" .encode())[1:4] - self.assertIn('name=":action"', action) - self.assertIn('doc_upload', action) - - -UploadTestCase = unittest.skipIf(threading is None, 'needs threading')( - UploadTestCase) + self.assertIn(b'name=":action"', action) + self.assertIn(b'doc_upload', action) def test_suite(): diff --git a/distutils2/tests/test_command_upload_docs.py b/distutils2/tests/test_command_upload_docs.py index d45eeab..b128cfe 100644 --- a/distutils2/tests/test_command_upload_docs.py +++ b/distutils2/tests/test_command_upload_docs.py @@ -33,7 +33,7 @@ password = long_island """ -#@skip if no threading, see end of file +@unittest.skipIf(threading is None, "Needs threading") class UploadDocsTestCase(support.TempdirManager, support.EnvironRestorer, support.LoggingCatcher, @@ -95,39 +95,39 @@ class UploadDocsTestCase(support.TempdirManager, self.assertEqual(len(self.pypi.requests), 1) handler, request_data = self.pypi.requests[-1] - self.assertIn("content", request_data) + self.assertIn(b"content", request_data) self.assertIn("Basic", handler.headers['authorization']) self.assertTrue(handler.headers['content-type'] .startswith('multipart/form-data;')) action, name, version, content = request_data.split( - '----------------GHSKFJDLGDS7543FJKLFHRE75642756743254')[1:5] + b'----------------GHSKFJDLGDS7543FJKLFHRE75642756743254')[1:5] # check that we picked the right chunks - self.assertIn('name=":action"', action) - self.assertIn('name="name"', name) - self.assertIn('name="version"', version) - self.assertIn('name="content"', content) + self.assertIn(b'name=":action"', action) + self.assertIn(b'name="name"', name) + self.assertIn(b'name="version"', version) + self.assertIn(b'name="content"', content) # check their contents - self.assertIn('doc_upload', action) - self.assertIn('distr-name', name) - self.assertIn('docs/index.html', content) - self.assertIn('Ce mortel ennui', content) + self.assertIn(b'doc_upload', action) + self.assertIn(b'distr-name', name) + self.assertIn(b'docs/index.html', content) + self.assertIn(b'Ce mortel ennui', content) @unittest.skipIf(_ssl is None, 'Needs SSL support') def test_https_connection(self): self.https_called = False self.addCleanup( - setattr, upload_docs_mod.httplib, 'HTTPSConnection', - upload_docs_mod.httplib.HTTPSConnection) + setattr, upload_docs_mod.http.client, 'HTTPSConnection', + upload_docs_mod.http.client.HTTPSConnection) def https_conn_wrapper(*args): self.https_called = True # the testing server is http - return upload_docs_mod.httplib.HTTPConnection(*args) + return upload_docs_mod.http.client.HTTPConnection(*args) - upload_docs_mod.httplib.HTTPSConnection = https_conn_wrapper + upload_docs_mod.http.client.HTTPSConnection = https_conn_wrapper self.prepare_command() self.cmd.run() @@ -178,9 +178,6 @@ class UploadDocsTestCase(support.TempdirManager, self.assertTrue(record, "should report the response") self.assertIn(self.pypi.default_response_data, record) -UploadDocsTestCase = unittest.skipIf(threading is None, "Needs threading")( - UploadDocsTestCase) - def test_suite(): return unittest.makeSuite(UploadDocsTestCase) diff --git a/distutils2/tests/test_compiler.py b/distutils2/tests/test_compiler.py index 3bc7c3f..d67805a 100644 --- a/distutils2/tests/test_compiler.py +++ b/distutils2/tests/test_compiler.py @@ -6,7 +6,7 @@ from distutils2.compiler import (get_default_compiler, customize_compiler, from distutils2.tests import unittest, support -class FakeCompiler(object): +class FakeCompiler: name = 'fake' description = 'Fake' @@ -36,7 +36,7 @@ class CompilerTestCase(support.EnvironRestorer, unittest.TestCase): os.environ['ARFLAGS'] = '-arflags' # make sure AR gets caught - class compiler(object): + class compiler: name = 'unix' def set_executables(self, **kw): diff --git a/distutils2/tests/test_config.py b/distutils2/tests/test_config.py index d3a0cc4..dfee483 100644 --- a/distutils2/tests/test_config.py +++ b/distutils2/tests/test_config.py @@ -1,4 +1,3 @@ -# encoding: utf-8 """Tests for distutils2.config.""" import os import sys @@ -13,7 +12,7 @@ from distutils2.tests import unittest, support from distutils2.tests.support import requires_zlib -SETUP_CFG = u""" +SETUP_CFG = """ [metadata] name = RestingParrot version = 0.6.4 @@ -174,7 +173,7 @@ def logging_hook(config): """ -class DCompiler(object): +class DCompiler: name = 'd' description = 'D Compiler' @@ -194,7 +193,7 @@ def third_hook(config): config['files']['modules'] += '\n third' -class FooBarBazTest(object): +class FooBarBazTest: def __init__(self, dist): self.distribution = dist @@ -485,11 +484,8 @@ class ConfigTestCase(support.TempdirManager, cmd.finalize_options() cmd.get_file_list() cmd.make_distribution() - fp = open('MANIFEST') - try: + with open('MANIFEST') as fp: self.assertIn('README\nREADME2\n', fp.read()) - finally: - fp.close() def test_sub_commands(self): self.write_setup() diff --git a/distutils2/tests/test_create.py b/distutils2/tests/test_create.py index ba44fc0..43dad60 100644 --- a/distutils2/tests/test_create.py +++ b/distutils2/tests/test_create.py @@ -1,8 +1,6 @@ -# encoding: utf-8 """Tests for distutils2.create.""" import os import sys -import codecs from textwrap import dedent from distutils2 import create from distutils2.create import MainProgram, ask_yn, ask, main @@ -32,23 +30,23 @@ class CreateTestCase(support.TempdirManager, def tearDown(self): sysconfig.get_paths = self._old_get_paths - if hasattr(create, 'raw_input'): - del create.raw_input + if hasattr(create, 'input'): + del create.input super(CreateTestCase, self).tearDown() def test_ask_yn(self): - create.raw_input = Inputs('y') + create.input = Inputs('y') self.assertEqual('y', ask_yn('is this a test')) def test_ask(self): - create.raw_input = Inputs('a', 'b') + 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() - create.raw_input = Inputs('aaaaa') + create.input = Inputs('aaaaa') mainprogram.data['author'] = [] mainprogram._set_multi('_set_multi test', 'author') self.assertEqual(['aaaaa'], mainprogram.data['author']) @@ -89,7 +87,7 @@ class CreateTestCase(support.TempdirManager, def test_convert_setup_py_to_cfg(self): self.write_file((self.wdir, 'setup.py'), - dedent(u""" + dedent(""" # coding: utf-8 from distutils.core import setup @@ -123,17 +121,14 @@ class CreateTestCase(support.TempdirManager, scripts=['my_script', 'bin/run'], ) """), encoding='utf-8') - create.raw_input = Inputs('y') + create.input = Inputs('y') main() path = os.path.join(self.wdir, 'setup.cfg') - fp = codecs.open(path, encoding='utf-8') - try: + with open(path, encoding='utf-8') as fp: contents = fp.read() - finally: - fp.close() - self.assertEqual(contents, dedent(u"""\ + self.assertEqual(contents, dedent("""\ [metadata] name = pyxfoil version = 0.2 @@ -172,14 +167,11 @@ class CreateTestCase(support.TempdirManager, def test_convert_setup_py_to_cfg_with_description_in_readme(self): self.write_file((self.wdir, 'setup.py'), - dedent(u""" + dedent(""" # coding: utf-8 from distutils.core import setup - fp = open('README.txt') - try: + with open('README.txt') as fp: long_description = fp.read() - finally: - fp.close() setup(name='pyxfoil', version='0.2', @@ -203,17 +195,14 @@ My super Death-scription barbar is now in the public domain, ho, baby! ''')) - create.raw_input = Inputs('y') + create.input = Inputs('y') main() path = os.path.join(self.wdir, 'setup.cfg') - fp = codecs.open(path, encoding='utf-8') - try: + with open(path, encoding='utf-8') as fp: contents = fp.read() - finally: - fp.close() - self.assertEqual(contents, dedent(u"""\ + self.assertEqual(contents, dedent("""\ [metadata] name = pyxfoil version = 0.2 diff --git a/distutils2/tests/test_database.py b/distutils2/tests/test_database.py index 6975258..06d6d7f 100644 --- a/distutils2/tests/test_database.py +++ b/distutils2/tests/test_database.py @@ -1,11 +1,9 @@ import os +import io import csv import sys import tempfile -try: - from hashlib import md5 -except ImportError: - from distutils2._backport.hashlib import md5 +from hashlib import md5 from textwrap import dedent from distutils2.tests.test_util import GlobTestCaseBase @@ -29,11 +27,8 @@ from distutils2._backport import shutil def get_hexdigest(filename): - fp = open(filename, 'rb') - try: - checksum = md5(fp.read()) - finally: - fp.close() + with open(filename, 'rb') as file: + checksum = md5(file.read()) return checksum.hexdigest() @@ -44,7 +39,7 @@ def record_pieces(path): return path, digest, size -class FakeDistsMixin(object): +class FakeDistsMixin: def setUp(self): super(FakeDistsMixin, self).setUp() @@ -66,11 +61,11 @@ class FakeDistsMixin(object): # shutil gives no control over the mode of directories :( # see http://bugs.python.org/issue1666318 for root, dirs, files in os.walk(self.fake_dists_path): - os.chmod(root, 0755) + os.chmod(root, 0o755) for f in files: - os.chmod(os.path.join(root, f), 0644) + os.chmod(os.path.join(root, f), 0o644) for d in dirs: - os.chmod(os.path.join(root, d), 0755) + os.chmod(os.path.join(root, d), 0o755) class CommonDistributionTests(FakeDistsMixin): @@ -107,9 +102,9 @@ class CommonDistributionTests(FakeDistsMixin): name, version, distdir = self.sample_dist dist = self.cls(self._get_dist_path(distdir)) self.assertEqual(name, dist.name) - # Sanity test: dist.name is unicode, + # Sanity test: dist.name is a unicode string, # but str output contains no u prefix. - self.assertIsInstance(dist.name, unicode) + self.assertIsInstance(dist.name, str) self.assertEqual(version, dist.version) self.assertEqual(str(dist), self.expected_str_output) @@ -153,10 +148,9 @@ class TestDistribution(CommonDistributionTests, unittest.TestCase): for distinfo_dir in self.dirs: record_file = os.path.join(distinfo_dir, 'RECORD') - fp = open(record_file, 'w') - try: + with open(record_file, 'w') as file: record_writer = csv.writer( - fp, delimiter=',', quoting=csv.QUOTE_NONE, + file, delimiter=',', quoting=csv.QUOTE_NONE, lineterminator='\n') dist_location = distinfo_dir.replace('.dist-info', '') @@ -167,12 +161,9 @@ class TestDistribution(CommonDistributionTests, unittest.TestCase): for file in ('INSTALLER', 'METADATA', 'REQUESTED'): record_writer.writerow(record_pieces((distinfo_dir, file))) record_writer.writerow([record_file]) - finally: - fp.close() - fp = open(record_file) - try: - record_reader = csv.reader(fp, lineterminator='\n') + with open(record_file) as file: + record_reader = csv.reader(file, lineterminator='\n') record_data = {} for row in record_reader: if row == []: @@ -180,8 +171,6 @@ class TestDistribution(CommonDistributionTests, unittest.TestCase): path, md5_, size = (row[:] + [None for i in range(len(row), 3)]) record_data[path] = md5_, size - finally: - fp.close() self.records[distinfo_dir] = record_data def test_instantiation(self): @@ -225,14 +214,11 @@ class TestDistribution(CommonDistributionTests, unittest.TestCase): ] for distfile in distinfo_files: - value = dist.get_distinfo_file(distfile) - try: - self.assertIsInstance(value, file) + with dist.get_distinfo_file(distfile) as value: + self.assertIsInstance(value, io.TextIOWrapper) # Is it the correct file? self.assertEqual(value.name, os.path.join(distinfo_dir, distfile)) - finally: - value.close() # Test an absolute path that is part of another distributions dist-info other_distinfo_file = os.path.join( @@ -675,8 +661,7 @@ class DataFilesTestCase(GlobTestCaseBase): metadata_path = os.path.join(dist_info, 'METADATA') resources_path = os.path.join(dist_info, 'RESOURCES') - fp = open(metadata_path, 'w') - try: + with open(metadata_path, 'w') as fp: fp.write(dedent("""\ Metadata-Version: 1.2 Name: test @@ -684,25 +669,18 @@ class DataFilesTestCase(GlobTestCaseBase): Summary: test Author: me """)) - finally: - fp.close() + test_path = 'test.cfg' fd, test_resource_path = tempfile.mkstemp() os.close(fd) self.addCleanup(os.remove, test_resource_path) - fp = open(test_resource_path, 'w') - try: + with open(test_resource_path, 'w') as fp: fp.write('Config') - finally: - fp.close() - fp = open(resources_path, 'w') - try: + with open(resources_path, 'w') as fp: fp.write('%s,%s' % (test_path, test_resource_path)) - finally: - fp.close() # Add fake site-packages to sys.path to retrieve fake dist self.addCleanup(sys.path.remove, temp_site_packages) @@ -717,11 +695,8 @@ class DataFilesTestCase(GlobTestCaseBase): test_resource_path) self.assertRaises(KeyError, get_file_path, dist_name, 'i-dont-exist') - fp = get_file(dist_name, test_path) - try: + with get_file(dist_name, test_path) as fp: self.assertEqual(fp.read(), 'Config') - finally: - fp.close() self.assertRaises(KeyError, get_file, dist_name, 'i-dont-exist') diff --git a/distutils2/tests/test_depgraph.py b/distutils2/tests/test_depgraph.py index 145ce57..5c58971 100644 --- a/distutils2/tests/test_depgraph.py +++ b/distutils2/tests/test_depgraph.py @@ -2,7 +2,7 @@ import os import re import sys -from StringIO import StringIO +from io import StringIO from distutils2 import depgraph from distutils2.database import get_distribution, enable_cache, disable_cache diff --git a/distutils2/tests/test_dist.py b/distutils2/tests/test_dist.py index 97d2885..bacfdd0 100644 --- a/distutils2/tests/test_dist.py +++ b/distutils2/tests/test_dist.py @@ -56,12 +56,9 @@ class DistributionTestCase(support.TempdirManager, def test_debug_mode(self): tmpdir = self.mkdtemp() setupcfg = os.path.join(tmpdir, 'setup.cfg') - f = open(setupcfg, "w") - try: + with open(setupcfg, "w") as f: f.write("[global]\n") f.write("command_packages = foo.bar, splat") - finally: - f.close() files = [setupcfg] sys.argv.append("build") @@ -132,11 +129,8 @@ class DistributionTestCase(support.TempdirManager, temp_dir = self.mkdtemp() user_filename = os.path.join(temp_dir, user_filename) - f = open(user_filename, 'w') - try: + with open(user_filename, 'w') as f: f.write('.') - finally: - f.close() dist = Distribution() @@ -152,11 +146,8 @@ class DistributionTestCase(support.TempdirManager, else: user_filename = os.path.join(temp_home, "pydistutils.cfg") - f = open(user_filename, 'w') - try: + with open(user_filename, 'w') as f: f.write('[distutils2]\n') - finally: - f.close() def _expander(path): return temp_home diff --git a/distutils2/tests/test_install.py b/distutils2/tests/test_install.py index 59e7d51..197129e 100644 --- a/distutils2/tests/test_install.py +++ b/distutils2/tests/test_install.py @@ -19,7 +19,7 @@ except ImportError: use_xmlrpc_server = fake_dec -class InstalledDist(object): +class InstalledDist: """Distribution object, represent distributions currently installed on the system""" def __init__(self, name, version, deps): @@ -34,7 +34,7 @@ class InstalledDist(object): return '<InstalledDist %r>' % self.metadata['Name'] -class ToInstallDist(object): +class ToInstallDist: """Distribution that will be installed""" def __init__(self, files=False): @@ -64,7 +64,7 @@ class ToInstallDist(object): return self.list_installed_files() -class MagicMock(object): +class MagicMock: def __init__(self, return_value=None, raise_exception=False): self.called = False self._times_called = 0 diff --git a/distutils2/tests/test_manifest.py b/distutils2/tests/test_manifest.py index a858265..e6072d8 100644 --- a/distutils2/tests/test_manifest.py +++ b/distutils2/tests/test_manifest.py @@ -1,7 +1,7 @@ """Tests for distutils2.manifest.""" import os import re -from StringIO import StringIO +from io import StringIO from distutils2.errors import PackagingTemplateError from distutils2.manifest import Manifest, _translate_pattern, _glob_to_re @@ -56,11 +56,8 @@ class ManifestTestCase(support.TempdirManager, def test_manifest_reader(self): tmpdir = self.mkdtemp() MANIFEST = os.path.join(tmpdir, 'MANIFEST.in') - f = open(MANIFEST, 'w') - try: + with open(MANIFEST, 'w') as f: f.write(MANIFEST_IN_2) - finally: - f.close() manifest = Manifest() manifest.read_template(MANIFEST) @@ -73,11 +70,8 @@ class ManifestTestCase(support.TempdirManager, self.assertIn('no files found matching', warning) # manifest also accepts file-like objects - f = open(MANIFEST) - try: + with open(MANIFEST) as f: manifest.read_template(f) - finally: - f.close() # the manifest should have been read and 3 warnings issued # (we didn't provide the files) diff --git a/distutils2/tests/test_markers.py b/distutils2/tests/test_markers.py index be82a88..872f54b 100644 --- a/distutils2/tests/test_markers.py +++ b/distutils2/tests/test_markers.py @@ -3,7 +3,6 @@ import os import sys import platform from distutils2.markers import interpret -from distutils2._backport.misc import python_implementation from distutils2.tests import unittest from distutils2.tests.support import LoggingCatcher @@ -18,7 +17,7 @@ class MarkersTestCase(LoggingCatcher, os_name = os.name platform_version = platform.version() platform_machine = platform.machine() - platform_python_implementation = python_implementation() + platform_python_implementation = platform.python_implementation() self.assertTrue(interpret("sys.platform == '%s'" % sys_platform)) self.assertTrue(interpret( diff --git a/distutils2/tests/test_metadata.py b/distutils2/tests/test_metadata.py index 600d5ea..96ea73b 100644 --- a/distutils2/tests/test_metadata.py +++ b/distutils2/tests/test_metadata.py @@ -1,10 +1,8 @@ -# encoding: utf-8 """Tests for distutils2.metadata.""" import os import sys -import codecs from textwrap import dedent -from StringIO import StringIO +from io import StringIO from distutils2.errors import (MetadataConflictError, MetadataMissingError, MetadataUnrecognizedVersionError) @@ -36,12 +34,8 @@ class MetadataTestCase(LoggingCatcher, def test_instantiation(self): PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO') - f = codecs.open(PKG_INFO, 'r', encoding='utf-8') - try: + with open(PKG_INFO, 'r', encoding='utf-8') as f: contents = f.read() - finally: - f.close() - fp = StringIO(contents) m = Metadata() @@ -69,11 +63,8 @@ class MetadataTestCase(LoggingCatcher, def test_metadata_markers(self): # see if we can be platform-aware PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO') - f = codecs.open(PKG_INFO, 'r', encoding='utf-8') - try: + with open(PKG_INFO, 'r', encoding='utf-8') as f: content = f.read() % sys.platform - finally: - f.close() metadata = Metadata(platform_dependent=True) metadata.read_file(StringIO(content)) @@ -91,11 +82,8 @@ class MetadataTestCase(LoggingCatcher, def test_mapping_api(self): PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO') - f = codecs.open(PKG_INFO, 'r', encoding='utf-8') - try: + with open(PKG_INFO, 'r', encoding='utf-8') as f: content = f.read() % sys.platform - finally: - f.close() metadata = Metadata(fileobj=StringIO(content)) self.assertIn('Version', metadata.keys()) self.assertIn('0.5', metadata.values()) @@ -110,6 +98,8 @@ class MetadataTestCase(LoggingCatcher, metadata.update({'version': '1--2'}) self.assertEqual(len(self.get_logs()), 1) + # XXX caveat: the keys method and friends are not 3.x-style views + # should be changed or documented self.assertEqual(list(metadata), metadata.keys()) def test_read_metadata(self): @@ -142,21 +132,18 @@ class MetadataTestCase(LoggingCatcher, tmp_dir = self.mkdtemp() my_file = os.path.join(tmp_dir, 'f') - metadata = Metadata(mapping={'author': u'Mister Café', - 'name': u'my.project', - 'author': u'Café Junior', - 'summary': u'Café torréfié', - 'description': u'Héhéhé', - 'keywords': [u'café', u'coffee']}) + metadata = Metadata(mapping={'author': 'Mister Café', + 'name': 'my.project', + 'author': 'Café Junior', + 'summary': 'Café torréfié', + 'description': 'Héhéhé', + 'keywords': ['café', 'coffee']}) metadata.write(my_file) # the file should use UTF-8 metadata2 = Metadata() - fp = codecs.open(my_file, encoding='utf-8') - try: + with open(my_file, encoding='utf-8') as fp: metadata2.read_file(fp) - finally: - fp.close() # XXX when keywords are not defined, metadata will have # 'Keywords': [] but metadata2 will have 'Keywords': [''] @@ -164,19 +151,16 @@ class MetadataTestCase(LoggingCatcher, self.assertEqual(metadata.items(), metadata2.items()) # ASCII also works, it's a subset of UTF-8 - metadata = Metadata(mapping={'author': u'Mister Cafe', - 'name': u'my.project', - 'author': u'Cafe Junior', - 'summary': u'Cafe torrefie', - 'description': u'Hehehe'}) + metadata = Metadata(mapping={'author': 'Mister Cafe', + 'name': 'my.project', + 'author': 'Cafe Junior', + 'summary': 'Cafe torrefie', + 'description': 'Hehehe'}) metadata.write(my_file) metadata2 = Metadata() - fp = codecs.open(my_file, encoding='utf-8') - try: + with open(my_file, encoding='utf-8') as fp: metadata2.read_file(fp) - finally: - fp.close() def test_metadata_read_write(self): PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO') @@ -335,21 +319,15 @@ class MetadataTestCase(LoggingCatcher, def test_description(self): PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO') - f = codecs.open(PKG_INFO, 'r', encoding='utf-8') - try: + with open(PKG_INFO, 'r', encoding='utf-8') as f: content = f.read() % sys.platform - finally: - f.close() metadata = Metadata() metadata.read_file(StringIO(content)) # see if we can read the description now DESC = os.path.join(os.path.dirname(__file__), 'LONG_DESC.txt') - f = open(DESC) - try: + with open(DESC) as f: wanted = f.read() - finally: - f.close() self.assertEqual(wanted, metadata['Description']) # save the file somewhere and make sure we can read it back diff --git a/distutils2/tests/test_mixin2to3.py b/distutils2/tests/test_mixin2to3.py index bfd5102..3b5be04 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 @@ -15,23 +14,16 @@ class Mixin2to3TestCase(support.TempdirManager, def check(self, source, wanted, **kwargs): source = textwrap.dedent(source) - fp = open(self.filename, 'w') - try: + with open(self.filename, 'w') as fp: fp.write(source) - finally: - fp.close() Mixin2to3()._run_2to3(**kwargs) - fp = open(self.filename) wanted = textwrap.dedent(wanted) - try: + with open(self.filename) as fp: converted = fp.read() - finally: - fp.close() self.assertMultiLineEqual(converted, wanted) - @support.requires_py26_min def test_conversion(self): # check that code and doctests get converted self.check('''\ @@ -57,7 +49,6 @@ class Mixin2to3TestCase(support.TempdirManager, ''', # 2to3 adds a newline here files=[self.filename]) - @support.requires_py26_min def test_doctests_conversion(self): # check that doctest files are converted self.check('''\ @@ -75,7 +66,6 @@ class Mixin2to3TestCase(support.TempdirManager, ''', doctests=[self.filename]) - @support.requires_py26_min def test_additional_fixers(self): # make sure the fixers argument works self.check("""\ diff --git a/distutils2/tests/test_msvc9compiler.py b/distutils2/tests/test_msvc9compiler.py index 7485ff3..eadec57 100644 --- a/distutils2/tests/test_msvc9compiler.py +++ b/distutils2/tests/test_msvc9compiler.py @@ -118,22 +118,16 @@ class msvc9compilerTestCase(support.TempdirManager, from distutils2.compiler.msvc9compiler import MSVCCompiler tempdir = self.mkdtemp() manifest = os.path.join(tempdir, 'manifest') - f = open(manifest, 'w') - try: + with open(manifest, 'w') as f: f.write(_MANIFEST) - finally: - f.close() compiler = MSVCCompiler() compiler._remove_visual_c_ref(manifest) # see what we got - f = open(manifest) - try: + with open(manifest) as f: # removing trailing spaces content = '\n'.join(line.rstrip() for line in f.readlines()) - finally: - f.close() # makes sure the manifest was properly cleaned self.assertEqual(content, _CLEANED_MANIFEST) diff --git a/distutils2/tests/test_pypi_server.py b/distutils2/tests/test_pypi_server.py index 8027401..36eb3d4 100644 --- a/distutils2/tests/test_pypi_server.py +++ b/distutils2/tests/test_pypi_server.py @@ -1,5 +1,7 @@ """Tests for distutils2.command.bdist.""" -import urllib2 +import urllib.request +import urllib.parse +import urllib.error try: import threading @@ -13,6 +15,7 @@ except ImportError: from distutils2.tests import unittest +@unittest.skipIf(threading is None, "Needs threading") class PyPIServerTest(unittest.TestCase): def test_records_requests(self): @@ -24,12 +27,13 @@ class PyPIServerTest(unittest.TestCase): server.start() self.assertEqual(len(server.requests), 0) - data = 'Rock Around The Bunker' + data = b'Rock Around The Bunker' headers = {"X-test-header": "Mister Iceberg"} - request = urllib2.Request(server.full_address, data, headers) - urllib2.urlopen(request) + request = urllib.request.Request( + server.full_address, data, headers) + urllib.request.urlopen(request) self.assertEqual(len(server.requests), 1) handler, request_data = server.requests[-1] self.assertIn(data, request_data) @@ -48,14 +52,11 @@ class PyPIServerTest(unittest.TestCase): server is the same than the one made by a simple file read. """ url = server.full_address + url_path - request = urllib2.Request(url) - response = urllib2.urlopen(request) - file = open(PYPI_DEFAULT_STATIC_PATH + "/test_pypi_server" - + url_path) - try: + request = urllib.request.Request(url) + response = urllib.request.urlopen(request) + with open(PYPI_DEFAULT_STATIC_PATH + "/test_pypi_server" + + url_path) as file: return response.read().decode() == file.read() - finally: - file.close() server = PyPIServer(static_uri_paths=["simple", "external"], static_filesystem_paths=["test_pypi_server"]) @@ -63,10 +64,10 @@ class PyPIServerTest(unittest.TestCase): try: # the file does not exists on the disc, so it might not be served url = server.full_address + "/simple/unexisting_page" - request = urllib2.Request(url) + request = urllib.request.Request(url) try: - urllib2.urlopen(request) - except urllib2.HTTPError, e: + urllib.request.urlopen(request) + except urllib.error.HTTPError as e: self.assertEqual(e.code, 404) # now try serving a content that do exists @@ -80,10 +81,6 @@ class PyPIServerTest(unittest.TestCase): server.stop() -PyPIServerTest = unittest.skipIf(threading is None, "Needs threading")( - PyPIServerTest) - - def test_suite(): return unittest.makeSuite(PyPIServerTest) diff --git a/distutils2/tests/test_pypi_simple.py b/distutils2/tests/test_pypi_simple.py index ba65abf..196f8ec 100644 --- a/distutils2/tests/test_pypi_simple.py +++ b/distutils2/tests/test_pypi_simple.py @@ -2,8 +2,10 @@ import re import os import sys -import httplib -import urllib2 +import http.client +import urllib.error +import urllib.parse +import urllib.request from distutils2.pypi.simple import Crawler @@ -12,7 +14,7 @@ from distutils2.tests.support import (TempdirManager, LoggingCatcher, fake_dec) try: - import thread as _thread + import _thread from distutils2.tests.pypi_server import (use_pypi_server, PyPIServer, PYPI_DEFAULT_STATIC_PATH) except ImportError: @@ -43,11 +45,11 @@ class SimpleCrawlerTestCase(TempdirManager, url = 'http://127.0.0.1:0/nonesuch/test_simple' try: v = crawler._open_url(url) - except Exception, v: + except Exception as v: self.assertIn(url, str(v)) else: v.close() - self.assertIsInstance(v, urllib2.HTTPError) + self.assertIsInstance(v, urllib.error.HTTPError) # issue 16 # easy_install inquant.contentmirror.plone breaks because of a typo @@ -57,36 +59,35 @@ class SimpleCrawlerTestCase(TempdirManager, 'inquant.contentmirror.plone/trunk') try: v = crawler._open_url(url) - except Exception, v: + except Exception as v: self.assertIn(url, str(v)) else: v.close() - self.assertIsInstance(v, urllib2.HTTPError) + self.assertIsInstance(v, urllib.error.HTTPError) def _urlopen(*args): - raise httplib.BadStatusLine('line') + raise http.client.BadStatusLine('line') - old_urlopen = urllib2.urlopen - urllib2.urlopen = _urlopen + old_urlopen = urllib.request.urlopen + urllib.request.urlopen = _urlopen url = 'http://example.org' try: - try: - v = crawler._open_url(url) - except Exception, v: - self.assertIn('line', str(v)) - else: - v.close() - # TODO use self.assertRaises - raise AssertionError('Should have raise here!') + v = crawler._open_url(url) + except Exception as v: + self.assertIn('line', str(v)) + else: + v.close() + # TODO use self.assertRaises + raise AssertionError('Should have raise here!') finally: - urllib2.urlopen = old_urlopen + urllib.request.urlopen = old_urlopen # issue 20 url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' try: crawler._open_url(url) - except Exception, v: - if sys.version_info[:3] < (2, 7, 3): + except Exception as v: + if sys.version_info[:3] < (3, 2, 3): # XXX check versions again wanted = 'nonnumeric port' else: wanted = 'Download error' @@ -278,22 +279,22 @@ class SimpleCrawlerTestCase(TempdirManager, # Test that the simple link matcher yield the good links. generator = crawler._simple_link_matcher(content, crawler.index_url) self.assertEqual(('%stest/foobar-1.tar.gz#md5=abcdef' % - crawler.index_url, True), generator.next()) - self.assertEqual(('http://dl-link1', True), generator.next()) + crawler.index_url, True), next(generator)) + self.assertEqual(('http://dl-link1', True), next(generator)) self.assertEqual(('%stest' % crawler.index_url, False), - generator.next()) - self.assertRaises(StopIteration, generator.next) + next(generator)) + self.assertRaises(StopIteration, generator.__next__) # Follow the external links is possible (eg. homepages) crawler.follow_externals = True generator = crawler._simple_link_matcher(content, crawler.index_url) self.assertEqual(('%stest/foobar-1.tar.gz#md5=abcdef' % - crawler.index_url, True), generator.next()) - self.assertEqual(('http://dl-link1', True), generator.next()) - self.assertEqual(('http://dl-link2', False), generator.next()) + crawler.index_url, True), next(generator)) + self.assertEqual(('http://dl-link1', True), next(generator)) + self.assertEqual(('http://dl-link2', False), next(generator)) self.assertEqual(('%stest' % crawler.index_url, False), - generator.next()) - self.assertRaises(StopIteration, generator.next) + next(generator)) + self.assertRaises(StopIteration, generator.__next__) def test_browse_local_files(self): # Test that we can browse local files""" diff --git a/distutils2/tests/test_pypi_xmlrpc.py b/distutils2/tests/test_pypi_xmlrpc.py index d286bf4..e123fff 100644 --- a/distutils2/tests/test_pypi_xmlrpc.py +++ b/distutils2/tests/test_pypi_xmlrpc.py @@ -13,6 +13,7 @@ except ImportError: use_xmlrpc_server = fake_dec +@unittest.skipIf(threading is None, "Needs threading") class TestXMLRPCClient(unittest.TestCase): def _get_client(self, server, *args, **kwargs): return Client(server.full_address, *args, **kwargs) @@ -91,10 +92,6 @@ class TestXMLRPCClient(unittest.TestCase): self.assertEqual(['FooFoo'], release.metadata['obsoletes_dist']) -TestXMLRPCClient = unittest.skipIf(threading is None, "Needs threading")( - TestXMLRPCClient) - - def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestXMLRPCClient)) diff --git a/distutils2/tests/test_run.py b/distutils2/tests/test_run.py index c1ce4f5..ed6c580 100644 --- a/distutils2/tests/test_run.py +++ b/distutils2/tests/test_run.py @@ -3,7 +3,7 @@ import os import sys import textwrap -from StringIO import StringIO +from io import StringIO from distutils2 import install from distutils2.tests import unittest, support @@ -76,18 +76,18 @@ class RunTestCase(support.TempdirManager, def test_show_help(self): # smoke test, just makes sure some help is displayed out, err = self.call_pysetup('--help') - self.assertGreater(out, '') - self.assertEqual(err, '') + self.assertGreater(out, b'') + self.assertEqual(err, b'') def test_list_commands(self): out, err = self.call_pysetup('run', '--list-commands') # check that something is displayed - self.assertGreater(out, '') - self.assertEqual(err, '') + self.assertGreater(out, b'') + self.assertEqual(err, b'') # make sure the manual grouping of commands is respected - check_position = out.find(' check: ') - build_position = out.find(' build: ') + check_position = out.find(b' check: ') + build_position = out.find(b' build: ') self.assertTrue(check_position, out) # "out" printed as debugging aid self.assertTrue(build_position, out) self.assertLess(check_position, build_position, out) @@ -96,30 +96,30 @@ class RunTestCase(support.TempdirManager, def test_unknown_command_option(self): out, err = self.call_pysetup_fail('run', 'build', '--unknown') - self.assertGreater(out, '') + self.assertGreater(out, b'') # sadly this message comes straight from the getopt module and can't be # modified to use repr instead of str for the unknown option; to be # changed when the command line parsers are replaced by something clean self.assertEqual(err.splitlines(), - ['error: option --unknown not recognized']) + [b'error: option --unknown not recognized']) def test_invalid_command(self): out, err = self.call_pysetup_fail('run', 'com#mand') - self.assertGreater(out, '') + self.assertGreater(out, b'') self.assertEqual(err.splitlines(), - ["error: invalid command name 'com#mand'"]) + [b"error: invalid command name 'com#mand'"]) def test_unknown_command(self): out, err = self.call_pysetup_fail('run', 'invalid_command') - self.assertGreater(out, '') + self.assertGreater(out, b'') self.assertEqual(err.splitlines(), - ["error: command 'invalid_command' not recognized"]) + [b"error: command 'invalid_command' not recognized"]) def test_unknown_action(self): out, err = self.call_pysetup_fail('invalid_action') - self.assertGreater(out, '') + self.assertGreater(out, b'') self.assertEqual(err.splitlines(), - ["error: action 'invalid_action' not recognized"]) + [b"error: action 'invalid_action' not recognized"]) def test_setupcfg_parsing(self): # #14733: pysetup used to parse setup.cfg too late @@ -140,7 +140,7 @@ class RunTestCase(support.TempdirManager, pass def run(self): - print 'custom: ok' + print('custom: ok') """) setupcfg = textwrap.dedent( """\ @@ -151,8 +151,8 @@ class RunTestCase(support.TempdirManager, self.write_file('setup.cfg', setupcfg) out, err = self.call_pysetup('run', 'custom') - self.assertEqual(err.splitlines(), ['running custom']) - self.assertEqual(out.splitlines(), ['custom: ok']) + self.assertEqual(err.splitlines(), [b'running custom']) + self.assertEqual(out.splitlines(), [b'custom: ok']) def test_suite(): diff --git a/distutils2/tests/test_util.py b/distutils2/tests/test_util.py index ea9535f..1c657fe 100644 --- a/distutils2/tests/test_util.py +++ b/distutils2/tests/test_util.py @@ -5,8 +5,9 @@ import time import logging import tempfile import textwrap +import warnings import subprocess -from StringIO import StringIO +from io import StringIO from distutils2.errors import ( PackagingPlatformError, PackagingFileError, @@ -59,24 +60,24 @@ password:xxx """ EXPECTED_MULTIPART_OUTPUT = [ - '---x', - 'Content-Disposition: form-data; name="username"', - '', - 'wok', - '---x', - 'Content-Disposition: form-data; name="password"', - '', - 'secret', - '---x', - 'Content-Disposition: form-data; name="picture"; filename="wok.png"', - '', - 'PNG89', - '---x--', - '', + b'---x', + b'Content-Disposition: form-data; name="username"', + b'', + b'wok', + b'---x', + b'Content-Disposition: form-data; name="password"', + b'', + b'secret', + b'---x', + b'Content-Disposition: form-data; name="picture"; filename="wok.png"', + b'', + b'PNG89', + b'---x--', + b'', ] -class FakePopen(object): +class FakePopen: test_class = None def __init__(self, args, bufsize=0, executable=None, @@ -86,7 +87,7 @@ class FakePopen(object): startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=()): - if isinstance(args, basestring): + if isinstance(args, str): args = args.split() self.cmd = args[0] exes = self.test_class._exes @@ -329,8 +330,6 @@ class UtilTestCase(support.EnvironRestorer, res = get_compiler_versions() self.assertEqual(res[2], None) - @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'), - 'sys.dont_write_bytecode not supported') def test_byte_compile_under_B(self): # make sure byte compilation works under -B (dont_write_bytecode) self.addCleanup(setattr, sys, 'dont_write_bytecode', @@ -412,7 +411,7 @@ class UtilTestCase(support.EnvironRestorer, self.assertEqual(resolve_name('sys').__name__, 'sys') # test module.attr - self.assertIs(resolve_name('__builtin__.str'), str) + 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') @@ -432,7 +431,6 @@ class UtilTestCase(support.EnvironRestorer, self.assertRaises(ImportError, resolve_name, 'a.b.Spam') self.assertRaises(ImportError, resolve_name, 'a.b.c.Spam') - @support.requires_py26_min @support.skip_2to3_optimize def test_run_2to3_on_code(self): content = "print 'test'" @@ -447,7 +445,6 @@ class UtilTestCase(support.EnvironRestorer, file_handle.close() self.assertEqual(new_content, converted_content) - @support.requires_py26_min @support.skip_2to3_optimize def test_run_2to3_on_doctests(self): # to check if text files containing doctests only get converted. @@ -473,24 +470,24 @@ class UtilTestCase(support.EnvironRestorer, if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 1') - os.chmod(exe, 0777) + os.chmod(exe, 0o777) else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 1') - os.chmod(exe, 0777) + os.chmod(exe, 0o777) self.assertRaises(PackagingExecError, spawn, [exe]) # now something that works if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 0') - os.chmod(exe, 0777) + os.chmod(exe, 0o777) else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 0') - os.chmod(exe, 0777) + os.chmod(exe, 0o777) spawn([exe]) # should work without any error def test_server_registration(self): @@ -522,11 +519,8 @@ class UtilTestCase(support.EnvironRestorer, self.assertFalse(os.path.exists(rc)) generate_pypirc('tarek', 'xxx') self.assertTrue(os.path.exists(rc)) - f = open(rc) - try: + with open(rc) as f: content = f.read() - finally: - f.close() self.assertEqual(content, WANTED) def test_cfg_to_args(self): @@ -535,10 +529,14 @@ class UtilTestCase(support.EnvironRestorer, self.write_file('setup.cfg', SETUP_CFG % opts, encoding='utf-8') self.write_file('README', 'loooong description') - args = cfg_to_args() + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + args = cfg_to_args() # use Distribution to get the contents of the setup.cfg file dist = Distribution() - dist.parse_config_files() + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + dist.parse_config_files() metadata = dist.metadata self.assertEqual(args['name'], metadata['Name']) @@ -571,20 +569,20 @@ class UtilTestCase(support.EnvironRestorer, generate_setup_py() self.assertTrue(os.path.exists('setup.py'), 'setup.py not created') rc, out, err = assert_python_ok('setup.py', '--name') - self.assertEqual(out, 'SPAM\n') - self.assertEqual(err, '') + self.assertEqual(out, b'SPAM\n') + self.assertEqual(err, b'') # a generated setup.py should complain if no setup.cfg is present os.unlink('setup.cfg') rc, out, err = assert_python_failure('setup.py', '--name') - self.assertIn('setup.cfg', err) + self.assertIn(b'setup.cfg', err) def test_encode_multipart(self): fields = [('username', 'wok'), ('password', 'secret')] - files = [('picture', 'wok.png', 'PNG89')] - content_type, body = encode_multipart(fields, files, '-x') - self.assertEqual('multipart/form-data; boundary=-x', content_type) - self.assertEqual(EXPECTED_MULTIPART_OUTPUT, body.split('\r\n')) + files = [('picture', 'wok.png', b'PNG89')] + content_type, body = encode_multipart(fields, files, b'-x') + self.assertEqual(b'multipart/form-data; boundary=-x', content_type) + self.assertEqual(EXPECTED_MULTIPART_OUTPUT, body.split(b'\r\n')) class GlobTestCaseBase(support.TempdirManager, @@ -831,7 +829,9 @@ class EggInfoToDistInfoTestCase(support.TempdirManager, distinfo_path = os.path.join(tempdir, distinfo) egginfo_path = os.path.join(tempdir, egginfo) metadata_file_paths = self.get_metadata_file_paths(distinfo_path) + egginfo_to_distinfo(record_file) + # test that directories and files get created self.assertTrue(os.path.isdir(distinfo_path)) self.assertTrue(os.path.isfile(egginfo_path)) @@ -854,21 +854,16 @@ class EggInfoToDistInfoTestCase(support.TempdirManager, content = '' path = os.path.join(tempdir, f) - _f = open(path, 'w') - try: + with open(path, 'w') as _f: _f.write(content) - finally: - _f.close() file_paths.append(path) - record_file = open(record_file_path, 'w') - try: + with open(record_file_path, 'w') as record_file: for fpath in file_paths: record_file.write(fpath + '\n') for dpath in dir_paths: record_file.write(dpath + '\n') - finally: - record_file.close() + return (tempdir, record_file_path) @@ -928,7 +923,9 @@ class PackagingLibChecks(support.TempdirManager, def test_get_install_method_with_packaging_pkg(self): path = self._valid_setup_cfg_pkg() - self.assertEqual("distutils2", get_install_method(path)) + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + self.assertEqual("distutils2", get_install_method(path)) def test_get_install_method_with_unknown_pkg(self): path = self._invalid_setup_cfg_pkg() diff --git a/distutils2/tests/xxmodule.c b/distutils2/tests/xxmodule.c index 6b498dd..a8a9360 100644 --- a/distutils2/tests/xxmodule.c +++ b/distutils2/tests/xxmodule.c @@ -10,7 +10,7 @@ your own types of attributes instead. Maybe you want to name your local variables other than 'self'. If your object type is needed in other files, you'll have to create a file "foobarobject.h"; see - intobject.h for an example. */ + floatobject.h for an example. */ /* Xxo objects */ @@ -19,23 +19,23 @@ static PyObject *ErrorObject; typedef struct { - PyObject_HEAD - PyObject *x_attr; /* Attributes dictionary */ + PyObject_HEAD + PyObject *x_attr; /* Attributes dictionary */ } XxoObject; static PyTypeObject Xxo_Type; -#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) +#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type) static XxoObject * newXxoObject(PyObject *arg) { - XxoObject *self; - self = PyObject_New(XxoObject, &Xxo_Type); - if (self == NULL) - return NULL; - self->x_attr = NULL; - return self; + XxoObject *self; + self = PyObject_New(XxoObject, &Xxo_Type); + if (self == NULL) + return NULL; + self->x_attr = NULL; + return self; } /* Xxo methods */ @@ -43,101 +43,101 @@ newXxoObject(PyObject *arg) static void Xxo_dealloc(XxoObject *self) { - Py_XDECREF(self->x_attr); - PyObject_Del(self); + Py_XDECREF(self->x_attr); + PyObject_Del(self); } static PyObject * Xxo_demo(XxoObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":demo")) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":demo")) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyMethodDef Xxo_methods[] = { - {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, - PyDoc_STR("demo() -> None")}, - {NULL, NULL} /* sentinel */ + {"demo", (PyCFunction)Xxo_demo, METH_VARARGS, + PyDoc_STR("demo() -> None")}, + {NULL, NULL} /* sentinel */ }; static PyObject * -Xxo_getattr(XxoObject *self, char *name) +Xxo_getattro(XxoObject *self, PyObject *name) { - if (self->x_attr != NULL) { - PyObject *v = PyDict_GetItemString(self->x_attr, name); - if (v != NULL) { - Py_INCREF(v); - return v; - } - } - return Py_FindMethod(Xxo_methods, (PyObject *)self, name); + if (self->x_attr != NULL) { + PyObject *v = PyDict_GetItem(self->x_attr, name); + if (v != NULL) { + Py_INCREF(v); + return v; + } + } + return PyObject_GenericGetAttr((PyObject *)self, name); } static int Xxo_setattr(XxoObject *self, char *name, PyObject *v) { - if (self->x_attr == NULL) { - self->x_attr = PyDict_New(); - if (self->x_attr == NULL) - return -1; - } - if (v == NULL) { - int rv = PyDict_DelItemString(self->x_attr, name); - if (rv < 0) - PyErr_SetString(PyExc_AttributeError, - "delete non-existing Xxo attribute"); - return rv; - } - else - return PyDict_SetItemString(self->x_attr, name, v); + if (self->x_attr == NULL) { + self->x_attr = PyDict_New(); + if (self->x_attr == NULL) + return -1; + } + if (v == NULL) { + int rv = PyDict_DelItemString(self->x_attr, name); + if (rv < 0) + PyErr_SetString(PyExc_AttributeError, + "delete non-existing Xxo attribute"); + return rv; + } + else + return PyDict_SetItemString(self->x_attr, name, v); } static PyTypeObject Xxo_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Xxo", /*tp_name*/ - sizeof(XxoObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)Xxo_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc)Xxo_getattr, /*tp_getattr*/ - (setattrfunc)Xxo_setattr, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Xxo", /*tp_name*/ + sizeof(XxoObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)Xxo_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)0, /*tp_getattr*/ + (setattrfunc)Xxo_setattr, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + (getattrofunc)Xxo_getattro, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + Xxo_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* --------------------------------------------------------------------- */ @@ -151,12 +151,12 @@ Return the sum of i and j."); static PyObject * xx_foo(PyObject *self, PyObject *args) { - long i, j; - long res; - if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) - return NULL; - res = i+j; /* XXX Do something here */ - return PyInt_FromLong(res); + long i, j; + long res; + if (!PyArg_ParseTuple(args, "ll:foo", &i, &j)) + return NULL; + res = i+j; /* XXX Do something here */ + return PyLong_FromLong(res); } @@ -165,14 +165,14 @@ xx_foo(PyObject *self, PyObject *args) static PyObject * xx_new(PyObject *self, PyObject *args) { - XxoObject *rv; - - if (!PyArg_ParseTuple(args, ":new")) - return NULL; - rv = newXxoObject(args); - if (rv == NULL) - return NULL; - return (PyObject *)rv; + XxoObject *rv; + + if (!PyArg_ParseTuple(args, ":new")) + return NULL; + rv = newXxoObject(args); + if (rv == NULL) + return NULL; + return (PyObject *)rv; } /* Example with subtle bug from extensions manual ("Thin Ice"). */ @@ -180,20 +180,20 @@ xx_new(PyObject *self, PyObject *args) static PyObject * xx_bug(PyObject *self, PyObject *args) { - PyObject *list, *item; + PyObject *list, *item; - if (!PyArg_ParseTuple(args, "O:bug", &list)) - return NULL; + if (!PyArg_ParseTuple(args, "O:bug", &list)) + return NULL; - item = PyList_GetItem(list, 0); - /* Py_INCREF(item); */ - PyList_SetItem(list, 1, PyInt_FromLong(0L)); - PyObject_Print(item, stdout, 0); - printf("\n"); - /* Py_DECREF(item); */ + item = PyList_GetItem(list, 0); + /* Py_INCREF(item); */ + PyList_SetItem(list, 1, PyLong_FromLong(0L)); + PyObject_Print(item, stdout, 0); + printf("\n"); + /* Py_DECREF(item); */ - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } /* Test bad format character */ @@ -201,61 +201,61 @@ xx_bug(PyObject *self, PyObject *args) static PyObject * xx_roj(PyObject *self, PyObject *args) { - PyObject *a; - long b; - if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *a; + long b; + if (!PyArg_ParseTuple(args, "O#:roj", &a, &b)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } /* ---------- */ static PyTypeObject Str_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Str", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see initxx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Str", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /* ---------- */ @@ -263,54 +263,54 @@ static PyTypeObject Str_Type = { static PyObject * null_richcompare(PyObject *self, PyObject *other, int op) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } static PyTypeObject Null_Type = { - /* The ob_type field must be initialized in the module init function - * to be portable to Windows without using C++. */ - PyVarObject_HEAD_INIT(NULL, 0) - "xxmodule.Null", /*tp_name*/ - 0, /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - null_richcompare, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /* see initxx */ /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /* see initxx */ /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + /* The ob_type field must be initialized in the module init function + * to be portable to Windows without using C++. */ + PyVarObject_HEAD_INIT(NULL, 0) + "xxmodule.Null", /*tp_name*/ + 0, /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + 0, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_reserved*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + null_richcompare, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + 0, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /* see PyInit_xx */ /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /* see PyInit_xx */ /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; @@ -320,60 +320,77 @@ static PyTypeObject Null_Type = { /* List of functions defined in the module */ static PyMethodDef xx_methods[] = { - {"roj", xx_roj, METH_VARARGS, - PyDoc_STR("roj(a,b) -> None")}, - {"foo", xx_foo, METH_VARARGS, - xx_foo_doc}, - {"new", xx_new, METH_VARARGS, - PyDoc_STR("new() -> new Xx object")}, - {"bug", xx_bug, METH_VARARGS, - PyDoc_STR("bug(o) -> None")}, - {NULL, NULL} /* sentinel */ + {"roj", xx_roj, METH_VARARGS, + PyDoc_STR("roj(a,b) -> None")}, + {"foo", xx_foo, METH_VARARGS, + xx_foo_doc}, + {"new", xx_new, METH_VARARGS, + PyDoc_STR("new() -> new Xx object")}, + {"bug", xx_bug, METH_VARARGS, + PyDoc_STR("bug(o) -> None")}, + {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "This is a template module just for instruction."); -/* Initialization function for the module (*must* be called initxx) */ +/* Initialization function for the module (*must* be called PyInit_xx) */ + + +static struct PyModuleDef xxmodule = { + PyModuleDef_HEAD_INIT, + "xx", + module_doc, + -1, + xx_methods, + NULL, + NULL, + NULL, + NULL +}; PyMODINIT_FUNC -initxx(void) +PyInit_xx(void) { - PyObject *m; - - /* Due to cross platform compiler issues the slots must be filled - * here. It's required for portability to Windows without requiring - * C++. */ - Null_Type.tp_base = &PyBaseObject_Type; - Null_Type.tp_new = PyType_GenericNew; - Str_Type.tp_base = &PyUnicode_Type; - - /* Finalize the type object including setting type of the new type - * object; doing it here is required for portability, too. */ - if (PyType_Ready(&Xxo_Type) < 0) - return; - - /* Create the module and add the functions */ - m = Py_InitModule3("xx", xx_methods, module_doc); - if (m == NULL) - return; - - /* Add some symbolic constants to the module */ - if (ErrorObject == NULL) { - ErrorObject = PyErr_NewException("xx.error", NULL, NULL); - if (ErrorObject == NULL) - return; - } - Py_INCREF(ErrorObject); - PyModule_AddObject(m, "error", ErrorObject); - - /* Add Str */ - if (PyType_Ready(&Str_Type) < 0) - return; - PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); - - /* Add Null */ - if (PyType_Ready(&Null_Type) < 0) - return; - PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); + PyObject *m = NULL; + + /* Due to cross platform compiler issues the slots must be filled + * here. It's required for portability to Windows without requiring + * C++. */ + Null_Type.tp_base = &PyBaseObject_Type; + Null_Type.tp_new = PyType_GenericNew; + Str_Type.tp_base = &PyUnicode_Type; + + /* Finalize the type object including setting type of the new type + * object; doing it here is required for portability, too. */ + if (PyType_Ready(&Xxo_Type) < 0) + goto fail; + + /* Create the module and add the functions */ + m = PyModule_Create(&xxmodule); + if (m == NULL) + goto fail; + + /* Add some symbolic constants to the module */ + if (ErrorObject == NULL) { + ErrorObject = PyErr_NewException("xx.error", NULL, NULL); + if (ErrorObject == NULL) + goto fail; + } + Py_INCREF(ErrorObject); + PyModule_AddObject(m, "error", ErrorObject); + + /* Add Str */ + if (PyType_Ready(&Str_Type) < 0) + goto fail; + PyModule_AddObject(m, "Str", (PyObject *)&Str_Type); + + /* Add Null */ + if (PyType_Ready(&Null_Type) < 0) + goto fail; + PyModule_AddObject(m, "Null", (PyObject *)&Null_Type); + return m; + fail: + Py_XDECREF(m); + return NULL; } |
