diff options
| author | ?ric Araujo <merwok@netwok.org> | 2011-10-05 01:10:36 +0200 |
|---|---|---|
| committer | ?ric Araujo <merwok@netwok.org> | 2011-10-05 01:10:36 +0200 |
| commit | 2ca03bf10e6be1c524b8d2090c2bd09705e2b503 (patch) | |
| tree | 81fb4ba59d899d252c728c34a842b08db7da7c6f /distutils2/tests | |
| parent | 4ae9f13581e67df33042952cedd023e3b3dded8c (diff) | |
| parent | 0330c9fae0c4a17b96ce03ed41b12477931e7e75 (diff) | |
| download | disutils2-2ca03bf10e6be1c524b8d2090c2bd09705e2b503.tar.gz | |
Merge #11841 and other changes from default
Diffstat (limited to 'distutils2/tests')
38 files changed, 542 insertions, 735 deletions
diff --git a/distutils2/tests/__init__.py b/distutils2/tests/__init__.py index cc8927f..bcd944a 100644 --- a/distutils2/tests/__init__.py +++ b/distutils2/tests/__init__.py @@ -7,14 +7,14 @@ to return an initialized unittest.TestSuite instance. Utility code is included in distutils2.tests.support. -Always import unittest from this module, it will be the right version +Always import unittest from this module: it will be unittest from the standard library for packaging tests and unittest2 for distutils2 tests. """ import os import sys import unittest2 as unittest -from StringIO import StringIO +from io import StringIO # XXX move helpers to support, add tests for them, remove things that # duplicate test.support (or keep them for the backport; needs thinking) @@ -42,7 +42,7 @@ class TestFailed(Error): """Test failed.""" -class BasicTestRunner(object): +class BasicTestRunner: def run(self, test): result = unittest.TestResult() test(result) @@ -72,13 +72,13 @@ def _run_suite(suite, verbose_=1): def run_unittest(classes, verbose_=1): """Run tests from unittest.TestCase-derived classes. - Originally extracted from stdlib test.test_support and modified to + Originally extracted from stdlib test.support and modified to support unittest2. """ valid_types = (unittest.TestSuite, unittest.TestCase) suite = unittest.TestSuite() for cls in classes: - if isinstance(cls, basestring): + if isinstance(cls, str): if cls in sys.modules: suite.addTest(unittest.findTestCases(sys.modules[cls])) else: diff --git a/distutils2/tests/__main__.py b/distutils2/tests/__main__.py index e238ed6..3609c64 100644 --- a/distutils2/tests/__main__.py +++ b/distutils2/tests/__main__.py @@ -4,7 +4,7 @@ import os import sys -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/pypi_server.py b/distutils2/tests/pypi_server.py index c98e232..710e055 100644 --- a/distutils2/tests/pypi_server.py +++ b/distutils2/tests/pypi_server.py @@ -30,17 +30,15 @@ implementations (static HTTP and XMLRPC over HTTP). """ import os -import Queue +import queue import select import threading -import SocketServer -from BaseHTTPServer import HTTPServer -from SimpleHTTPServer import SimpleHTTPRequestHandler -from SimpleXMLRPCServer import SimpleXMLRPCServer +import socketserver +from functools import wraps +from http.server import HTTPServer, SimpleHTTPRequestHandler +from xmlrpc.server import SimpleXMLRPCServer from distutils2.tests import unittest -from distutils2.compat import wraps - PYPI_DEFAULT_STATIC_PATH = os.path.join( @@ -116,7 +114,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')] @@ -153,7 +151,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() @@ -170,7 +168,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 @@ -222,18 +220,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))) @@ -269,7 +261,7 @@ 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) @@ -278,12 +270,12 @@ class PyPIRequestHandler(SimpleHTTPRequestHandler): class PyPIXMLRPCServer(SimpleXMLRPCServer): def server_bind(self): """Override server_bind to store the server name.""" - SocketServer.TCPServer.server_bind(self) + socketserver.TCPServer.server_bind(self) host, port = self.socket.getsockname()[:2] 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/", @@ -398,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 92e0241..9938d75 100644 --- a/distutils2/tests/support.py +++ b/distutils2/tests/support.py @@ -83,7 +83,7 @@ class _TestHandler(logging.handlers.BufferingHandler): 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 @@ -139,7 +139,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 @@ -182,11 +182,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. @@ -224,7 +221,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) @@ -251,7 +248,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 @@ -339,6 +336,11 @@ def fixup_build_ext(cmd): cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() + + In addition, this function also fixes cmd.distribution.include_dirs if + the running Python is an uninstalled Python 3.3. (This fix is not done in + packaging, which does not need it, nor in distutils2 for Python 2, which + has no in-development version that can't be expected to be installed.) """ if os.name == 'nt': cmd.debug = sys.executable.endswith('_d.exe') @@ -354,12 +356,17 @@ def fixup_build_ext(cmd): name, equals, value = runshared.partition('=') cmd.library_dirs = value.split(os.pathsep) + # Allow tests to run with an uninstalled Python 3.3 + if sys.version_info[:2] == (3, 3) and sysconfig.is_python_build(): + pysrcdir = sysconfig.get_config_var('projectbase') + cmd.distribution.include_dirs.append(os.path.join(pysrcdir, 'Include')) + 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') + 'requires test.support.skip_unless_symlink') requires_zlib = unittest.skipUnless(zlib, 'requires zlib') @@ -368,7 +375,7 @@ requires_zlib = unittest.skipUnless(zlib, 'requires zlib') 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 @@ -381,7 +388,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_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 4ad0ec5..06b5992 100644 --- a/distutils2/tests/test_command_build_ext.py +++ b/distutils2/tests/test_command_build_ext.py @@ -3,7 +3,7 @@ import sys import site import shutil import textwrap -from StringIO import StringIO +from io import StringIO from distutils2.dist import Distribution from distutils2.errors import (UnknownFileError, CompileError, PackagingPlatformError) @@ -21,18 +21,13 @@ class BuildExtTestCase(support.TempdirManager, def setUp(self): super(BuildExtTestCase, self).setUp() self.tmp_dir = self.mkdtemp() - if sys.version > "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 > "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') @@ -94,7 +89,6 @@ class BuildExtTestCase(support.TempdirManager, # make sure we get some library dirs under solaris self.assertGreater(len(cmd.library_dirs), 0) - @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_user_site(self): dist = Distribution({'name': 'xx'}) cmd = build_ext(dist) @@ -362,8 +356,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> @@ -375,8 +368,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 b659895..7351890 100644 --- a/distutils2/tests/test_command_build_py.py +++ b/distutils2/tests/test_command_build_py.py @@ -61,7 +61,7 @@ class BuildPyTestCase(support.TempdirManager, self.assertIn("__init__.py", files) self.assertIn("README.txt", files) # XXX even with -O, distutils writes pyc, not pyo; bug? - if getattr(sys , 'dont_write_bytecode', False): + if sys.dont_write_bytecode: self.assertNotIn("__init__.pyc", files) else: self.assertIn("__init__.pyc", files) @@ -99,8 +99,6 @@ class BuildPyTestCase(support.TempdirManager, os.chdir(cwd) sys.stdout = old_stdout - @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'), - 'sys.dont_write_bytecode not supported') def test_dont_write_bytecode(self): # makes sure byte_compile is not used pkg_dir, dist = self.create_dist() diff --git a/distutils2/tests/test_command_build_scripts.py b/distutils2/tests/test_command_build_scripts.py index ab41bee..9abd5c3 100644 --- a/distutils2/tests/test_command_build_scripts.py +++ b/distutils2/tests/test_command_build_scripts.py @@ -71,11 +71,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_config.py b/distutils2/tests/test_command_config.py index 7c577b0..91058c7 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_dist.py b/distutils2/tests/test_command_install_dist.py index 409de06..c477299 100644 --- a/distutils2/tests/test_command_install_dist.py +++ b/distutils2/tests/test_command_install_dist.py @@ -72,7 +72,6 @@ class InstallTestCase(support.TempdirManager, check_path(cmd.install_scripts, os.path.join(destination, "bin")) check_path(cmd.install_data, destination) - @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_user_site(self): # test install with --user # preparing the environment for the test @@ -173,19 +172,18 @@ class InstallTestCase(support.TempdirManager, cmd.home = 'home' self.assertRaises(PackagingOptionError, cmd.finalize_options) - if sys.version >= '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) install_dir = self.mkdtemp() project_dir, dist = self.create_dist(scripts=['hello']) os.chdir(project_dir) - self.write_file('hello', "print 'o hai'") + self.write_file('hello', "print('o hai')") cmd = install_dist(dist) dist.command_obj['install_dist'] = cmd @@ -194,11 +192,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 = ['hello', 'METADATA', 'INSTALLER', 'REQUESTED', 'RECORD'] @@ -207,8 +202,6 @@ class InstallTestCase(support.TempdirManager, # 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() @@ -229,11 +222,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 7bfd05f..9e77e47 100644 --- a/distutils2/tests/test_command_install_distinfo.py +++ b/distutils2/tests/test_command_install_distinfo.py @@ -2,7 +2,7 @@ import os import csv -import codecs +import hashlib from distutils2.command.install_distinfo import install_distinfo from distutils2.command.cmd import Command @@ -10,10 +10,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): @@ -59,18 +55,10 @@ 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()) @@ -91,11 +79,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', @@ -171,21 +156,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(): @@ -240,29 +219,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 3f241ea..8216de0 100644 --- a/distutils2/tests/test_command_install_lib.py +++ b/distutils2/tests/test_command_install_lib.py @@ -33,8 +33,7 @@ class InstallLibTestCase(support.TempdirManager, cmd.finalize_options() self.assertEqual(cmd.optimize, 2) - @unittest.skipIf(getattr(sys, 'dont_write_bytecode', False), - 'byte-compile disabled') + @unittest.skipIf(sys.dont_write_bytecode, 'byte-compile disabled') def test_byte_compile(self): pkg_dir, dist = self.create_dist() cmd = install_lib(dist) @@ -83,8 +82,6 @@ class InstallLibTestCase(support.TempdirManager, # get_input should return 2 elements self.assertEqual(len(cmd.get_inputs()), 2) - @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'), - 'sys.dont_write_bytecode not supported') def test_dont_write_bytecode(self): # makes sure byte_compile is not used pkg_dir, dist = self.create_dist() 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 85c3535..46ee2b1 100644 --- a/distutils2/tests/test_command_register.py +++ b/distutils2/tests/test_command_register.py @@ -1,8 +1,10 @@ -# encoding: utf-8 """Tests for distutils2.command.register.""" import os import getpass -import urllib2 +import urllib.request +import urllib.error +import urllib.parse + try: import docutils DOCUTILS_SUPPORT = True @@ -36,7 +38,7 @@ password:password """ -class Inputs(object): +class Inputs: """Fakes user inputs.""" def __init__(self, *answers): self.answers = answers @@ -49,7 +51,7 @@ class Inputs(object): self.index += 1 -class FakeOpener(object): +class FakeOpener: """Fakes a PyPI server""" def __init__(self): self.reqs = [] @@ -85,12 +87,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() @@ -121,7 +123,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() @@ -129,11 +131,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 @@ -153,7 +152,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): @@ -171,7 +170,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() @@ -182,13 +181,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() @@ -197,7 +196,7 @@ 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) @unittest.skipUnless(DOCUTILS_SUPPORT, 'needs docutils') def test_strict(self): @@ -211,7 +210,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 self.assertRaises(PackagingSetupError, cmd.run) # metadata is OK but long_description is broken @@ -232,7 +231,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() @@ -240,7 +239,7 @@ 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() diff --git a/distutils2/tests/test_command_sdist.py b/distutils2/tests/test_command_sdist.py index c056881..9bf1fcf 100644 --- a/distutils2/tests/test_command_sdist.py +++ b/distutils2/tests/test_command_sdist.py @@ -214,11 +214,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 @@ -334,12 +331,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 @@ -352,12 +346,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) @@ -370,12 +361,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') @@ -388,12 +376,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']) @@ -404,11 +389,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) diff --git a/distutils2/tests/test_command_test.py b/distutils2/tests/test_command_test.py index 2b832cb..9fb6fb9 100644 --- a/distutils2/tests/test_command_test.py +++ b/distutils2/tests/test_command_test.py @@ -113,7 +113,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 76281ca..5c58879 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,6 +43,7 @@ repository:http://another.pypi/ """ +@unittest.skipIf(threading is None, 'needs threading') class UploadTestCase(support.TempdirManager, support.EnvironRestorer, support.LoggingCatcher, PyPIServerTestCase): @@ -112,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) @@ -148,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 d6edc37..cf69af9 100644 --- a/distutils2/tests/test_command_upload_docs.py +++ b/distutils2/tests/test_command_upload_docs.py @@ -32,6 +32,7 @@ password = long_island """ +@unittest.skipIf(threading is None, "Needs threading") class UploadDocsTestCase(support.TempdirManager, support.EnvironRestorer, support.LoggingCatcher, @@ -94,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() @@ -174,9 +175,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 295f1ae..7c913ee 100644 --- a/distutils2/tests/test_config.py +++ b/distutils2/tests/test_config.py @@ -1,9 +1,8 @@ -# encoding: utf-8 """Tests for distutils2.config.""" import os import sys import logging -from StringIO import StringIO +from io import StringIO from distutils2 import command from distutils2.dist import Distribution @@ -15,7 +14,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 @@ -161,7 +160,7 @@ def logging_hook(config): """ -class DCompiler(object): +class DCompiler: name = 'd' description = 'D Compiler' @@ -181,7 +180,7 @@ def third_hook(config): config['files']['modules'] += '\n third' -class FooBarBazTest(object): +class FooBarBazTest: def __init__(self, dist): self.distribution = dist @@ -474,11 +473,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 a268c4f..7a0aa0d 100644 --- a/distutils2/tests/test_create.py +++ b/distutils2/tests/test_create.py @@ -1,9 +1,7 @@ -# encoding: utf-8 """Tests for distutils2.create.""" import os import sys -import codecs -from StringIO import StringIO +from io import StringIO from textwrap import dedent from distutils2.create import MainProgram, ask_yn, ask, main from distutils2._backport import sysconfig @@ -98,7 +96,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 @@ -133,18 +131,15 @@ class CreateTestCase(support.TempdirManager, scripts=['my_script', 'bin/run'], ) """), encoding='utf-8') - sys.stdin.write(u'y\n') + sys.stdin.write('y\n') sys.stdin.seek(0) 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 @@ -184,14 +179,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', @@ -221,13 +213,10 @@ ho, baby! 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 e524306..02c72da 100644 --- a/distutils2/tests/test_database.py +++ b/distutils2/tests/test_database.py @@ -1,12 +1,10 @@ import os +import io import csv import sys import shutil 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 @@ -28,11 +26,8 @@ from distutils2.database import ( 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() @@ -43,7 +38,7 @@ def record_pieces(path): return path, digest, size -class FakeDistsMixin(object): +class FakeDistsMixin: def setUp(self): super(FakeDistsMixin, self).setUp() @@ -65,11 +60,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): @@ -138,10 +133,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', '') @@ -152,12 +146,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 == []: @@ -165,8 +156,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): @@ -210,14 +199,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( @@ -640,8 +626,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 @@ -649,25 +634,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) @@ -682,11 +660,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 0c1f036..22fd37b 100644 --- a/distutils2/tests/test_dist.py +++ b/distutils2/tests/test_dist.py @@ -1,7 +1,6 @@ """Tests for distutils2.dist.""" import os import sys -import codecs import logging import textwrap @@ -52,12 +51,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") @@ -128,11 +124,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() @@ -148,11 +141,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 d00116c..571133c 100644 --- a/distutils2/tests/test_install.py +++ b/distutils2/tests/test_install.py @@ -18,7 +18,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): @@ -33,7 +33,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): @@ -63,7 +63,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 d7c4d6f..24f0510 100644 --- a/distutils2/tests/test_manifest.py +++ b/distutils2/tests/test_manifest.py @@ -1,7 +1,7 @@ """Tests for distutils2.manifest.""" import os import logging -from StringIO import StringIO +from io import StringIO from distutils2.manifest import Manifest from distutils2.tests import unittest, support @@ -37,11 +37,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) - finally: - f.close() manifest = Manifest() manifest.read_template(MANIFEST) @@ -54,11 +51,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 67e9e9b..0e8b74e 100644 --- a/distutils2/tests/test_markers.py +++ b/distutils2/tests/test_markers.py @@ -2,7 +2,6 @@ import os import sys import platform -from distutils2.compat import python_implementation from distutils2.markers import interpret from distutils2.tests import unittest @@ -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 aceedc2..82f5212 100644 --- a/distutils2/tests/test_metadata.py +++ b/distutils2/tests/test_metadata.py @@ -1,11 +1,9 @@ -# encoding: utf-8 """Tests for distutils2.metadata.""" import os import sys -import codecs import logging from textwrap import dedent -from StringIO import StringIO +from io import StringIO from distutils2.errors import (MetadataConflictError, MetadataMissingError, MetadataUnrecognizedVersionError) @@ -37,12 +35,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() @@ -70,11 +64,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)) @@ -92,11 +83,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()) @@ -111,6 +99,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): @@ -143,21 +133,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': [''] @@ -165,19 +152,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') @@ -324,21 +308,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 1fe3574..4d1584b 100644 --- a/distutils2/tests/test_mixin2to3.py +++ b/distutils2/tests/test_mixin2to3.py @@ -9,30 +9,22 @@ class Mixin2to3TestCase(support.TempdirManager, support.LoggingCatcher, unittest.TestCase): - @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_convert_code_only(self): # used to check if code gets converted properly. code = "print 'test'" - fp = self.mktempfile() - try: + with self.mktempfile() as fp: fp.write(code) - finally: - fp.close() mixin2to3 = Mixin2to3() mixin2to3._run_2to3([fp.name]) expected = "print('test')" - fp = open(fp.name) - try: + with open(fp.name) as fp: converted = fp.read() - finally: - fp.close() self.assertEqual(expected, converted) - @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_doctests_only(self): # used to check if doctests gets converted properly. doctest = textwrap.dedent('''\ @@ -44,11 +36,8 @@ class Mixin2to3TestCase(support.TempdirManager, It works. """''') - fp = self.mktempfile() - try: + with self.mktempfile() as fp: fp.write(doctest) - finally: - fp.close() mixin2to3 = Mixin2to3() mixin2to3._run_2to3([fp.name]) @@ -61,24 +50,17 @@ class Mixin2to3TestCase(support.TempdirManager, It works. """\n''') - fp = open(fp.name) - try: + with open(fp.name) as fp: converted = fp.read() - finally: - fp.close() self.assertEqual(expected, converted) - @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_additional_fixers(self): # used to check if use_2to3_fixers works code = 'type(x) is not T' - fp = self.mktempfile() - try: + with self.mktempfile() as fp: fp.write(code) - finally: - fp.close() mixin2to3 = Mixin2to3() mixin2to3._run_2to3(files=[fp.name], doctests=[fp.name], @@ -86,11 +68,8 @@ class Mixin2to3TestCase(support.TempdirManager, expected = 'not isinstance(x, T)' - fp = open(fp.name) - try: + with open(fp.name) as fp: converted = fp.read() - finally: - fp.close() self.assertEqual(expected, converted) diff --git a/distutils2/tests/test_msvc9compiler.py b/distutils2/tests/test_msvc9compiler.py index 22e5cea..16382e7 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 a2d8787..93d6fac 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,35 +59,34 @@ 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: + except Exception as v: self.assertIn('nonnumeric port', str(v)) # issue #160 @@ -274,22 +275,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 21b76f1..8645f63 100644 --- a/distutils2/tests/test_run.py +++ b/distutils2/tests/test_run.py @@ -2,7 +2,7 @@ import os import sys -from StringIO import StringIO +from io import StringIO from distutils2 import install from distutils2.tests import unittest, support @@ -71,12 +71,11 @@ class RunTestCase(support.TempdirManager, else: pythonpath = d2parent - status, out, err = assert_python_ok( - '-c', 'from distutils2.run import main; main()', '--help', - PYTHONPATH=pythonpath) + status, out, err = assert_python_ok('-m', 'distutils2.run', '--help', + PYTHONPATH=pythonpath) self.assertEqual(status, 0) - self.assertGreater(out, '') - self.assertEqual(err, '') + self.assertGreater(out, b'') + self.assertEqual(err, b'') def test_suite(): diff --git a/distutils2/tests/test_uninstall.py b/distutils2/tests/test_uninstall.py index 39dc786..d38d447 100644 --- a/distutils2/tests/test_uninstall.py +++ b/distutils2/tests/test_uninstall.py @@ -1,7 +1,7 @@ """Tests for the uninstall command.""" import os import sys -from StringIO import StringIO +from io import StringIO import stat import distutils2.util diff --git a/distutils2/tests/test_util.py b/distutils2/tests/test_util.py index f369ce7..74e7ddc 100644 --- a/distutils2/tests/test_util.py +++ b/distutils2/tests/test_util.py @@ -5,7 +5,7 @@ import time import logging import tempfile import subprocess -from StringIO import StringIO +from io import StringIO from distutils2.tests import support, unittest from distutils2.tests.test_config import SETUP_CFG @@ -55,24 +55,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, @@ -82,7 +82,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 @@ -319,8 +319,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_dont_write_bytecode(self): # makes sure byte_compile raise a PackagingError # if sys.dont_write_bytecode is True @@ -377,7 +375,7 @@ class UtilTestCase(support.EnvironRestorer, 'pkg1.pkg3.pkg6'])) def test_resolve_name(self): - self.assertIs(str, resolve_name('__builtin__.str')) + self.assertIs(str, resolve_name('builtins.str')) self.assertEqual( UtilTestCase.__name__, resolve_name("distutils2.tests.test_util.UtilTestCase").__name__) @@ -407,7 +405,6 @@ class UtilTestCase(support.EnvironRestorer, finally: sys.path.remove(tmp_dir) - @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_run_2to3_on_code(self): content = "print 'test'" converted_content = "print('test')" @@ -421,7 +418,6 @@ class UtilTestCase(support.EnvironRestorer, file_handle.close() self.assertEqual(new_content, converted_content) - @unittest.skipIf(sys.version < '2.6', 'requires Python 2.6 or higher') def test_run_2to3_on_doctests(self): # to check if text files containing doctests only get converted. content = ">>> print 'test'\ntest\n" @@ -448,24 +444,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): @@ -497,11 +493,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): @@ -538,10 +531,10 @@ class UtilTestCase(support.EnvironRestorer, 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, @@ -787,21 +780,16 @@ class EggInfoToDistInfoTestCase(support.TempdirManager, dir_paths.append(path) for f in files: path = os.path.join(tempdir, f) - _f = open(path, 'w') - try: + with open(path, 'w') as _f: _f.write(f) - 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) 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; } |
