diff options
32 files changed, 161 insertions, 152 deletions
@@ -62,3 +62,5 @@ ddca71ae5ceb9b14512dc60ea83802c10e224cf0 0.6.45  7f2c08e9ca22023d1499c512fccc1513813b7dc4 0.7  024dd30ed702135f5328975042566e48cc479d7d 0.7.1  d04c05f035e3a5636006fc34f4be7e6c77035d17 0.7.2 +d212e48e0cef689acba57ed017289c027660b23c 0.7.3 +74c6c12268059986f9cc0b535399594f1d131201 0.8b1 diff --git a/CHANGES.txt b/CHANGES.txt index 59e37ad6..00bef01b 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -2,12 +2,17 @@  CHANGES  ======= +--- +0.8 +--- + +* Code base now runs on Python 2.4 - Python 3.3 without Python 2to3 +  conversion. +  -----  0.7.3  ----- -* Rename DISTRIBUTE_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT environment -  variable to SETUPTOOLS_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT.  * Issue #1: Disable installation of Windows-specific files on non-Windows systems.  * Use new sysconfig module with Python 2.7 or >=3.2. @@ -12,7 +12,7 @@ Installation Instructions  Upgrading from Distribute  ========================= -Currently, Distribute disallows installing Setuptools 0.7.3 over Distribute. +Currently, Distribute disallows installing Setuptools 0.7+ over Distribute.  You must first uninstall any active version of Distribute first (see  `Uninstalling`_). @@ -29,7 +29,7 @@ The recommended way to install setuptools on Windows is to download  `ez_setup.py`_ and run it. The script will download the appropriate .egg  file and install it for you. -.. _ez_setup.py: https://bitbucket.org/pypa/setuptools/raw/0.7.3/ez_setup.py +.. _ez_setup.py: https://bitbucket.org/pypa/setuptools/raw/0.8/ez_setup.py  For best results, uninstall previous versions FIRST (see `Uninstalling`_). @@ -45,7 +45,7 @@ Unix-based Systems including Mac OS X  Download `ez_setup.py`_ and run it using the target Python version. The script  will download the appropriate version and install it for you:: -    > wget https://bitbucket.org/pypa/setuptools/raw/0.7.3/ez_setup.py -O - | python +    > wget https://bitbucket.org/pypa/setuptools/raw/0.8/ez_setup.py -O - | python  Note that you will may need to invoke the command with superuser privileges to  install to the system Python. @@ -53,7 +53,7 @@ install to the system Python.  Alternatively, on Python 2.6 and later, Setuptools may be installed to a  user-local path:: -    > wget https://bitbucket.org/pypa/setuptools/raw/0.7.3/ez_setup.py +    > wget https://bitbucket.org/pypa/setuptools/raw/0.8/ez_setup.py      > python ez_setup.py --user @@ -66,7 +66,7 @@ tarball from `Setuptools on PyPI <https://pypi.python.org/pypi/setuptools>`_  and run setup.py with any supported distutils and Setuptools options.  For example:: -    setuptools-0.7.3$ python setup.py --prefix=/opt/setuptools +    setuptools-0.8$ python setup.py --prefix=/opt/setuptools  Use ``--help`` to get a full options list, but we recommend consulting  the `EasyInstall manual`_ for detailed instructions, especially `the section diff --git a/docs/conf.py b/docs/conf.py index 44d8378a..3fccd87f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -48,9 +48,9 @@ copyright = '2009-2013, The fellowship of the packaging'  # built documents.  #  # The short X.Y version. -version = '0.7.3' +version = '0.8'  # The full version, including alpha/beta/rc tags. -release = '0.7.3' +release = '0.8'  # The language for content autogenerated by Sphinx. Refer to documentation  # for a list of supported languages. diff --git a/ez_setup.py b/ez_setup.py index ba0d781e..c225c6ae 100644 --- a/ez_setup.py +++ b/ez_setup.py @@ -28,7 +28,7 @@ try:  except ImportError:      USER_SITE = None -DEFAULT_VERSION = "0.7.3" +DEFAULT_VERSION = "0.8"  DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"  def _python_cmd(*args): diff --git a/pkg_resources.py b/pkg_resources.py index 521a7e00..e03667e0 100644 --- a/pkg_resources.py +++ b/pkg_resources.py @@ -13,7 +13,7 @@ The package resource API is designed to work with normal filesystem packages,  method.  """ -import sys, os, zipfile, zipimport, time, re, imp, types +import sys, os, time, re, imp, types, zipfile, zipimport  try:      from urlparse import urlparse, urlunparse  except ImportError: @@ -11,32 +11,32 @@ import subprocess  import shutil  import os  import sys -import urllib2  import getpass  import collections  import itertools  import re  try: -    from urllib2 import urlopen, Request, HTTPError -    from itertools import izip_longest +	import urllib.request as urllib_request  except ImportError: -    from urllib.request import urlopen, Request -    from urllib.error import HTTPError -    raw_input = input -    from itertools import zip_longest as izip_longest +	import urllib2 as urllib_request + +try: +	input = raw_input +except NameError: +	pass  try:  	import keyring  except Exception:  	pass -VERSION = '0.7.3' +VERSION = '0.8'  PACKAGE_INDEX = 'https://pypi.python.org/pypi'  def set_versions():  	global VERSION -	version = raw_input("Release as version [%s]> " % VERSION) or VERSION +	version = input("Release as version [%s]> " % VERSION) or VERSION  	if version != VERSION:  		VERSION = bump_versions(version) @@ -108,11 +108,11 @@ def add_milestone_and_version(version):  	for type in 'milestones', 'versions':  		url = (base + '/1.0/repositories/{repo}/issues/{type}'  			.format(repo = get_repo_name(), type=type)) -		req = Request(url = url, headers = headers, +		req = urllib_request.Request(url = url, headers = headers,  			data='name='+version)  		try: -			urlopen(req) -		except HTTPError as e: +			urllib_request.urlopen(req) +		except urllib_request.HTTPError as e:  			print(e.fp.read())  def bump_versions(target_ver): @@ -125,7 +125,10 @@ def bump_versions(target_ver):  def bump_version(filename, target_ver):  	with open(filename, 'rb') as f: -		lines = [line.replace(VERSION, target_ver) for line in f] +		lines = [ +			line.replace(VERSION.encode('ascii'), target_ver.encode('ascii')) +			for line in f +		]  	with open(filename, 'wb') as f:  		f.writelines(lines) @@ -234,7 +237,7 @@ def _linkified_text(rst_content):  	anchors = []  	linkified_parts = [_linkified_part(part, anchors)  		for part in plain_text_parts] -	pairs = izip_longest( +	pairs = itertools.izip_longest(  		linkified_parts,  		HREF_pattern.findall(rst_content),  		fillvalue='', @@ -47,7 +47,7 @@ exec(init_file.read(), d)  init_file.close()  SETUP_COMMANDS = d['__all__'] -VERSION = "0.7.3" +VERSION = "0.8"  from setuptools import setup, find_packages  from setuptools.command.build_py import build_py as _build_py @@ -56,7 +56,7 @@ from setuptools.command.test import test as _test  scripts = []  console_scripts = ["easy_install = setuptools.command.easy_install:main"] -if os.environ.get("SETUPTOOLS_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT") is None: +if os.environ.get("DISTRIBUTE_DISABLE_VERSIONED_EASY_INSTALL_SCRIPT") is None:      console_scripts.append("easy_install-%s = setuptools.command.easy_install:main" % sys.version[:3])  # specific command that is used to generate windows .exe files diff --git a/setuptools.egg-info/requires.txt b/setuptools.egg-info/requires.txt index 5ff415da..77cddef2 100644 --- a/setuptools.egg-info/requires.txt +++ b/setuptools.egg-info/requires.txt @@ -1,5 +1,8 @@ +[ssl:sys_platform=='win32' and python_version=='2.4'] +ctypes==1.0.2 +  [ssl:sys_platform=='win32']  wincertstore==0.1 diff --git a/setuptools/__init__.py b/setuptools/__init__.py index 0f29f575..a8e7617a 100644 --- a/setuptools/__init__.py +++ b/setuptools/__init__.py @@ -8,7 +8,7 @@ from distutils.util import convert_path  import os  import sys -__version__ = '0.7.3' +__version__ = '0.8'  __all__ = [      'setup', 'Distribution', 'Feature', 'Command', 'Extension', 'Require',      'find_packages' diff --git a/setuptools/command/alias.py b/setuptools/command/alias.py index 4c08c48d..52384e1a 100755 --- a/setuptools/command/alias.py +++ b/setuptools/command/alias.py @@ -9,7 +9,7 @@ def shquote(arg):      """Quote an argument for later parsing by shlex.split()"""      for c in '"', "'", "\\", "#":          if c in arg: return repr(arg) -    if arg.split()!=[arg]: +    if arg.split() != [arg]:          return repr(arg)      return arg         @@ -33,7 +33,7 @@ class alias(option_base):      def finalize_options(self):          option_base.finalize_options(self) -        if self.remove and len(self.args)!=1: +        if self.remove and len(self.args) != 1:              raise DistutilsOptionError(                  "Must specify exactly one argument (the alias name) when "                  "using --remove" diff --git a/setuptools/command/bdist_egg.py b/setuptools/command/bdist_egg.py index de72ea04..c5776158 100644 --- a/setuptools/command/bdist_egg.py +++ b/setuptools/command/bdist_egg.py @@ -412,7 +412,7 @@ def write_safety_flag(egg_dir, safe):      for flag,fn in safety_flags.items():          fn = os.path.join(egg_dir, fn)          if os.path.exists(fn): -            if safe is None or bool(safe)!=flag: +            if safe is None or bool(safe) != flag:                  os.unlink(fn)          elif safe is not None and bool(safe)==flag:              f=open(fn,'wt'); f.write('\n'); f.close() diff --git a/setuptools/command/easy_install.py b/setuptools/command/easy_install.py index c53ca9f2..000fefa0 100755 --- a/setuptools/command/easy_install.py +++ b/setuptools/command/easy_install.py @@ -447,7 +447,7 @@ class easy_install(Command):              self.pth_file = None          PYTHONPATH = os.environ.get('PYTHONPATH','').split(os.pathsep) -        if instdir not in map(normalize_path, filter(None,PYTHONPATH)): +        if instdir not in map(normalize_path, [_f for _f in PYTHONPATH if _f]):              # only PYTHONPATH dirs need a site.py, so pretend it's there              self.sitepy_installed = True          elif self.multi_version and not os.path.exists(pth_file): @@ -802,7 +802,7 @@ Please make the appropriate changes for your system and try again.              f = open(target,"w"+mode)              f.write(contents)              f.close() -            chmod(target,0x1FF - mask) # 0777 +            chmod(target, 0x1FF-mask) # 0777 @@ -916,7 +916,7 @@ Please make the appropriate changes for your system and try again.              f = open(pkg_inf,'w')              f.write('Metadata-Version: 1.0\n')              for k,v in cfg.items('metadata'): -                if k!='target_version': +                if k != 'target_version':                      f.write('%s: %s\n' % (k.replace('_','-').title(), v))              f.close()          script_dir = os.path.join(egg_info,'scripts') @@ -1156,7 +1156,7 @@ See the setuptools documentation for the "develop" command for more info.              'site_dirs', 'allow_hosts',          )          fetch_options = {} -        for key, val in iteritems(ei_opts): +        for key, val in ei_opts.items():              if key not in fetch_directives: continue              fetch_options[key.replace('_', '-')] = val[1]          # create a settings dictionary suitable for `edit_config` @@ -1390,7 +1390,8 @@ Please make the appropriate changes for your system and try again.""" % (  def get_site_dirs():      # return a list of 'site' dirs -    sitedirs = list(filter(None,os.environ.get('PYTHONPATH','').split(os.pathsep))) +    sitedirs = [_f for _f in os.environ.get('PYTHONPATH', +                                            '').split(os.pathsep) if _f]      prefixes = [sys.prefix]      if sys.exec_prefix != sys.prefix:          prefixes.append(sys.exec_prefix) @@ -1509,7 +1510,7 @@ def extract_wininst_cfg(dist_filename):              #  unicode for the RawConfigParser, so decode it. Is this the              #  right encoding?              config = config.decode('ascii') -            cfg.readfp(StringIO.StringIO(config)) +            cfg.readfp(StringIO(config))          except ConfigParser.Error:              return None          if not cfg.has_section('metadata') or not cfg.has_section('Setup'): @@ -1544,7 +1545,7 @@ def get_exe_prefixes(exe_filename):                  if parts[1].endswith('.egg-info'):                      prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/'))                      break -            if len(parts)!=2 or not name.endswith('.pth'): +            if len(parts) != 2 or not name.endswith('.pth'):                  continue              if name.endswith('-nspkg.pth'):                  continue @@ -1577,7 +1578,8 @@ class PthDistributions(Environment):      dirty = False      def __init__(self, filename, sitedirs=()): -        self.filename = filename; self.sitedirs = list(map(normalize_path, sitedirs)) +        self.filename = filename +        self.sitedirs = list(map(normalize_path, sitedirs))          self.basedir = normalize_path(os.path.dirname(self.filename))          self._load(); Environment.__init__(self, [], None, None)          for path in yield_lines(self.paths): diff --git a/setuptools/command/egg_info.py b/setuptools/command/egg_info.py index 1a61dfcb..6b0d2426 100755 --- a/setuptools/command/egg_info.py +++ b/setuptools/command/egg_info.py @@ -8,7 +8,7 @@ from setuptools import Command  from distutils.errors import *  from distutils import log  from setuptools.command.sdist import sdist -from setuptools.compat import basestring, PY3 +from setuptools.compat import basestring  from distutils.util import convert_path  from distutils.filelist import FileList as _FileList  from pkg_resources import parse_requirements, safe_name, parse_version, \ @@ -416,7 +416,8 @@ def write_pkg_info(cmd, basename, filename):              metadata.name, metadata.version = oldname, oldver          safe = getattr(cmd.distribution,'zip_safe',None) -        from setuptools.command import bdist_egg; bdist_egg.write_safety_flag(cmd.egg_info, safe) +        from setuptools.command import bdist_egg +        bdist_egg.write_safety_flag(cmd.egg_info, safe)  def warn_depends_obsolete(cmd, basename, filename):      if os.path.exists(filename): diff --git a/setuptools/command/install_scripts.py b/setuptools/command/install_scripts.py index ad522f6c..105dabca 100755 --- a/setuptools/command/install_scripts.py +++ b/setuptools/command/install_scripts.py @@ -50,5 +50,5 @@ class install_scripts(_install_scripts):              f = open(target,"w"+mode)              f.write(contents)              f.close() -            chmod(target,0x1FF - mask)  # 0777 +            chmod(target, 0x1FF-mask)  # 0777 diff --git a/setuptools/command/saveopts.py b/setuptools/command/saveopts.py index 1180a440..7209be4c 100755 --- a/setuptools/command/saveopts.py +++ b/setuptools/command/saveopts.py @@ -9,10 +9,9 @@ class saveopts(option_base):      def run(self):          dist = self.distribution -        commands = dist.command_options.keys()          settings = {} -        for cmd in commands: +        for cmd in dist.command_options:              if cmd=='saveopts':                  continue    # don't save our own options! diff --git a/setuptools/command/upload_docs.py b/setuptools/command/upload_docs.py index e07b885d..12bc916b 100644 --- a/setuptools/command/upload_docs.py +++ b/setuptools/command/upload_docs.py @@ -25,7 +25,9 @@ except ImportError:  from setuptools.compat import httplib, urlparse, unicode, iteritems -if sys.version_info >= (3,): +_IS_PYTHON3 = sys.version > '3' + +if _IS_PYTHON3:      errors = 'surrogateescape'  else:      errors = 'strict' diff --git a/setuptools/compat.py b/setuptools/compat.py index 49438502..437fb710 100644 --- a/setuptools/compat.py +++ b/setuptools/compat.py @@ -1,4 +1,5 @@  import sys +import itertools  if sys.version_info[0] < 3:      PY3 = False @@ -14,8 +15,9 @@ if sys.version_info[0] < 3:      im_func = lambda o: o.im_func      from htmlentitydefs import name2codepoint      import httplib -    from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler +    from BaseHTTPServer import HTTPServer      from SimpleHTTPServer import SimpleHTTPRequestHandler +    from BaseHTTPServer import BaseHTTPRequestHandler      iteritems = lambda o: o.iteritems()      long_type = long      maxsize = sys.maxint @@ -29,7 +31,7 @@ if sys.version_info[0] < 3:      from urllib2 import urlopen, HTTPError, URLError, unquote, splituser      from urlparse import urlparse, urlunparse, urljoin      xrange = xrange -    from itertools import ifilterfalse +    filterfalse = itertools.ifilterfalse      def exec_(code, globs=None, locs=None):          if globs is None: @@ -57,7 +59,8 @@ else:      im_func = lambda o: o.__func__      from html.entities import name2codepoint      import http.client as httplib -    from http.server import HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler +    from http.server import HTTPServer, SimpleHTTPRequestHandler +    from http.server import BaseHTTPRequestHandler      iteritems = lambda o: o.items()      long_type = int      maxsize = sys.maxsize @@ -71,7 +74,7 @@ else:      from urllib.request import urlopen, url2pathname      from urllib.parse import urlparse, urlunparse, quote, unquote, splituser, urljoin      xrange = range -    from itertools import filterfalse as ifilterfalse +    filterfalse = itertools.filterfalse      def execfile(fn, globs=None, locs=None):          if globs is None: diff --git a/setuptools/depends.py b/setuptools/depends.py index f1ef2736..8b9d1217 100644 --- a/setuptools/depends.py +++ b/setuptools/depends.py @@ -36,7 +36,7 @@ class Require:      def version_ok(self,version):          """Is 'version' sufficiently up-to-date?"""          return self.attribute is None or self.format is None or \ -            str(version)!="unknown" and version >= self.requested_version +            str(version) != "unknown" and version >= self.requested_version      def get_version(self, paths=None, default="unknown"): diff --git a/setuptools/package_index.py b/setuptools/package_index.py index 25936b91..61a66c6d 100755 --- a/setuptools/package_index.py +++ b/setuptools/package_index.py @@ -1,14 +1,16 @@  """PyPI and direct package downloading"""  import sys, os.path, re, shutil, random, socket +import itertools +import base64 +from setuptools import ssl_support  from pkg_resources import *  from distutils import log  from distutils.errors import DistutilsError - -from setuptools import ssl_support  from setuptools.compat import (urllib2, httplib, StringIO, HTTPError,                                 urlparse, urlunparse, unquote, splituser, -                               url2pathname, name2codepoint, ifilterfalse, +                               url2pathname, name2codepoint,                                 unichr, urljoin) +from setuptools.compat import filterfalse  try:      from hashlib import md5  except ImportError: @@ -60,9 +62,9 @@ def parse_bdist_wininst(name):  def egg_info_for_url(url):      scheme, server, path, parameters, query, fragment = urlparse(url) -    base = urllib2.unquote(path.split('/')[-1]) +    base = unquote(path.split('/')[-1])      if server=='sourceforge.net' and base=='download':    # XXX Yuck -        base = urllib2.unquote(path.split('/')[-2]) +        base = unquote(path.split('/')[-2])      if '#' in base: base, fragment = base.split('#',1)      return base,fragment @@ -148,7 +150,7 @@ def unique_everseen(iterable, key=None):      seen = set()      seen_add = seen.add      if key is None: -        for element in ifilterfalse(seen.__contains__, iterable): +        for element in filterfalse(seen.__contains__, iterable):              seen_add(element)              yield element      else: @@ -292,7 +294,8 @@ class PackageIndex(Environment):                          self.scan_egg_link(item, entry)      def scan_egg_link(self, path, entry): -        lines = list(filter(None, map(str.strip, open(os.path.join(path, entry))))) +        lines = [_f for _f in map(str.strip, +                                  open(os.path.join(path, entry))) if _f]          if len(lines)==2:              for dist in find_distributions(os.path.join(path, lines[0])):                  dist.location = os.path.join(path, *lines) @@ -387,7 +390,7 @@ class PackageIndex(Environment):      def check_md5(self, cs, info, filename, tfp):          if re.match('md5=[0-9a-f]{32}$', info):              self.debug("Validating md5 checksum for %s", filename) -            if cs.hexdigest()!=info[4:]: +            if cs.hexdigest() != info[4:]:                  tfp.close()                  os.unlink(filename)                  raise DistutilsError( @@ -889,7 +892,7 @@ def _encode_auth(auth):      >>> _encode_auth('username%3Apassword')      u'dXNlcm5hbWU6cGFzc3dvcmQ='      """ -    auth_s = urllib2.unquote(auth) +    auth_s = unquote(auth)      # convert to bytes      auth_bytes = auth_s.encode()      # use the legacy interface for Python 2.3 support diff --git a/setuptools/sandbox.py b/setuptools/sandbox.py index a5a01a46..91dfc519 100755 --- a/setuptools/sandbox.py +++ b/setuptools/sandbox.py @@ -12,6 +12,8 @@ from distutils.errors import DistutilsError  from setuptools.compat import builtins, execfile, reduce  from pkg_resources import working_set +from setuptools.compat import builtins, execfile, reduce +  __all__ = [      "AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup",  ] diff --git a/setuptools/ssl_support.py b/setuptools/ssl_support.py index af718a4b..e749b312 100644 --- a/setuptools/ssl_support.py +++ b/setuptools/ssl_support.py @@ -1,6 +1,7 @@  import sys, os, socket, atexit, re  import pkg_resources  from pkg_resources import ResolutionError, ExtractionError +from setuptools.compat import urllib2  try:      import urllib2 diff --git a/setuptools/tests/__init__.py b/setuptools/tests/__init__.py index 1cd5df2b..b5328ce6 100644 --- a/setuptools/tests/__init__.py +++ b/setuptools/tests/__init__.py @@ -9,6 +9,7 @@ from distutils.errors import DistutilsOptionError, DistutilsPlatformError  from distutils.errors import DistutilsSetupError  from distutils.core import Extension  from distutils.version import LooseVersion +from setuptools.compat import func_code  from setuptools.compat import func_code  import setuptools.dist diff --git a/setuptools/tests/server.py b/setuptools/tests/server.py index 5f5ed6bb..ae2381e3 100644 --- a/setuptools/tests/server.py +++ b/setuptools/tests/server.py @@ -2,10 +2,10 @@  """  import sys  import time -from threading import Thread +import threading +from setuptools.compat import BaseHTTPRequestHandler  from setuptools.compat import (urllib2, URLError, HTTPServer, -                               SimpleHTTPRequestHandler, -                               BaseHTTPRequestHandler) +                               SimpleHTTPRequestHandler)  class IndexServer(HTTPServer):      """Basic single-threaded http server simulating a package index @@ -28,7 +28,7 @@ class IndexServer(HTTPServer):              self.handle_request()      def start(self): -        self.thread = Thread(target=self.serve) +        self.thread = threading.Thread(target=self.serve)          self.thread.start()      def stop(self): @@ -47,7 +47,7 @@ class IndexServer(HTTPServer):                  urllib2.urlopen(url, timeout=5)              else:                  urllib2.urlopen(url) -        except urllib2.URLError: +        except URLError:              # ignore any errors; all that's important is the request              pass          self.thread.join() @@ -63,14 +63,14 @@ class RequestRecorder(BaseHTTPRequestHandler):          requests.append(self)          self.send_response(200, 'OK') -class MockServer(HTTPServer, Thread): +class MockServer(HTTPServer, threading.Thread):      """      A simple HTTP Server that records the requests made to it.      """      def __init__(self, server_address=('', 0),              RequestHandlerClass=RequestRecorder):          HTTPServer.__init__(self, server_address, RequestHandlerClass) -        Thread.__init__(self) +        threading.Thread.__init__(self)          self.setDaemon(True)          self.requests = [] diff --git a/setuptools/tests/test_develop.py b/setuptools/tests/test_develop.py index e2939fea..7b90161a 100644 --- a/setuptools/tests/test_develop.py +++ b/setuptools/tests/test_develop.py @@ -90,11 +90,15 @@ class TestDevelopTest(unittest.TestCase):          # Check that we are using the right code.          egg_link_file = open(os.path.join(site.USER_SITE, 'foo.egg-link'), 'rt') -        path = egg_link_file.read().split()[0].strip() -        egg_link_file.close() +        try: +            path = egg_link_file.read().split()[0].strip() +        finally: +            egg_link_file.close()          init_file = open(os.path.join(path, 'foo', '__init__.py'), 'rt') -        init = init_file.read().strip() -        init_file.close() +        try: +            init = init_file.read().strip() +        finally: +            init_file.close()          if sys.version < "3":              self.assertEqual(init, 'print "foo"')          else: @@ -116,4 +120,3 @@ class TestDevelopTest(unittest.TestCase):                      pass          finally:              os.chdir(old_dir) - diff --git a/setuptools/tests/test_dist_info.py b/setuptools/tests/test_dist_info.py index fcb78c36..a8adb68c 100644 --- a/setuptools/tests/test_dist_info.py +++ b/setuptools/tests/test_dist_info.py @@ -51,30 +51,33 @@ class TestDistInfo(unittest.TestCase):                                   'VersionedDistribution-2.718.dist-info')          os.mkdir(versioned)          metadata_file = open(os.path.join(versioned, 'METADATA'), 'w+') -        metadata_file.write(DALS( -            """ -            Metadata-Version: 1.2 -            Name: VersionedDistribution -            Requires-Dist: splort (4) -            Provides-Extra: baz -            Requires-Dist: quux (>=1.1); extra == 'baz' -            """)) -        metadata_file.close() - +        try: +            metadata_file.write(DALS( +                """ +                Metadata-Version: 1.2 +                Name: VersionedDistribution +                Requires-Dist: splort (4) +                Provides-Extra: baz +                Requires-Dist: quux (>=1.1); extra == 'baz' +                """)) +        finally: +            metadata_file.close()          unversioned = os.path.join(self.tmpdir,                                     'UnversionedDistribution.dist-info')          os.mkdir(unversioned)          metadata_file = open(os.path.join(unversioned, 'METADATA'), 'w+') -        metadata_file.write(DALS( -            """ -            Metadata-Version: 1.2 -            Name: UnversionedDistribution -            Version: 0.3 -            Requires-Dist: splort (==4) -            Provides-Extra: baz -            Requires-Dist: quux (>=1.1); extra == 'baz' -            """)) -        metadata_file.close() +        try: +            metadata_file.write(DALS( +                """ +                Metadata-Version: 1.2 +                Name: UnversionedDistribution +                Version: 0.3 +                Requires-Dist: splort (==4) +                Provides-Extra: baz +                Requires-Dist: quux (>=1.1); extra == 'baz' +                """)) +        finally: +            metadata_file.close()      def tearDown(self):          shutil.rmtree(self.tmpdir) diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py index 66d43b62..b0609eb1 100644 --- a/setuptools/tests/test_easy_install.py +++ b/setuptools/tests/test_easy_install.py @@ -6,6 +6,8 @@ import shutil  import tempfile  import unittest  import site +from setuptools.compat import StringIO, BytesIO, next +from setuptools.compat import urlparse  import textwrap  import tarfile  import distutils.core diff --git a/setuptools/tests/test_packageindex.py b/setuptools/tests/test_packageindex.py index c2ff0539..92d1e2e0 100644 --- a/setuptools/tests/test_packageindex.py +++ b/setuptools/tests/test_packageindex.py @@ -69,7 +69,8 @@ class TestPackageIndex(unittest.TestCase):          try:              index.open_url(url)          except distutils.errors.DistutilsError: -            msg = unicode(sys.exc_info()[1]) +            error = sys.exc_info()[1] +            msg = unicode(error)              assert 'nonnumeric port' in msg or 'getaddrinfo failed' in msg or 'Name or service not known' in msg              return          raise RuntimeError("Did not raise") diff --git a/setuptools/tests/test_sdist.py b/setuptools/tests/test_sdist.py index c1e7864b..a58b749c 100644 --- a/setuptools/tests/test_sdist.py +++ b/setuptools/tests/test_sdist.py @@ -342,7 +342,7 @@ class TestSdistTest(unittest.TestCase):          if sys.version_info >= (3,):              fs_enc = sys.getfilesystemencoding() -            if sys.platform == 'win32':  +            if sys.platform == 'win32':                  if fs_enc == 'cp1252':                      # Python 3 mangles the UTF-8 filename                      filename = filename.decode('cp1252') @@ -377,14 +377,14 @@ class TestSdistTest(unittest.TestCase):          if sys.version_info >= (3,):              #not all windows systems have a default FS encoding of cp1252              if sys.platform == 'win32': -                # Latin-1 is similar to Windows-1252 however  +                # Latin-1 is similar to Windows-1252 however                  # on mbcs filesys it is not in latin-1 encoding                  fs_enc = sys.getfilesystemencoding()                  if fs_enc == 'mbcs':                      filename = filename.decode('mbcs')                  else:                      filename = filename.decode('latin-1') -                     +                  self.assertTrue(filename in cmd.filelist.files)              else:                  # The Latin-1 filename should have been skipped diff --git a/setuptools/tests/test_test.py b/setuptools/tests/test_test.py index d6e68590..7a06a403 100644 --- a/setuptools/tests/test_test.py +++ b/setuptools/tests/test_test.py @@ -1,4 +1,4 @@ -# -*- coding: UTF-8 -*-  +# -*- coding: UTF-8 -*-  """develop tests  """ @@ -23,7 +23,7 @@ setup(name='foo',  )  """ -NS_INIT = """# -*- coding: Latin-1 -*-  +NS_INIT = """# -*- coding: Latin-1 -*-  # Söme Arbiträry Ünicode to test Issüé 310  try:      __import__('pkg_resources').declare_namespace(__name__) @@ -77,7 +77,7 @@ class TestTestTest(unittest.TestCase):          f = open(init, 'wt')          f.write(TEST_PY)          f.close() -         +          os.chdir(self.dir)          self.old_base = site.USER_BASE          site.USER_BASE = tempfile.mkdtemp() @@ -87,7 +87,7 @@ class TestTestTest(unittest.TestCase):      def tearDown(self):          if sys.version < "2.6" or hasattr(sys, 'real_prefix'):              return -         +          os.chdir(self.old_cwd)          shutil.rmtree(self.dir)          shutil.rmtree(site.USER_BASE) @@ -98,7 +98,7 @@ class TestTestTest(unittest.TestCase):      def test_test(self):          if sys.version < "2.6" or hasattr(sys, 'real_prefix'):              return -         +          dist = Distribution(dict(              name='foo',              packages=['name', 'name.space', 'name.space.tests'], @@ -121,4 +121,4 @@ class TestTestTest(unittest.TestCase):                  pass          finally:              sys.stdout = old_stdout -            
\ No newline at end of file + diff --git a/setuptools/tests/win_script_wrapper.txt b/setuptools/tests/win_script_wrapper.txt index db1daf6b..731243dd 100644 --- a/setuptools/tests/win_script_wrapper.txt +++ b/setuptools/tests/win_script_wrapper.txt @@ -49,37 +49,16 @@ GUI programs, the suffix '-script-pyw' is added.)  This is why we  named out script the way we did.  Now we can run out script by running  the wrapper: -    >>> from subprocess import Popen, PIPE, STDOUT -    >>> try: -    ...     unicode=unicode -    ... except: -    ...     unicode=str -    >>> def popen4(cmd, *args): -    ...     if hasattr(os, 'popen4'): -    ...         input, output = os.popen4(cmd + " ".join(args)) -    ...         return input, output -    ...     else: -    ...         #emulate popen4 in python 3 -    ...         if cmd[0] == '"' and cmd[-1] != '"': -    ...             cmd = cmd[1:] -    ...         cmd += " ".join(args) -    ...         p = Popen(cmd, shell=True, bufsize=0, -    ...                               stdin=PIPE, stdout=PIPE, stderr=STDOUT) -    ...         return p.stdin, p.stdout -     -    >>> input, output = popen4('"' + nt_quote_arg(os.path.join(sample_directory, 'foo.exe')),  -    ...                        r' arg1', r'"arg 2"', r'"arg \"2\\\""', r'"arg 4\\"', r'"arg5 a\\b"') -    >>> bytes_written = input.write('hello\nworld\n'.encode('utf-8')) -    >>> input.close() -    >>> # This is needed for line ending differences between py2 and py3 on win32 -    >>> msg = unicode(output.read(), encoding='utf-8').split("\n") -    >>> for line in msg: -    ...     print(line.strip())  +    >>> import subprocess +    >>> cmd = [os.path.join(sample_directory, 'foo.exe'), 'arg1', 'arg 2', +    ...     'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] +    >>> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) +    >>> stdout, stderr = proc.communicate('hello\nworld\n'.encode('ascii')) +    >>> bytes = sys.stdout.write(stdout.decode('ascii').replace('\r\n', '\n'))      \foo-script.py      ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b']      'hello\nworld\n'      non-optimized -    <BLANKLINE>  This example was a little pathological in that it exercised windows  (MS C runtime) quoting rules: @@ -115,18 +94,14 @@ enter the interpreter after running the script, you could use -Oi:      ... sys.ps1 = '---'      ... """ % dict(python_exe=nt_quote_arg(sys.executable)))      >>> f.close() - -    >>> input, output = popen4(nt_quote_arg(os.path.join(sample_directory, 'foo.exe'))) -    >>> input.close() -    >>> # This is needed for line ending differences between py2 and py3 on win32 -    >>> msg = unicode(output.read(), encoding='utf-8').split("\n") -    >>> for line in msg: -    ...     print(line.strip())  +    >>> cmd = [os.path.join(sample_directory, 'foo.exe')] +    >>> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) +    >>> stdout, stderr = proc.communicate() +    >>> bytes = sys.stdout.write(stdout.decode('ascii').replace('\r\n', '\n'))      \foo-script.py      []      ''      --- -    <BLANKLINE>  Testing the GUI Version  ----------------------- @@ -157,18 +132,19 @@ We'll also copy gui.exe to the sample-directory with the name bar.exe:  Finally, we'll run the script and check the result: -    >>> input, output = popen4('"'+nt_quote_arg(os.path.join(sample_directory, 'bar.exe')), -    ...               r' "%s" "Test Argument"' % os.path.join(sample_directory, 'test_output.txt')) -    >>> input.close() -    >>> # This is needed for line ending differences between py2 and py3 on win32 -    >>> msg = unicode(output.read(), encoding='utf-8').split("\n") -    >>> for line in msg: -    ...     print(line.strip())  +    >>> cmd = [ +    ...     os.path.join(sample_directory, 'bar.exe'), +    ...     os.path.join(sample_directory, 'test_output.txt'), +    ...     'Test Argument', +    ... ] +    >>> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) +    >>> stdout, stderr = proc.communicate() +    >>> print(stdout.decode('ascii'))      <BLANKLINE> -    >>> f = open(os.path.join(sample_directory, 'test_output.txt'), 'rb') -    >>> print(unicode(f.read(), encoding='utf-8')) +    >>> f_out = open(os.path.join(sample_directory, 'test_output.txt'), 'rb') +    >>> print(f_out.read().decode('ascii'))      'Test Argument' -    >>> f.close() +    >>> f_out.close()  We're done with the sample_directory: diff --git a/tests/test_ez_setup.py b/tests/test_ez_setup.py index 6dd4c055..26881f52 100644 --- a/tests/test_ez_setup.py +++ b/tests/test_ez_setup.py @@ -16,7 +16,7 @@ import ez_setup  class TestSetup(unittest.TestCase):      def urlopen(self, url): -        return open(self.tarball) +        return open(self.tarball, 'rb')      def setUp(self):          self.old_sys_path = copy.copy(sys.path) @@ -27,10 +27,7 @@ class TestSetup(unittest.TestCase):                      "--dist-dir", "%s" % self.tmpdir)          tarball = os.listdir(self.tmpdir)[0]          self.tarball = os.path.join(self.tmpdir, tarball) -        try: -            import urllib2 -        except ImportError: -            import urllib.request as urllib2 +        from setuptools.compat import urllib2          urllib2.urlopen = self.urlopen      def tearDown(self): @@ -40,7 +37,7 @@ class TestSetup(unittest.TestCase):      def test_build_egg(self):          # making it an egg -        egg = _build_egg(self.tarball, self.tmpdir) +        egg = _build_egg('Egg to be built', self.tarball, self.tmpdir)          # now trying to import it          sys.path[0] = egg  | 
