summaryrefslogtreecommitdiff
path: root/src/distutils2
diff options
context:
space:
mode:
Diffstat (limited to 'src/distutils2')
-rw-r--r--src/distutils2/README4
-rw-r--r--src/distutils2/_backport/pkgutil.py296
-rw-r--r--src/distutils2/_backport/sysconfig.cfg2
-rw-r--r--src/distutils2/_backport/sysconfig.py4
-rw-r--r--src/distutils2/_backport/tests/__init__.py5
-rw-r--r--src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO1
-rw-r--r--src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/PKG-INFO18
-rw-r--r--src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/SOURCES.txt0
-rw-r--r--src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/dependency_links.txt1
-rw-r--r--src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/entry_points.txt3
-rw-r--r--src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/not-zip-safe1
-rw-r--r--src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/requires.txt6
-rw-r--r--src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/top_level.txt0
-rw-r--r--src/distutils2/_backport/tests/fake_dists/strawberry-0.6.eggbin0 -> 1402 bytes
-rw-r--r--src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA2
-rw-r--r--src/distutils2/_backport/tests/test_pkgutil.py233
-rw-r--r--src/distutils2/_backport/tests/test_sysconfig.py48
-rw-r--r--src/distutils2/command/bdist.py6
-rw-r--r--src/distutils2/command/bdist_dumb.py2
-rw-r--r--src/distutils2/command/bdist_msi.py4
-rw-r--r--src/distutils2/command/bdist_wininst.py4
-rw-r--r--src/distutils2/command/cmd.py (renamed from src/distutils2/cmd.py)6
-rw-r--r--src/distutils2/command/install_egg_info.py2
-rw-r--r--src/distutils2/config.py6
-rw-r--r--src/distutils2/core.py2
-rw-r--r--src/distutils2/depgraph.py132
-rw-r--r--src/distutils2/dist.py18
-rw-r--r--src/distutils2/metadata.py16
-rw-r--r--src/distutils2/tests/__init__.py41
-rw-r--r--src/distutils2/tests/support.py16
-rw-r--r--src/distutils2/tests/test_bdist.py16
-rw-r--r--src/distutils2/tests/test_bdist_dumb.py16
-rw-r--r--src/distutils2/tests/test_bdist_msi.py8
-rw-r--r--src/distutils2/tests/test_bdist_wininst.py6
-rw-r--r--src/distutils2/tests/test_build.py22
-rw-r--r--src/distutils2/tests/test_build_clib.py18
-rw-r--r--src/distutils2/tests/test_build_ext.py63
-rw-r--r--src/distutils2/tests/test_build_py.py10
-rw-r--r--src/distutils2/tests/test_build_scripts.py8
-rw-r--r--src/distutils2/tests/test_ccompiler.py12
-rw-r--r--src/distutils2/tests/test_check.py18
-rwxr-xr-xsrc/distutils2/tests/test_clean.py8
-rw-r--r--src/distutils2/tests/test_cmd.py14
-rw-r--r--src/distutils2/tests/test_config.py27
-rw-r--r--src/distutils2/tests/test_config_cmd.py20
-rw-r--r--src/distutils2/tests/test_converter.py12
-rw-r--r--src/distutils2/tests/test_core.py8
-rw-r--r--src/distutils2/tests/test_cygwinccompiler.py24
-rw-r--r--src/distutils2/tests/test_depgraph.py187
-rw-r--r--src/distutils2/tests/test_dist.py56
-rw-r--r--src/distutils2/tests/test_emxccompiler.py6
-rwxr-xr-xsrc/distutils2/tests/test_extension.py8
-rw-r--r--src/distutils2/tests/test_install.py28
-rw-r--r--src/distutils2/tests/test_install_data.py16
-rw-r--r--src/distutils2/tests/test_install_headers.py12
-rw-r--r--src/distutils2/tests/test_install_lib.py20
-rw-r--r--src/distutils2/tests/test_install_scripts.py8
-rw-r--r--src/distutils2/tests/test_manifest.py8
-rw-r--r--src/distutils2/tests/test_metadata.py95
-rw-r--r--src/distutils2/tests/test_msvc9compiler.py18
-rw-r--r--src/distutils2/tests/test_pypi_versions.py6
-rw-r--r--src/distutils2/tests/test_register.py22
-rw-r--r--src/distutils2/tests/test_sdist.py51
-rw-r--r--src/distutils2/tests/test_spawn.py12
-rw-r--r--src/distutils2/tests/test_unixccompiler.py8
-rw-r--r--src/distutils2/tests/test_upload.py24
-rw-r--r--src/distutils2/tests/test_util.py50
-rw-r--r--src/distutils2/tests/test_version.py40
-rw-r--r--src/distutils2/util.py3
-rw-r--r--src/distutils2/version.py37
70 files changed, 1204 insertions, 700 deletions
diff --git a/src/distutils2/README b/src/distutils2/README
index 0416160..4afd700 100644
--- a/src/distutils2/README
+++ b/src/distutils2/README
@@ -1,4 +1,4 @@
-This directory contains the Distutils package.
+This directory contains the Distutils2 package.
There's a full documentation available at:
@@ -8,6 +8,6 @@ The Distutils-SIG web page is also a good starting point:
http://www.python.org/sigs/distutils-sig/
-WARNING: Distutils2 must remain compatible with 2.4
+WARNING: Distutils2 must remain compatible with Python 2.4
$Id: README 70017 2009-02-27 12:53:34Z tarek.ziade $
diff --git a/src/distutils2/_backport/pkgutil.py b/src/distutils2/_backport/pkgutil.py
index 8fbe24d..99f54ae 100644
--- a/src/distutils2/_backport/pkgutil.py
+++ b/src/distutils2/_backport/pkgutil.py
@@ -12,10 +12,17 @@ from types import ModuleType
from distutils2.errors import DistutilsError
from distutils2.metadata import DistributionMetadata
from distutils2.version import suggest_normalized_version, VersionPredicate
+import zipimport
+try:
+ import cStringIO as StringIO
+except ImportError:
+ import StringIO
+import re
+import warnings
__all__ = [
'get_importer', 'iter_importers', 'get_loader', 'find_loader',
- 'walk_packages', 'iter_modules',
+ 'walk_packages', 'iter_modules', 'get_data',
'ImpImporter', 'ImpLoader', 'read_code', 'extend_path',
'Distribution', 'EggInfoDistribution', 'distinfo_dirname',
'get_distributions', 'get_distribution', 'get_file_users',
@@ -24,7 +31,7 @@ __all__ = [
def read_code(stream):
- # This helper is needed in order for the PEP 302 emulation to
+ # This helper is needed in order for the :pep:`302` emulation to
# correctly handle compiled files
import marshal
@@ -79,32 +86,34 @@ def simplegeneric(func):
def walk_packages(path=None, prefix='', onerror=None):
- """Yields (module_loader, name, ispkg) for all modules recursively
- on path, or, if path is None, all accessible modules.
+ """Yields ``(module_loader, name, ispkg)`` for all modules recursively
+ on *path*, or, if *path* is ``None``, all accessible modules.
- 'path' should be either None or a list of paths to look for
- modules in.
+ :parameter path: should be either ``None`` or a list of paths to look for
+ modules in.
+ :parameter prefix: is a string to output on the front of every module name
+ on output.
- 'prefix' is a string to output on the front of every module name
- on output.
-
- Note that this function must import all *packages* (NOT all
- modules!) on the given path, in order to access the __path__
+ Note that this function must import all packages (NOT all
+ modules!) on the given path, in order to access the ``__path__``
attribute to find submodules.
- 'onerror' is a function which gets called with one argument (the
+ *onerror* is a function which gets called with one argument (the
name of the package which was being imported) if any exception
occurs while trying to import a package. If no onerror function is
- supplied, ImportErrors are caught and ignored, while all other
+ supplied, ``ImportErrors`` are caught and ignored, while all other
exceptions are propagated, terminating the search.
Examples:
- # list all modules python can access
- walk_packages()
+ * list all modules python can access::
+
+ walk_packages()
+
+ * list all submodules of ctypes::
+
+ walk_packages(ctypes.__path__, ctypes.__name__+'.')
- # list all submodules of ctypes
- walk_packages(ctypes.__path__, ctypes.__name__+'.')
"""
def seen(p, m={}):
@@ -137,14 +146,14 @@ def walk_packages(path=None, prefix='', onerror=None):
def iter_modules(path=None, prefix=''):
- """Yields (module_loader, name, ispkg) for all submodules on path,
- or, if path is None, all top-level modules on sys.path.
+ """Yields ``(module_loader, name, ispkg)`` for all submodules on path,
+ or, if *path* is ``None``, all top-level modules on ``sys.path``.
- 'path' should be either None or a list of paths to look for
- modules in.
+ :parameter path: should be either None or a list of paths to look for
+ modules in.
+ :parameter prefix: is a string to output on the front of every module name
+ on output.
- 'prefix' is a string to output on the front of every module name
- on output.
"""
if path is None:
@@ -162,6 +171,7 @@ def iter_modules(path=None, prefix=''):
#@simplegeneric
def iter_importer_modules(importer, prefix=''):
+ ""
if not hasattr(importer, 'iter_modules'):
return []
return importer.iter_modules(prefix)
@@ -170,14 +180,15 @@ iter_importer_modules = simplegeneric(iter_importer_modules)
class ImpImporter:
- """PEP 302 Importer that wraps Python's "classic" import algorithm
+ """:pep:`302` Importer that wraps Python's "classic" import algorithm
- ImpImporter(dirname) produces a PEP 302 importer that searches that
- directory. ImpImporter(None) produces a PEP 302 importer that searches
- the current sys.path, plus any modules that are frozen or built-in.
+ ``ImpImporter(dirname)`` produces a :pep:`302` importer that searches that
+ directory. ``ImpImporter(None)`` produces a :pep:`302` importer that
+ searches the current ``sys.path``, plus any modules that are frozen
+ or built-in.
- Note that ImpImporter does not currently support being used by placement
- on sys.meta_path.
+ Note that :class:`ImpImporter` does not currently support being used by placement
+ on ``sys.meta_path``.
"""
def __init__(self, path=None):
@@ -232,8 +243,8 @@ class ImpImporter:
class ImpLoader:
- """PEP 302 Loader that wraps Python's "classic" import algorithm
- """
+ """:pep:`302` Loader that wraps Python's "classic" import algorithm """
+
code = source = None
def __init__(self, fullname, file, filename, etc):
@@ -365,17 +376,17 @@ except ImportError:
def get_importer(path_item):
- """Retrieve a PEP 302 importer for the given path item
+ """Retrieve a :pep:`302` importer for the given path item
- The returned importer is cached in sys.path_importer_cache
+ The returned importer is cached in ``sys.path_importer_cache``
if it was newly created by a path hook.
If there is no importer, a wrapper around the basic import
machinery is returned. This wrapper is never inserted into
- the importer cache (None is inserted instead).
+ the importer cache (``None`` is inserted instead).
The cache (or part of it) can be cleared manually if a
- rescan of sys.path_hooks is necessary.
+ rescan of ``sys.path_hooks`` is necessary.
"""
try:
importer = sys.path_importer_cache[path_item]
@@ -399,7 +410,7 @@ def get_importer(path_item):
def iter_importers(fullname=""):
- """Yield PEP 302 importers for the given module name
+ """Yield :pep:`302` importers for the given module name
If fullname contains a '.', the importers will be for the package
containing fullname, otherwise they will be importers for sys.meta_path,
@@ -407,20 +418,20 @@ def iter_importers(fullname=""):
the named module is in a package, that package is imported as a side
effect of invoking this function.
- Non PEP 302 mechanisms (e.g. the Windows registry) used by the
+ Non :pep:`302` mechanisms (e.g. the Windows registry) used by the
standard import machinery to find files in alternative locations
- are partially supported, but are searched AFTER sys.path. Normally,
- these locations are searched BEFORE sys.path, preventing sys.path
+ are partially supported, but are searched AFTER ``sys.path``. Normally,
+ these locations are searched BEFORE sys.path, preventing ``sys.path``
entries from shadowing them.
For this to cause a visible difference in behaviour, there must
be a module or package name that is accessible via both sys.path
- and one of the non PEP 302 file system mechanisms. In this case,
+ and one of the non :pep:`302` file system mechanisms. In this case,
the emulation will find the former version, while the builtin
import mechanism will find the latter.
Items of the following types can be affected by this discrepancy:
- imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY
+ ``imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY``
"""
if fullname.startswith('.'):
raise ImportError("Relative module names not supported")
@@ -441,15 +452,15 @@ def iter_importers(fullname=""):
def get_loader(module_or_name):
- """Get a PEP 302 "loader" object for module_or_name
+ """Get a :pep:`302` "loader" object for module_or_name
If the module or package is accessible via the normal import
mechanism, a wrapper around the relevant part of that machinery
is returned. Returns None if the module cannot be found or imported.
If the named module is not already imported, its containing package
- (if any) is imported, in order to establish the package __path__.
+ (if any) is imported, in order to establish the package ``__path__``.
- This function uses iter_importers(), and is thus subject to the same
+ This function uses :func:`iter_importers`, and is thus subject to the same
limitations regarding platform-specific special import locations such
as the Windows registry.
"""
@@ -467,12 +478,13 @@ def get_loader(module_or_name):
def find_loader(fullname):
- """Find a PEP 302 "loader" object for fullname
+ """Find a :pep:`302` "loader" object for fullname
- If fullname contains dots, path must be the containing package's __path__.
- Returns None if the module cannot be found or imported. This function uses
- iter_importers(), and is thus subject to the same limitations regarding
- platform-specific special import locations such as the Windows registry.
+ If fullname contains dots, path must be the containing package's
+ ``__path__``. Returns ``None`` if the module cannot be found or imported.
+ This function uses :func:`iter_importers`, and is thus subject to the same
+ limitations regarding platform-specific special import locations such as
+ the Windows registry.
"""
for importer in iter_importers(fullname):
loader = importer.find_module(fullname)
@@ -485,21 +497,22 @@ def find_loader(fullname):
def extend_path(path, name):
"""Extend a package's path.
- Intended use is to place the following code in a package's __init__.py:
+ Intended use is to place the following code in a package's
+ ``__init__.py``::
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
- This will add to the package's __path__ all subdirectories of
- directories on sys.path named after the package. This is useful
+ This will add to the package's ``__path__`` all subdirectories of
+ directories on ``sys.path`` named after the package. This is useful
if one wants to distribute different parts of a single logical
package as multiple directories.
- It also looks for *.pkg files beginning where * matches the name
- argument. This feature is similar to *.pth files (see site.py),
- except that it doesn't special-case lines starting with 'import'.
- A *.pkg file is trusted at face value: apart from checking for
- duplicates, all entries found in a *.pkg file are added to the
+ It also looks for ``*.pkg`` files beginning where ``*`` matches the name
+ argument. This feature is similar to ``*.pth`` files (see ``site.py``),
+ except that it doesn't special-case lines starting with ``import``.
+ A ``*.pkg`` file is trusted at face value: apart from checking for
+ duplicates, all entries found in a ``*.pkg`` file are added to the
path, regardless of whether they are exist the filesystem. (This
is a feature.)
@@ -512,7 +525,7 @@ def extend_path(path, name):
are not (unicode or 8-bit) strings referring to existing
directories are ignored. Unicode items of sys.path that cause
errors when used as filenames may cause this function to raise an
- exception (in line with os.path.isdir() behavior).
+ exception (in line with ``os.path.isdir()`` behavior).
"""
if not isinstance(path, list):
@@ -560,23 +573,23 @@ def extend_path(path, name):
def get_data(package, resource):
"""Get a resource from a package.
- This is a wrapper round the PEP 302 loader get_data API. The package
+ This is a wrapper round the :pep:`302` loader get_data API. The package
argument should be the name of a package, in standard module format
- (foo.bar). The resource argument should be in the form of a relative
- filename, using '/' as the path separator. The parent directory name '..'
- is not allowed, and nor is a rooted name (starting with a '/').
+ (``foo.bar``). The resource argument should be in the form of a relative
+ filename, using ``'/'`` as the path separator. The parent directory name
+ ``'..'`` is not allowed, and nor is a rooted name (starting with a ``'/'``).
The function returns a binary string, which is the contents of the
specified resource.
For packages located in the filesystem, which have already been imported,
- this is the rough equivalent of
+ this is the rough equivalent of::
d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()
- If the package cannot be located or loaded, or it uses a PEP 302 loader
- which does not support get_data(), then None is returned.
+ If the package cannot be located or loaded, or it uses a :pep:`302` loader
+ which does not support :func:`get_data`, then ``None`` is returned.
"""
loader = get_loader(package)
@@ -603,7 +616,7 @@ DIST_FILES = ('INSTALLER', 'METADATA', 'RECORD', 'REQUESTED',)
class Distribution(object):
"""Created with the *path* of the ``.dist-info`` directory provided to the
- constructor. It reads the metadata contained in METADATA when it is
+ constructor. It reads the metadata contained in ``METADATA`` when it is
instantiated."""
# Attribute documenting for Sphinx style documentation, see for more info:
@@ -612,9 +625,9 @@ class Distribution(object):
"""The name of the distribution."""
metadata = None
"""A :class:`distutils2.metadata.DistributionMetadata` instance loaded with
- the distribution's METADATA file."""
+ the distribution's ``METADATA`` file."""
requested = False
- """A boolean that indicates whether the REQUESTED metadata file is present
+ """A boolean that indicates whether the ``REQUESTED`` metadata file is present
(in other words, whether the package was installed by user request)."""
def __init__(self, path):
@@ -635,15 +648,17 @@ class Distribution(object):
def get_installed_files(self, local=False):
"""
- Iterates over the RECORD entries and returns a tuple (path, md5, size)
- for each line. If *local* is ``True``, the returned path is transformed
- into a local absolute path. Otherwise the raw value from RECORD is
- returned.
+ Iterates over the ``RECORD`` entries and returns a tuple
+ ``(path, md5, size)`` for each line. If *local* is ``True``,
+ the returned path is transformed into a local absolute path.
+ Otherwise the raw value from RECORD is returned.
A local absolute path is an absolute path in which occurrences of
``'/'`` have been replaced by the system separator given by ``os.sep``.
+
:parameter local: flag to say if the path should be returned a local
absolute path
+
:type local: boolean
:returns: iterator of (path, md5, size)
"""
@@ -651,7 +666,7 @@ class Distribution(object):
def uses(self, path):
"""
- Returns ``True`` if path is listed in RECORD. *path* can be a local
+ Returns ``True`` if path is listed in ``RECORD``. *path* can be a local
absolute path or a relative ``'/'``-separated path.
:rtype: boolean
@@ -673,8 +688,8 @@ class Distribution(object):
directory path, a :class:`DistutilsError` is raised
:type path: string
:parameter binary: If *binary* is ``True``, opens the file in read-only
- binary mode (rb), otherwise opens it in read-only
- mode (r).
+ binary mode (``rb``), otherwise opens it in read-only
+ mode (``r``).
:rtype: file object
"""
open_flags = 'r'
@@ -701,37 +716,126 @@ class Distribution(object):
def get_distinfo_files(self, local=False):
"""
- Iterates over the RECORD entries and returns paths for each line if the
- path is pointing to a file located in the ``.dist-info`` directory or
- one of its subdirectories.
+ Iterates over the ``RECORD`` entries and returns paths for each line if
+ the path is pointing to a file located in the ``.dist-info`` directory
+ or one of its subdirectories.
:parameter local: If *local* is ``True``, each returned path is
transformed into a local absolute path. Otherwise the
- raw value from RECORD is returned.
+ raw value from ``RECORD`` is returned.
:type local: boolean
:returns: iterator of paths
"""
for path, md5, size in self._get_records(local):
yield path
+ def __eq__(self, other):
+ return isinstance(other, Distribution) and self.path == other.path
+
class EggInfoDistribution(object):
"""Created with the *path* of the ``.egg-info`` directory or file provided
to the constructor. It reads the metadata contained in the file itself, or
if the given path happens to be a directory, the metadata is read from the
- file PKG-INFO under that directory."""
+ file ``PKG-INFO`` under that directory."""
name = ''
"""The name of the distribution."""
metadata = None
"""A :class:`distutils2.metadata.DistributionMetadata` instance loaded with
- the distribution's METADATA file."""
+ the distribution's ``METADATA`` file."""
+ _REQUIREMENT = re.compile( \
+ r'(?P<name>[-A-Za-z0-9_.]+)\s*' \
+ r'(?P<first>(?:<|<=|!=|==|>=|>)[-A-Za-z0-9_.]+)?\s*' \
+ r'(?P<rest>(?:\s*,\s*(?:<|<=|!=|==|>=|>)[-A-Za-z0-9_.]+)*)\s*' \
+ r'(?P<extras>\[.*\])?')
def __init__(self, path):
- if os.path.isdir(path):
- path = os.path.join(path, 'PKG-INFO')
- self.metadata = DistributionMetadata(path=path)
- self.name = self.metadata['name']
+ self.path = path
+
+ # reused from Distribute's pkg_resources
+ def yield_lines(strs):
+ """Yield non-empty/non-comment lines of a ``basestring`` or sequence"""
+ if isinstance(strs, basestring):
+ for s in strs.splitlines():
+ s = s.strip()
+ if s and not s.startswith('#'): # skip blank lines/comments
+ yield s
+ else:
+ for ss in strs:
+ for s in yield_lines(ss):
+ yield s
+
+ requires = None
+ if path.endswith('.egg'):
+ if os.path.isdir(path):
+ meta_path = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
+ self.metadata = DistributionMetadata(path=meta_path)
+ try:
+ req_path = os.path.join(path, 'EGG-INFO', 'requires.txt')
+ requires = open(req_path, 'r').read()
+ except IOError:
+ requires = None
+ else:
+ zipf = zipimport.zipimporter(path)
+ fileobj = StringIO.StringIO(zipf.get_data('EGG-INFO/PKG-INFO'))
+ self.metadata = DistributionMetadata(fileobj=fileobj)
+ try:
+ requires = zipf.get_data('EGG-INFO/requires.txt')
+ except IOError:
+ requires = None
+ self.name = self.metadata['name']
+ elif path.endswith('.egg-info'):
+ if os.path.isdir(path):
+ path = os.path.join(path, 'PKG-INFO')
+ try:
+ req_f = open(os.path.join(path, 'requires.txt'), 'r')
+ requires = req_f.read()
+ except IOError:
+ requires = None
+ self.metadata = DistributionMetadata(path=path)
+ self.name = self.metadata['name']
+ else:
+ raise ValueError('The path must end with .egg-info or .egg')
+
+ provides = "%s (%s)" % (self.metadata['name'],
+ self.metadata['version'])
+ if self.metadata['Metadata-Version'] == '1.2':
+ self.metadata['Provides-Dist'] += (provides,)
+ else:
+ self.metadata['Provides'] += (provides,)
+ reqs = []
+ if requires is not None:
+ for line in yield_lines(requires):
+ if line[0] == '[':
+ warnings.warn('distutils2 does not support extensions in requires.txt')
+ break
+ else:
+ match = self._REQUIREMENT.match(line.strip())
+ if not match:
+ raise ValueError('Distribution %s has ill formed '
+ 'requires.txt file (%s)' %
+ (self.name, line))
+ else:
+ if match.group('extras'):
+ s = 'Distribution %s uses extra requirements which'\
+ ' are not supported in distutils' % (self.name)
+ warnings.warn(s)
+ name = match.group('name')
+ version = None
+ if match.group('first'):
+ version = match.group('first')
+ if match.group('rest'):
+ version += match.group('rest')
+ version = version.replace(' ', '') # trim spaces
+ if version is None:
+ reqs.append(name)
+ else:
+ reqs.append('%s (%s)' % (name, version))
+ if self.metadata['Metadata-Version'] == '1.2':
+ self.metadata['Requires-Dist'] += reqs
+ else:
+ self.metadata['Requires'] += reqs
def get_installed_files(self, local=False):
return []
@@ -739,6 +843,10 @@ class EggInfoDistribution(object):
def uses(self, path):
return False
+ def __eq__(self, other):
+ return isinstance(other, EggInfoDistribution) and \
+ self.path == other.path
+
def _normalize_dist_name(name):
"""Returns a normalized name from the given *name*.
@@ -792,7 +900,8 @@ def get_distributions(use_egg_info=False):
if dir.endswith('.dist-info'):
dist = Distribution(os.path.join(realpath, dir))
yield dist
- elif use_egg_info and dir.endswith('.egg-info'):
+ elif use_egg_info and (dir.endswith('.egg-info') or
+ dir.endswith('.egg')):
dist = EggInfoDistribution(os.path.join(realpath, dir))
yield dist
@@ -801,18 +910,18 @@ def get_distribution(name, use_egg_info=False):
"""
Scans all elements in ``sys.path`` and looks for all directories ending with
``.dist-info``. Returns a :class:`Distribution` corresponding to the
- ``.dist-info`` directory that contains the METADATA that matches *name* for
- the *name* metadata field.
+ ``.dist-info`` directory that contains the ``METADATA`` that matches *name*
+ for the *name* metadata field.
If no distribution exists with the given *name* and the parameter
*use_egg_info* is set to ``True``, then all files and directories ending
with ``.egg-info`` are scanned. A :class:`EggInfoDistribution` instance is
returned if one is found that has metadata that matches *name* for the
*name* metadata field.
- This function only returns the first result founded, as no more than one
+ This function only returns the first result found, as no more than one
value is expected. If the directory is not found, ``None`` is returned.
- :rtype: :class:`Distribution` or :class:`EggInfoDistribution: or None"""
+ :rtype: :class:`Distribution` or :class:`EggInfoDistribution` or None"""
found = None
for dist in get_distributions():
if dist.name == name:
@@ -867,7 +976,7 @@ def provides_distribution(name, version=None, use_egg_info=False):
then all files and directories ending with ``.egg-info`` are considered
as well and returns an :class:`EggInfoDistribution` instance.
- This function only returns the first result founded, since no more than
+ This function only returns the first result found, since no more than
one values are expected. If the directory is not found, returns ``None``.
:parameter version: a version specifier that indicates the version
@@ -887,7 +996,7 @@ def provides_distribution(name, version=None, use_egg_info=False):
provided = dist.metadata['Provides-Dist'] + dist.metadata['Provides']
for p in provided:
- p_components = p.split(' ', 1)
+ p_components = p.rsplit(' ', 1)
if len(p_components) == 1 or predicate is None:
if name == p_components[0]:
yield dist
@@ -896,7 +1005,8 @@ def provides_distribution(name, version=None, use_egg_info=False):
p_name, p_ver = p_components
if len(p_ver) < 2 or p_ver[0] != '(' or p_ver[-1] != ')':
raise DistutilsError(('Distribution %s has invalid ' +
- 'provides field') % (dist.name,))
+ 'provides field: %s') \
+ % (dist.name, p))
p_ver = p_ver[1:-1] # trim off the parenthesis
if p_name == name and predicate.match(p_ver):
yield dist
diff --git a/src/distutils2/_backport/sysconfig.cfg b/src/distutils2/_backport/sysconfig.cfg
index 2a2a996..01328db 100644
--- a/src/distutils2/_backport/sysconfig.cfg
+++ b/src/distutils2/_backport/sysconfig.cfg
@@ -1,6 +1,6 @@
[globals]
# These are the useful categories that are sometimes referenced at runtime,
-# using pkgutils.open():
+# using pkgutil.open():
config = {confdir}/{distribution.name} # Configuration files
appdata = {datadir}/{distribution.name} # Non-writable data that is independent of architecture (images, many xml/text files)
appdata.arch = {libdir}/{distribution.name} # Non-writable data that is architecture-dependent (some binary data formats)
diff --git a/src/distutils2/_backport/sysconfig.py b/src/distutils2/_backport/sysconfig.py
index 5d082b7..e2448f8 100644
--- a/src/distutils2/_backport/sysconfig.py
+++ b/src/distutils2/_backport/sysconfig.py
@@ -5,7 +5,7 @@ import sys
import os
import re
from os.path import pardir, abspath
-from ConfigParser import ConfigParser
+from ConfigParser import RawConfigParser
_PREFIX = os.path.normpath(sys.prefix)
_EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
@@ -14,7 +14,7 @@ _EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
# XXX _CONFIG_DIR will be set by the Makefile later
_CONFIG_DIR = os.path.normpath(os.path.dirname(__file__))
_CONFIG_FILE = os.path.join(_CONFIG_DIR, 'sysconfig.cfg')
-_SCHEMES = ConfigParser()
+_SCHEMES = RawConfigParser()
_SCHEMES.read(_CONFIG_FILE)
_VAR_REPL = re.compile(r'\{([^{]*?)\}')
diff --git a/src/distutils2/_backport/tests/__init__.py b/src/distutils2/_backport/tests/__init__.py
index 9a7ff25..e816dd0 100644
--- a/src/distutils2/_backport/tests/__init__.py
+++ b/src/distutils2/_backport/tests/__init__.py
@@ -1,12 +1,13 @@
import os
import sys
-import unittest2
+
+from distutils2.tests.support import unittest
here = os.path.dirname(__file__)
def test_suite():
- suite = unittest2.TestSuite()
+ suite = unittest.TestSuite()
for fn in os.listdir(here):
if fn.startswith("test") and fn.endswith(".py"):
modname = "distutils2._backport.tests." + fn[:-3]
diff --git a/src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO b/src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO
index 8914d76..a176dfd 100644
--- a/src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO
+++ b/src/distutils2/_backport/tests/fake_dists/bacon-0.1.egg-info/PKG-INFO
@@ -2,4 +2,5 @@ Metadata-Version: 1.2
Name: bacon
Version: 0.1
Provides-Dist: truffles (2.0)
+Provides-Dist: bacon (0.1)
Obsoletes-Dist: truffles (>=0.9,<=1.5)
diff --git a/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/PKG-INFO b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/PKG-INFO
new file mode 100644
index 0000000..a7e118a
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/PKG-INFO
@@ -0,0 +1,18 @@
+Metadata-Version: 1.0
+Name: banana
+Version: 0.4
+Summary: A yellow fruit
+Home-page: http://en.wikipedia.org/wiki/Banana
+Author: Josip Djolonga
+Author-email: foo@nbar.com
+License: BSD
+Description: A fruit
+Keywords: foo bar
+Platform: UNKNOWN
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Science/Research
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Topic :: Scientific/Engineering :: GIS
diff --git a/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/SOURCES.txt b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/SOURCES.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/SOURCES.txt
diff --git a/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/dependency_links.txt b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/dependency_links.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/entry_points.txt b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/entry_points.txt
new file mode 100644
index 0000000..5d3e5f6
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/entry_points.txt
@@ -0,0 +1,3 @@
+
+ # -*- Entry points: -*-
+ \ No newline at end of file
diff --git a/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/not-zip-safe b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/not-zip-safe
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/not-zip-safe
@@ -0,0 +1 @@
+
diff --git a/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/requires.txt b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/requires.txt
new file mode 100644
index 0000000..4354305
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/requires.txt
@@ -0,0 +1,6 @@
+# this should be ignored
+
+strawberry >=0.5
+
+[section ignored]
+foo ==0.5
diff --git a/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/top_level.txt b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/top_level.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/banana-0.4.egg/EGG-INFO/top_level.txt
diff --git a/src/distutils2/_backport/tests/fake_dists/strawberry-0.6.egg b/src/distutils2/_backport/tests/fake_dists/strawberry-0.6.egg
new file mode 100644
index 0000000..6d160e8
--- /dev/null
+++ b/src/distutils2/_backport/tests/fake_dists/strawberry-0.6.egg
Binary files differ
diff --git a/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA b/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA
index e8b764e..ca46d0a 100644
--- a/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA
+++ b/src/distutils2/_backport/tests/fake_dists/towel_stuff-0.1.dist-info/METADATA
@@ -2,4 +2,6 @@ Metadata-Version: 1.2
Name: towel-stuff
Version: 0.1
Provides-Dist: truffles (1.1.2)
+Provides-Dist: towel-stuff (0.1)
Obsoletes-Dist: truffles (!=0.8,<1.0)
+Requires-Dist: bacon (<=0.2)
diff --git a/src/distutils2/_backport/tests/test_pkgutil.py b/src/distutils2/_backport/tests/test_pkgutil.py
index 46ba64c..ae75d69 100644
--- a/src/distutils2/_backport/tests/test_pkgutil.py
+++ b/src/distutils2/_backport/tests/test_pkgutil.py
@@ -4,6 +4,10 @@ import unittest2
import sys
import os
import csv
+import imp
+import tempfile
+import shutil
+import zipfile
try:
from hashlib import md5
except ImportError:
@@ -11,30 +15,141 @@ except ImportError:
from test.test_support import run_unittest, TESTFN
-import distutils2._backport.pkgutil
+from distutils2._backport import pkgutil
# TODO Add a test for getting a distribution that is provided by another
# distribution.
# TODO Add a test for absolute pathed RECORD items (e.g. /etc/myapp/config.ini)
+# Adapted from Python 2.7's trunk
+class TestPkgUtilData(unittest2.TestCase):
+
+ def setUp(self):
+ self.dirname = tempfile.mkdtemp()
+ sys.path.insert(0, self.dirname)
+
+ def tearDown(self):
+ del sys.path[0]
+ shutil.rmtree(self.dirname)
+
+ def test_getdata_filesys(self):
+ pkg = 'test_getdata_filesys'
+
+ # Include a LF and a CRLF, to test that binary data is read back
+ RESOURCE_DATA = 'Hello, world!\nSecond line\r\nThird line'
+
+ # Make a package with some resources
+ package_dir = os.path.join(self.dirname, pkg)
+ os.mkdir(package_dir)
+ # Empty init.py
+ f = open(os.path.join(package_dir, '__init__.py'), "wb")
+ f.close()
+ # Resource files, res.txt, sub/res.txt
+ f = open(os.path.join(package_dir, 'res.txt'), "wb")
+ f.write(RESOURCE_DATA)
+ f.close()
+ os.mkdir(os.path.join(package_dir, 'sub'))
+ f = open(os.path.join(package_dir, 'sub', 'res.txt'), "wb")
+ f.write(RESOURCE_DATA)
+ f.close()
+
+ # Check we can read the resources
+ res1 = pkgutil.get_data(pkg, 'res.txt')
+ self.assertEqual(res1, RESOURCE_DATA)
+ res2 = pkgutil.get_data(pkg, 'sub/res.txt')
+ self.assertEqual(res2, RESOURCE_DATA)
+
+ del sys.modules[pkg]
+
+ def test_getdata_zipfile(self):
+ zip = 'test_getdata_zipfile.zip'
+ pkg = 'test_getdata_zipfile'
+
+ # Include a LF and a CRLF, to test that binary data is read back
+ RESOURCE_DATA = 'Hello, world!\nSecond line\r\nThird line'
+
+ # Make a package with some resources
+ zip_file = os.path.join(self.dirname, zip)
+ z = zipfile.ZipFile(zip_file, 'w')
+
+ # Empty init.py
+ z.writestr(pkg + '/__init__.py', "")
+ # Resource files, res.txt, sub/res.txt
+ z.writestr(pkg + '/res.txt', RESOURCE_DATA)
+ z.writestr(pkg + '/sub/res.txt', RESOURCE_DATA)
+ z.close()
+
+ # Check we can read the resources
+ sys.path.insert(0, zip_file)
+ res1 = pkgutil.get_data(pkg, 'res.txt')
+ self.assertEqual(res1, RESOURCE_DATA)
+ res2 = pkgutil.get_data(pkg, 'sub/res.txt')
+ self.assertEqual(res2, RESOURCE_DATA)
+ del sys.path[0]
+
+ del sys.modules[pkg]
+
+# Adapted from Python 2.7's trunk
+class TestPkgUtilPEP302(unittest2.TestCase):
+
+ class MyTestLoader(object):
+ def load_module(self, fullname):
+ # Create an empty module
+ mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
+ mod.__file__ = "<%s>" % self.__class__.__name__
+ mod.__loader__ = self
+ # Make it a package
+ mod.__path__ = []
+ # Count how many times the module is reloaded
+ mod.__dict__['loads'] = mod.__dict__.get('loads',0) + 1
+ return mod
+
+ def get_data(self, path):
+ return "Hello, world!"
+
+ class MyTestImporter(object):
+ def find_module(self, fullname, path=None):
+ return TestPkgUtilPEP302.MyTestLoader()
+
+ def setUp(self):
+ sys.meta_path.insert(0, self.MyTestImporter())
+
+ def tearDown(self):
+ del sys.meta_path[0]
+
+ def test_getdata_pep302(self):
+ # Use a dummy importer/loader
+ self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
+ del sys.modules['foo']
+
+ def test_alreadyloaded(self):
+ # Ensure that get_data works without reloading - the "loads" module
+ # variable in the example loader should count how many times a reload
+ # occurs.
+ import foo
+ self.assertEqual(foo.loads, 1)
+ self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
+ self.assertEqual(foo.loads, 1)
+ del sys.modules['foo']
+
+
class TestPkgUtilDistribution(unittest2.TestCase):
"""Tests the pkgutil.Distribution class"""
def setUp(self):
- super(TestPkgUtilDistribution, self).setUp()
-
self.fake_dists_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'fake_dists'))
- self.distinfo_dirs = [ os.path.join(self.fake_dists_path, dir)
+
+ self.distinfo_dirs = [os.path.join(self.fake_dists_path, dir)
for dir in os.listdir(self.fake_dists_path)
- if dir.endswith('.dist-info')
- ]
+ if dir.endswith('.dist-info')]
def get_hexdigest(file):
md5_hash = md5()
md5_hash.update(open(file).read())
return md5_hash.hexdigest()
+
def record_pieces(file):
path = os.path.relpath(file, sys.prefix)
digest = get_hexdigest(file)
@@ -51,7 +166,8 @@ class TestPkgUtilDistribution(unittest2.TestCase):
for path, dirs, files in os.walk(dist_location):
for f in files:
- record_writer.writerow(record_pieces(os.path.join(path, f)))
+ record_writer.writerow(record_pieces(
+ os.path.join(path, f)))
for file in ['INSTALLER', 'METADATA', 'REQUESTED']:
record_writer.writerow(record_pieces(
os.path.join(distinfo_dir, file)))
@@ -60,7 +176,8 @@ class TestPkgUtilDistribution(unittest2.TestCase):
record_reader = csv.reader(open(record_file, 'rb'))
record_data = []
for row in record_reader:
- path, md5_, size = row[:] + [ None for i in xrange(len(row), 3) ]
+ path, md5_, size = row[:] + \
+ [None for i in xrange(len(row), 3)]
record_data.append([path, (md5_, size,)])
self.records[distinfo_dir] = dict(record_data)
@@ -69,7 +186,6 @@ class TestPkgUtilDistribution(unittest2.TestCase):
for distinfo_dir in self.distinfo_dirs:
record_file = os.path.join(distinfo_dir, 'RECORD')
open(record_file, 'w').close()
- super(TestPkgUtilDistribution, self).tearDown()
def test_instantiation(self):
"""Test the Distribution class's instantiation provides us with usable
@@ -108,7 +224,8 @@ class TestPkgUtilDistribution(unittest2.TestCase):
distinfo_name = 'grammar-1.0a4'
distinfo_dir = os.path.join(self.fake_dists_path,
distinfo_name + '.dist-info')
- true_path = [self.fake_dists_path, distinfo_name, 'grammar', 'utils.py']
+ true_path = [self.fake_dists_path, distinfo_name, \
+ 'grammar', 'utils.py']
true_path = os.path.relpath(os.path.join(*true_path), sys.prefix)
false_path = [self.fake_dists_path, 'towel_stuff-0.1', 'towel_stuff',
'__init__.py']
@@ -150,7 +267,8 @@ class TestPkgUtilDistribution(unittest2.TestCase):
self.assertRaises(DistutilsError, dist.get_distinfo_file,
other_distinfo_file)
# Test for a file that does not exist and should not exist
- self.assertRaises(DistutilsError, dist.get_distinfo_file, 'ENTRYPOINTS')
+ self.assertRaises(DistutilsError, dist.get_distinfo_file, \
+ 'ENTRYPOINTS')
def test_get_distinfo_files(self):
"""Test for the iteration of RECORD path entries."""
@@ -161,21 +279,19 @@ class TestPkgUtilDistribution(unittest2.TestCase):
dist = Distribution(distinfo_dir)
# Test for the iteration of the raw path
distinfo_record_paths = self.records[distinfo_dir].keys()
- found = [ path for path in dist.get_distinfo_files() ]
+ found = [path for path in dist.get_distinfo_files()]
self.assertEqual(sorted(found), sorted(distinfo_record_paths))
# Test for the iteration of local absolute paths
- distinfo_record_paths = [ os.path.join(sys.prefix, path)
- for path in self.records[distinfo_dir].keys()
- ]
- found = [ path for path in dist.get_distinfo_files(local=True) ]
+ distinfo_record_paths = [os.path.join(sys.prefix, path)
+ for path in self.records[distinfo_dir].keys()]
+ found = [path for path in dist.get_distinfo_files(local=True)]
self.assertEqual(sorted(found), sorted(distinfo_record_paths))
-class TestPkgUtilFunctions(unittest2.TestCase):
+class TestPkgUtilPEP376(unittest2.TestCase):
"""Tests for the new functionality added in PEP 376."""
def setUp(self):
- super(TestPkgUtilFunctions, self).setUp()
# Setup the path environment with our fake distributions
current_path = os.path.abspath(os.path.dirname(__file__))
self.sys_path = sys.path[:]
@@ -183,15 +299,15 @@ class TestPkgUtilFunctions(unittest2.TestCase):
sys.path[0:0] = [self.fake_dists_path]
def tearDown(self):
- super(TestPkgUtilFunctions, self).tearDown()
sys.path[:] = self.sys_path
def test_distinfo_dirname(self):
"""Given a name and a version, we expect the distinfo_dirname function
to return a standard distribution information directory name."""
- items = [ # (name, version, standard_dirname)
- # Test for a very simple single word name and decimal version number
+ items = [# (name, version, standard_dirname)
+ # Test for a very simple single word name and decimal
+ # version number
('docutils', '0.5', 'docutils-0.5.dist-info'),
# Test for another except this time with a '-' in the name, which
# needs to be transformed during the name lookup
@@ -221,7 +337,7 @@ class TestPkgUtilFunctions(unittest2.TestCase):
EggInfoDistribution
# Verify the fake dists have been found.
- dists = [ dist for dist in get_distributions() ]
+ dists = [dist for dist in get_distributions()]
for dist in dists:
if not isinstance(dist, Distribution):
self.fail("item received was not a Distribution instance: "
@@ -234,10 +350,11 @@ class TestPkgUtilFunctions(unittest2.TestCase):
self.assertListEqual(sorted(found_dists), sorted(fake_dists))
# Now, test if the egg-info distributions are found correctly as well
- fake_dists += [('bacon', '0.1'), ('cheese', '2.0.2')]
+ fake_dists += [('bacon', '0.1'), ('cheese', '2.0.2'),
+ ('banana', '0.4'), ('strawberry', '0.6')]
found_dists = []
- dists = [ dist for dist in get_distributions(use_egg_info=True) ]
+ dists = [dist for dist in get_distributions(use_egg_info=True)]
for dist in dists:
if not (isinstance(dist, Distribution) or \
isinstance(dist, EggInfoDistribution)):
@@ -248,7 +365,6 @@ class TestPkgUtilFunctions(unittest2.TestCase):
self.assertListEqual(sorted(fake_dists), sorted(found_dists))
-
def test_get_distribution(self):
"""Test for looking up a distribution by name."""
# Test the lookup of the towel-stuff distribution
@@ -274,6 +390,8 @@ class TestPkgUtilFunctions(unittest2.TestCase):
# instructed to
self.assertEqual(None, get_distribution('bacon'))
self.assertEqual(None, get_distribution('cheese'))
+ self.assertEqual(None, get_distribution('strawberry'))
+ self.assertEqual(None, get_distribution('banana'))
# Now check that it works well in both situations, when egg-info
# is a file and directory respectively.
@@ -285,6 +403,14 @@ class TestPkgUtilFunctions(unittest2.TestCase):
self.assertTrue(isinstance(dist, EggInfoDistribution))
self.assertEqual(dist.name, 'bacon')
+ dist = get_distribution('banana', use_egg_info=True)
+ self.assertTrue(isinstance(dist, EggInfoDistribution))
+ self.assertEqual(dist.name, 'banana')
+
+ dist = get_distribution('strawberry', use_egg_info=True)
+ self.assertTrue(isinstance(dist, EggInfoDistribution))
+ self.assertEqual(dist.name, 'strawberry')
+
def test_get_file_users(self):
"""Test the iteration of distributions that use a file."""
from distutils2._backport.pkgutil import get_file_users, Distribution
@@ -300,7 +426,7 @@ class TestPkgUtilFunctions(unittest2.TestCase):
from distutils2._backport.pkgutil import provides_distribution
from distutils2.errors import DistutilsError
- checkLists = lambda x,y: self.assertListEqual(sorted(x), sorted(y))
+ checkLists = lambda x, y: self.assertListEqual(sorted(x), sorted(y))
l = [dist.name for dist in provides_distribution('truffles')]
checkLists(l, ['choxie', 'towel-stuff'])
@@ -318,10 +444,12 @@ class TestPkgUtilFunctions(unittest2.TestCase):
l = [dist.name for dist in provides_distribution('truffles', '1.1')]
checkLists(l, ['towel-stuff'])
- l = [dist.name for dist in provides_distribution('truffles', '!=1.1,<=2.0')]
+ l = [dist.name for dist in provides_distribution('truffles', \
+ '!=1.1,<=2.0')]
checkLists(l, ['choxie'])
- l = [dist.name for dist in provides_distribution('truffles', '!=1.1,<=2.0',
+ l = [dist.name for dist in provides_distribution('truffles', \
+ '!=1.1,<=2.0',
use_egg_info=True)]
checkLists(l, ['choxie', 'bacon', 'cheese'])
@@ -338,12 +466,39 @@ class TestPkgUtilFunctions(unittest2.TestCase):
l = [dist.name for dist in provides_distribution('truffles', '>=1.0')]
checkLists(l, ['choxie', 'towel-stuff'])
+ l = [dist.name for dist in provides_distribution('strawberry', '0.6',
+ use_egg_info=True)]
+ checkLists(l, ['strawberry'])
+
+ l = [dist.name for dist in provides_distribution('strawberry', '>=0.5',
+ use_egg_info=True)]
+ checkLists(l, ['strawberry'])
+
+
+ l = [dist.name for dist in provides_distribution('strawberry', '>0.6',
+ use_egg_info=True)]
+ checkLists(l, [])
+
+
+ l = [dist.name for dist in provides_distribution('banana', '0.4',
+ use_egg_info=True)]
+ checkLists(l, ['banana'])
+
+ l = [dist.name for dist in provides_distribution('banana', '>=0.3',
+ use_egg_info=True)]
+ checkLists(l, ['banana'])
+
+
+ l = [dist.name for dist in provides_distribution('banana', '!=0.4',
+ use_egg_info=True)]
+ checkLists(l, [])
+
def test_obsoletes(self):
""" Test looking for distributions based on what they obsolete """
from distutils2._backport.pkgutil import obsoletes_distribution
from distutils2.errors import DistutilsError
- checkLists = lambda x,y: self.assertListEqual(sorted(x), sorted(y))
+ checkLists = lambda x, y: self.assertListEqual(sorted(x), sorted(y))
l = [dist.name for dist in obsoletes_distribution('truffles', '1.0')]
checkLists(l, [])
@@ -363,7 +518,8 @@ class TestPkgUtilFunctions(unittest2.TestCase):
l = [dist.name for dist in obsoletes_distribution('truffles', '0.9.6')]
checkLists(l, ['choxie', 'towel-stuff'])
- l = [dist.name for dist in obsoletes_distribution('truffles', '0.5.2.3')]
+ l = [dist.name for dist in obsoletes_distribution('truffles', \
+ '0.5.2.3')]
checkLists(l, ['choxie', 'towel-stuff'])
l = [dist.name for dist in obsoletes_distribution('truffles', '0.2')]
@@ -373,25 +529,16 @@ class TestPkgUtilFunctions(unittest2.TestCase):
def test_suite():
suite = unittest2.TestSuite()
testcase_loader = unittest2.loader.defaultTestLoader.loadTestsFromTestCase
- suite.addTest(testcase_loader(TestPkgUtilFunctions))
+ suite.addTest(testcase_loader(TestPkgUtilData))
suite.addTest(testcase_loader(TestPkgUtilDistribution))
+ suite.addTest(testcase_loader(TestPkgUtilPEP302))
+ suite.addTest(testcase_loader(TestPkgUtilPEP376))
return suite
-def test_main():
- run_unittest(test_suite())
-
-if __name__ == "__main__":
- test_main()
-
-def test_suite():
- suite = unittest2.TestSuite()
- testcase_loader = unittest2.loader.defaultTestLoader.loadTestsFromTestCase
- suite.addTest(testcase_loader(TestPkgUtilFunctions))
- suite.addTest(testcase_loader(TestPkgUtilDistribution))
- return suite
def test_main():
run_unittest(test_suite())
+
if __name__ == "__main__":
test_main()
diff --git a/src/distutils2/_backport/tests/test_sysconfig.py b/src/distutils2/_backport/tests/test_sysconfig.py
index e4db614..f6f21e8 100644
--- a/src/distutils2/_backport/tests/test_sysconfig.py
+++ b/src/distutils2/_backport/tests/test_sysconfig.py
@@ -4,12 +4,11 @@ Tests assume the initial paths in sys.path once the interpreter has begun
executing have not been removed.
"""
-import unittest2
import sys
import os
import shutil
from copy import copy, deepcopy
-from ConfigParser import ConfigParser
+from ConfigParser import RawConfigParser
from test.test_support import run_unittest, TESTFN
@@ -19,8 +18,9 @@ from distutils2._backport.sysconfig import (get_paths, get_platform,
get_path, get_path_names,
_get_default_scheme, _subst_vars, _expand_vars,
get_scheme_names, _CONFIG_FILE)
+from distutils2.tests.support import unittest
-class TestSysConfig(unittest2.TestCase):
+class TestSysConfig(unittest.TestCase):
def setUp(self):
"""Make a copy of sys.path"""
@@ -97,7 +97,7 @@ class TestSysConfig(unittest2.TestCase):
substitution key (which would be weird).
"""
- self.failUnlessEqual(_subst_vars('{py{version}}', {'version': '31'}), '{py31}')
+ self.assertEqual(_subst_vars('{py{version}}', {'version': '31'}), '{py31}')
def test_get_paths(self):
scheme = get_paths()
@@ -107,7 +107,7 @@ class TestSysConfig(unittest2.TestCase):
wanted.sort()
scheme = scheme.items()
scheme.sort()
- self.assertEquals(scheme, wanted)
+ self.assertEqual(scheme, wanted)
def test_get_config_vars(self):
cvars = get_config_vars()
@@ -120,21 +120,21 @@ class TestSysConfig(unittest2.TestCase):
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Intel)]')
sys.platform = 'win32'
- self.assertEquals(get_platform(), 'win32')
+ self.assertEqual(get_platform(), 'win32')
# windows XP, amd64
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Amd64)]')
sys.platform = 'win32'
- self.assertEquals(get_platform(), 'win-amd64')
+ self.assertEqual(get_platform(), 'win-amd64')
# windows XP, itanium
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Itanium)]')
sys.platform = 'win32'
- self.assertEquals(get_platform(), 'win-ia64')
+ self.assertEqual(get_platform(), 'win-ia64')
# macbook
os.name = 'posix'
@@ -153,9 +153,9 @@ class TestSysConfig(unittest2.TestCase):
maxint = sys.maxint
try:
sys.maxint = 2147483647
- self.assertEquals(get_platform(), 'macosx-10.3-ppc')
+ self.assertEqual(get_platform(), 'macosx-10.3-ppc')
sys.maxint = 9223372036854775807
- self.assertEquals(get_platform(), 'macosx-10.3-ppc64')
+ self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
finally:
sys.maxint = maxint
@@ -173,9 +173,9 @@ class TestSysConfig(unittest2.TestCase):
maxint = sys.maxint
try:
sys.maxint = 2147483647
- self.assertEquals(get_platform(), 'macosx-10.3-i386')
+ self.assertEqual(get_platform(), 'macosx-10.3-i386')
sys.maxint = 9223372036854775807
- self.assertEquals(get_platform(), 'macosx-10.3-x86_64')
+ self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
finally:
sys.maxint = maxint
@@ -186,33 +186,33 @@ class TestSysConfig(unittest2.TestCase):
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
- self.assertEquals(get_platform(), 'macosx-10.4-fat')
+ self.assertEqual(get_platform(), 'macosx-10.4-fat')
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
- self.assertEquals(get_platform(), 'macosx-10.4-intel')
+ self.assertEqual(get_platform(), 'macosx-10.4-intel')
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
- self.assertEquals(get_platform(), 'macosx-10.4-fat3')
+ self.assertEqual(get_platform(), 'macosx-10.4-fat3')
get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
- self.assertEquals(get_platform(), 'macosx-10.4-universal')
+ self.assertEqual(get_platform(), 'macosx-10.4-universal')
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
- self.assertEquals(get_platform(), 'macosx-10.4-fat64')
+ self.assertEqual(get_platform(), 'macosx-10.4-fat64')
for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
@@ -220,7 +220,7 @@ class TestSysConfig(unittest2.TestCase):
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3'%(arch,))
- self.assertEquals(get_platform(), 'macosx-10.4-%s'%(arch,))
+ self.assertEqual(get_platform(), 'macosx-10.4-%s'%(arch,))
# linux debian sarge
os.name = 'posix'
@@ -230,7 +230,7 @@ class TestSysConfig(unittest2.TestCase):
self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
'#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
- self.assertEquals(get_platform(), 'linux-i686')
+ self.assertEqual(get_platform(), 'linux-i686')
# XXX more platforms to tests here
@@ -241,11 +241,11 @@ class TestSysConfig(unittest2.TestCase):
def test_get_scheme_names(self):
wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'posix_home',
'posix_prefix', 'posix_user')
- self.assertEquals(get_scheme_names(), wanted)
+ self.assertEqual(get_scheme_names(), wanted)
def test_expand_globals(self):
- config = ConfigParser()
+ config = RawConfigParser()
config.add_section('globals')
config.set('globals', 'foo', 'ok')
config.add_section('posix')
@@ -254,15 +254,15 @@ class TestSysConfig(unittest2.TestCase):
_expand_globals(config)
- self.assertEquals(config.get('posix', 'foo'), 'ok')
- self.assertEquals(config.get('posix', 'more'), '/etc/ok')
+ self.assertEqual(config.get('posix', 'foo'), 'ok')
+ self.assertEqual(config.get('posix', 'more'), '/etc/ok')
# we might not have globals after all
# extending again (==no more globals section)
_expand_globals(config)
def test_suite():
- return unittest2.makeSuite(TestSysConfig)
+ return unittest.makeSuite(TestSysConfig)
def test_main():
run_unittest(test_suite())
diff --git a/src/distutils2/command/bdist.py b/src/distutils2/command/bdist.py
index 27f9ec3..147a31e 100644
--- a/src/distutils2/command/bdist.py
+++ b/src/distutils2/command/bdist.py
@@ -62,7 +62,7 @@ class bdist(Command):
'os2': 'zip'}
# Establish the preferred order (for the --help-formats option).
- format_commands = ['rpm', 'gztar', 'bztar', 'ztar', 'tar',
+ format_commands = ['gztar', 'bztar', 'ztar', 'tar',
'wininst', 'zip', 'msi']
# And the real information.
@@ -96,7 +96,7 @@ class bdist(Command):
# 'bdist_base' -- parent of per-built-distribution-format
# temporary directories (eg. we'll probably have
- # "build/bdist.<plat>/dumb", "build/bdist.<plat>/rpm", etc.)
+ # "build/bdist.<plat>/dumb", etc.)
if self.bdist_base is None:
build_base = self.get_finalized_command('build').build_base
self.bdist_base = os.path.join(build_base,
@@ -126,7 +126,7 @@ class bdist(Command):
# Reinitialize and run each command.
for i in range(len(self.formats)):
cmd_name = commands[i]
- sub_cmd = self.reinitialize_command(cmd_name)
+ sub_cmd = self.get_reinitialized_command(cmd_name)
# passing the owner and group names for tar archiving
if cmd_name == 'bdist_dumb':
diff --git a/src/distutils2/command/bdist_dumb.py b/src/distutils2/command/bdist_dumb.py
index 429725c..b36e7a3 100644
--- a/src/distutils2/command/bdist_dumb.py
+++ b/src/distutils2/command/bdist_dumb.py
@@ -85,7 +85,7 @@ class bdist_dumb (Command):
if not self.skip_build:
self.run_command('build')
- install = self.reinitialize_command('install', reinit_subcommands=1)
+ install = self.get_reinitialized_command('install', reinit_subcommands=1)
install.root = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = 0
diff --git a/src/distutils2/command/bdist_msi.py b/src/distutils2/command/bdist_msi.py
index 158065b..bbbcbcc 100644
--- a/src/distutils2/command/bdist_msi.py
+++ b/src/distutils2/command/bdist_msi.py
@@ -177,12 +177,12 @@ class bdist_msi (Command):
if not self.skip_build:
self.run_command('build')
- install = self.reinitialize_command('install', reinit_subcommands=1)
+ install = self.get_reinitialized_command('install', reinit_subcommands=1)
install.prefix = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = 0
- install_lib = self.reinitialize_command('install_lib')
+ install_lib = self.get_reinitialized_command('install_lib')
# we do not want to include pyc or pyo files
install_lib.compile = 0
install_lib.optimize = 0
diff --git a/src/distutils2/command/bdist_wininst.py b/src/distutils2/command/bdist_wininst.py
index 10f8bec..e0b93d1 100644
--- a/src/distutils2/command/bdist_wininst.py
+++ b/src/distutils2/command/bdist_wininst.py
@@ -126,13 +126,13 @@ class bdist_wininst (Command):
if not self.skip_build:
self.run_command('build')
- install = self.reinitialize_command('install', reinit_subcommands=1)
+ install = self.get_reinitialized_command('install', reinit_subcommands=1)
install.root = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = 0
install.plat_name = self.plat_name
- install_lib = self.reinitialize_command('install_lib')
+ install_lib = self.get_reinitialized_command('install_lib')
# we do not want to include pyc or pyo files
install_lib.compile = 0
install_lib.optimize = 0
diff --git a/src/distutils2/cmd.py b/src/distutils2/command/cmd.py
index 161fc46..e94263b 100644
--- a/src/distutils2/cmd.py
+++ b/src/distutils2/command/cmd.py
@@ -333,10 +333,8 @@ class Command:
cmd_obj.ensure_finalized()
return cmd_obj
- # XXX rename to 'get_reinitialized_command()'? (should do the
- # same in dist.py, if so)
- def reinitialize_command(self, command, reinit_subcommands=0):
- return self.distribution.reinitialize_command(
+ def get_reinitialized_command(self, command, reinit_subcommands=0):
+ return self.distribution.get_reinitialized_command(
command, reinit_subcommands)
def run_command(self, command):
diff --git a/src/distutils2/command/install_egg_info.py b/src/distutils2/command/install_egg_info.py
index 765c69f..c8b568a 100644
--- a/src/distutils2/command/install_egg_info.py
+++ b/src/distutils2/command/install_egg_info.py
@@ -4,7 +4,7 @@ Implements the Distutils 'install_egg_info' command, for installing
a package's PKG-INFO metadata."""
-from distutils2.cmd import Command
+from distutils2.command.cmd import Command
from distutils2 import log
from distutils2._backport.shutil import rmtree
import os, sys, re
diff --git a/src/distutils2/config.py b/src/distutils2/config.py
index 55b5123..30ad479 100644
--- a/src/distutils2/config.py
+++ b/src/distutils2/config.py
@@ -4,9 +4,9 @@ Provides the PyPIRCCommand class, the base class for the command classes
that uses .pypirc in the distutils.command package.
"""
import os
-from ConfigParser import ConfigParser
+from ConfigParser import RawConfigParser
-from distutils2.cmd import Command
+from distutils2.command.cmd import Command
DEFAULT_PYPIRC = """\
[distutils]
@@ -59,7 +59,7 @@ class PyPIRCCommand(Command):
if os.path.exists(rc):
self.announce('Using PyPI login from %s' % rc)
repository = self.repository or self.DEFAULT_REPOSITORY
- config = ConfigParser()
+ config = RawConfigParser()
config.read(rc)
sections = config.sections()
if 'distutils' in sections:
diff --git a/src/distutils2/core.py b/src/distutils2/core.py
index 5f948e5..d10a558 100644
--- a/src/distutils2/core.py
+++ b/src/distutils2/core.py
@@ -17,7 +17,7 @@ from distutils2.util import grok_environment_error
# Mainly import these so setup scripts can "from distutils2.core import" them.
from distutils2.dist import Distribution
-from distutils2.cmd import Command
+from distutils2.command.cmd import Command
from distutils2.config import PyPIRCCommand
from distutils2.extension import Extension
diff --git a/src/distutils2/depgraph.py b/src/distutils2/depgraph.py
index 8ab4690..75bc4d3 100644
--- a/src/distutils2/depgraph.py
+++ b/src/distutils2/depgraph.py
@@ -1,47 +1,49 @@
-"""
-A dependency graph generator. The graph is represented as an instance of
-:class:`DependencyGraph`, and DOT output is possible as well.
+"""Analyse the relationships between the distributions in the system and generate
+a dependency graph.
"""
-from distutils2._backport import pkgutil
from distutils2.errors import DistutilsError
from distutils2.version import VersionPredicate
-__all__ = ['DependencyGraph', 'generate_graph']
+__all__ = ['DependencyGraph', 'generate_graph', 'dependent_dists',
+ 'graph_to_dot']
class DependencyGraph(object):
"""
Represents a dependency graph between distributions.
- The depedency relationships are stored in an *adjacency_list* that maps
+ The dependency relationships are stored in an ``adjacency_list`` that maps
distributions to a list of ``(other, label)`` tuples where ``other``
is a distribution and the edge is labelled with ``label`` (i.e. the version
- specifier, if such was provided). If any missing depencies are found,
- they are stored in ``missing``. It maps distributions to a list of
- requirements that were not provided by any other distributions.
+ specifier, if such was provided). Also, for more efficient traversal, for
+ every distribution ``x``, a list of predecessors is kept in
+ ``reverse_list[x]``. An edge from distribution ``a`` to
+ distribution ``b`` means that ``a`` depends on ``b``. If any missing
+ depencies are found, they are stored in ``missing``, which is a dictionary
+ that maps distributions to a list of requirements that were not provided by
+ any other distributions.
"""
def __init__(self):
self.adjacency_list = {}
+ self.reverse_list = {}
self.missing = {}
def add_distribution(self, distribution):
- """
- Add distribution *x* to the graph.
+ """Add the *distribution* to the graph.
:type distribution: :class:`pkgutil.Distribution` or
:class:`pkgutil.EggInfoDistribution`
"""
self.adjacency_list[distribution] = list()
+ self.reverse_list[distribution] = list()
self.missing[distribution] = list()
def add_edge(self, x, y, label=None):
- """
- Add an edge from distribution *x* to distribution *y* with the given
+ """Add an edge from distribution *x* to distribution *y* with the given
*label*.
-
:type x: :class:`pkgutil.Distribution` or
:class:`pkgutil.EggInfoDistribution`
:type y: :class:`pkgutil.Distribution` or
@@ -49,6 +51,9 @@ class DependencyGraph(object):
:type label: ``str`` or ``None``
"""
self.adjacency_list[x].append((y, label))
+ # multiple edges are allowed, so be careful
+ if not x in self.reverse_list[y]:
+ self.reverse_list[y].append(x)
def add_missing(self, distribution, requirement):
"""
@@ -60,45 +65,42 @@ class DependencyGraph(object):
"""
self.missing[distribution].append(requirement)
- def to_dot(self, f, skip_disconnected=True):
- """
- Writes a DOT output for the graph to the provided *file*.
- If *skip_disconnected* is set to ``True``, then all distributions
- that are not dependent on any other distributions are skipped.
- :type f: ``file``
- ;type skip_disconnected: ``bool``
- """
- if not isinstance(f, file):
- raise TypeError('the argument has to be of type file')
-
- disconnected = []
-
- f.write("digraph dependencies {\n")
- for dist, adjs in self.adjacency_list.iteritems():
- if len(adjs) == 0 and not skip_disconnected:
- disconnected.append(dist)
- for (other, label) in adjs:
- if not label is None:
- f.write('"%s" -> "%s" [label="%s"]\n' %
- (dist.name, other.name, label))
- else:
- f.write('"%s" -> "%s"\n' % (dist.name, other.name))
- if not skip_disconnected and len(disconnected) > 0:
- f.write('subgraph disconnected {\n')
- f.write('label = "Disconnected"\n')
- f.write('bgcolor = red\n')
-
- for dist in disconnected:
- f.write('"%s"' % dist.name)
- f.write('\n')
- f.write('}\n')
+def graph_to_dot(graph, f, skip_disconnected=True):
+ """Writes a DOT output for the graph to the provided file *f*.
+
+ If *skip_disconnected* is set to ``True``, then all distributions
+ that are not dependent on any other distribution are skipped.
+
+ :type f: has to support ``file``-like operations
+ :type skip_disconnected: ``bool``
+ """
+ disconnected = []
+
+ f.write("digraph dependencies {\n")
+ for dist, adjs in graph.adjacency_list.iteritems():
+ if len(adjs) == 0 and not skip_disconnected:
+ disconnected.append(dist)
+ for (other, label) in adjs:
+ if not label is None:
+ f.write('"%s" -> "%s" [label="%s"]\n' %
+ (dist.name, other.name, label))
+ else:
+ f.write('"%s" -> "%s"\n' % (dist.name, other.name))
+ if not skip_disconnected and len(disconnected) > 0:
+ f.write('subgraph disconnected {\n')
+ f.write('label = "Disconnected"\n')
+ f.write('bgcolor = red\n')
+
+ for dist in disconnected:
+ f.write('"%s"' % dist.name)
+ f.write('\n')
f.write('}\n')
+ f.write('}\n')
def generate_graph(dists):
- """
- Generates a dependency graph from the given distributions.
+ """Generates a dependency graph from the given distributions.
:parameter dists: a list of distributions
:type dists: list of :class:`pkgutil.Distribution` and
@@ -115,7 +117,7 @@ def generate_graph(dists):
provides = dist.metadata['Provides-Dist'] + dist.metadata['Provides']
for p in provides:
- comps = p.split(" ", 1)
+ comps = p.strip().rsplit(" ", 1)
name = comps[0]
version = None
if len(comps) == 2:
@@ -133,22 +135,26 @@ def generate_graph(dists):
requires = dist.metadata['Requires-Dist'] + dist.metadata['Requires']
for req in requires:
predicate = VersionPredicate(req)
- comps = req.split(" ", 1)
+ comps = req.strip().rsplit(" ", 1)
name = comps[0]
if not name in provided:
graph.add_missing(dist, req)
else:
+ matched = False
for (version, provider) in provided[name]:
if predicate.match(version):
graph.add_edge(dist, provider, req)
+ matched = True
+ break
+ if not matched:
+ graph.add_missing(dist, req)
return graph
def dependent_dists(dists, dist):
- """
- Recursively generate a list of distributions from *dists* that are
+ """Recursively generate a list of distributions from *dists* that are
dependent on *dist*.
:param dists: a list of distributions
@@ -158,24 +164,26 @@ def dependent_dists(dists, dist):
raise ValueError('The given distribution is not a member of the list')
graph = generate_graph(dists)
- dep = [dist]
- fringe = [dist] # list of nodes we should expand
+ dep = [dist] # dependent distributions
+ fringe = graph.reverse_list[dist] # list of nodes we should inspect
+
while not len(fringe) == 0:
- next = graph.adjacency_list[fringe.pop()]
- for (dist, label) in next:
- if not dist in dep: # avoid infinite loops
- dep.append(dist)
- fringe.append(dist)
+ node = fringe.pop()
+ dep.append(node)
+ for prev in graph.reverse_list[node]:
+ if not prev in dep:
+ fringe.append(prev)
- dep.pop()
+ dep.pop(0) # remove dist from dep, was there to prevent infinite loops
return dep
if __name__ == '__main__':
- dists = list(pkgutil.get_distributions(use_egg_info=True))
+ from distutils2._backport.pkgutil import get_distributions
+ dists = list(get_distributions(use_egg_info=True))
graph = generate_graph(dists)
for dist, reqs in graph.missing.iteritems():
if len(reqs) > 0:
print("Missing dependencies for %s: %s" % (dist.name,
", ".join(reqs)))
f = open('output.dot', 'w')
- graph.to_dot(f, True)
+ graph_to_dot(graph, f, True)
diff --git a/src/distutils2/dist.py b/src/distutils2/dist.py
index 2b3fcad..c1088d7 100644
--- a/src/distutils2/dist.py
+++ b/src/distutils2/dist.py
@@ -13,6 +13,8 @@ try:
except ImportError:
warnings = None
+from ConfigParser import RawConfigParser
+
from distutils2.errors import (DistutilsOptionError, DistutilsArgError,
DistutilsModuleError, DistutilsClassError)
from distutils2.fancy_getopt import FancyGetopt, translate_longopt
@@ -362,14 +364,12 @@ Common commands: (see '--help-commands' for more)
return files
def parse_config_files(self, filenames=None):
- from ConfigParser import ConfigParser
-
if filenames is None:
filenames = self.find_config_files()
log.debug("Distribution.parse_config_files():")
- parser = ConfigParser()
+ parser = RawConfigParser()
for filename in filenames:
log.debug(" reading %s" % filename)
parser.read(filename)
@@ -383,7 +383,7 @@ Common commands: (see '--help-commands' for more)
opt = opt.replace('-', '_')
opt_dict[opt] = (filename, val)
- # Make the ConfigParser forget everything (so we retain
+ # Make the RawConfigParser forget everything (so we retain
# the original filenames that options come from)
parser.__init__()
@@ -493,7 +493,7 @@ Common commands: (see '--help-commands' for more)
None if the user asked for help on this command.
"""
# late import because of mutual dependence between these modules
- from distutils2.cmd import Command
+ from distutils2.command.cmd import Command
# Pull the current command from the head of the command line
command = args[0]
@@ -607,7 +607,7 @@ Common commands: (see '--help-commands' for more)
"""
# late import because of mutual dependence between these modules
from distutils2.core import gen_usage
- from distutils2.cmd import Command
+ from distutils2.command.cmd import Command
if global_options:
if display_options:
@@ -885,7 +885,7 @@ Common commands: (see '--help-commands' for more)
except ValueError, msg:
raise DistutilsOptionError, msg
- def reinitialize_command(self, command, reinit_subcommands=0):
+ def get_reinitialized_command(self, command, reinit_subcommands=0):
"""Reinitializes a command to the state it was in when first
returned by 'get_command_obj()': ie., initialized but not yet
finalized. This provides the opportunity to sneak option
@@ -904,7 +904,7 @@ Common commands: (see '--help-commands' for more)
Returns the reinitialized command object.
"""
- from distutils2.cmd import Command
+ from distutils2.command.cmd import Command
if not isinstance(command, Command):
command_name = command
command = self.get_command_obj(command_name)
@@ -920,7 +920,7 @@ Common commands: (see '--help-commands' for more)
if reinit_subcommands:
for sub in command.get_sub_commands():
- self.reinitialize_command(sub, reinit_subcommands)
+ self.get_reinitialized_command(sub, reinit_subcommands)
return command
diff --git a/src/distutils2/metadata.py b/src/distutils2/metadata.py
index 3d04ac4..74a65be 100644
--- a/src/distutils2/metadata.py
+++ b/src/distutils2/metadata.py
@@ -105,7 +105,6 @@ def _best_version(fields):
keys = fields.keys()
possible_versions = ['1.0', '1.1', '1.2']
-
# first let's try to see if a field is not part of one of the version
for key in keys:
if key not in _241_FIELDS and '1.0' in possible_versions:
@@ -128,9 +127,9 @@ def _best_version(fields):
raise MetadataConflictError('You used incompatible 1.1 and 1.2 fields')
# we have the choice, either 1.0, or 1.2
- # - 1.0 has a broken Summary field but work with all tools
+ # - 1.0 has a broken Summary field but works with all tools
# - 1.1 is to avoid
- # - 1.2 fixes Summary but is not spreaded yet
+ # - 1.2 fixes Summary but is not widespread yet
if not is_1_1 and not is_1_2:
# we couldn't find any specific marker
if PKG_INFO_PREFERRED_VERSION in possible_versions:
@@ -185,14 +184,16 @@ _UNICODEFIELDS = ('Author', 'Maintainer', 'Summary', 'Description')
class DistributionMetadata(object):
"""Distribution meta-data class (1.0 or 1.2).
"""
- def __init__(self, path=None, platform_dependant=False,
- execution_context=None):
+ def __init__(self, path=None, platform_dependent=False,
+ execution_context=None, fileobj=None):
self._fields = {}
self.version = None
self.docutils_support = _HAS_DOCUTILS
- self.platform_dependant = platform_dependant
+ self.platform_dependent = platform_dependent
if path is not None:
self.read(path)
+ elif fileobj is not None:
+ self.read_file(fileobj)
self.execution_context = execution_context
def _set_best_version(self):
@@ -261,7 +262,7 @@ class DistributionMetadata(object):
return reporter.messages
def _platform(self, value):
- if not self.platform_dependant or ';' not in value:
+ if not self.platform_dependent or ';' not in value:
return True, value
value, marker = value.split(';')
return _interpret(marker, self.execution_context), value
@@ -633,4 +634,3 @@ def _interpret(marker, execution_context=None):
operations = _CHAIN(execution_context)
tokenize(StringIO(marker).readline, operations.eat)
return operations.result()
-
diff --git a/src/distutils2/tests/__init__.py b/src/distutils2/tests/__init__.py
index c093ece..f5b4b1e 100644
--- a/src/distutils2/tests/__init__.py
+++ b/src/distutils2/tests/__init__.py
@@ -1,20 +1,25 @@
-"""Test suite for distutils.
+"""Test suite for distutils2.
This test suite consists of a collection of test modules in the
-distutils.tests package. Each test module has a name starting with
+distutils2.tests package. Each test module has a name starting with
'test' and contains a function test_suite(). The function is expected
-to return an initialized unittest2.TestSuite instance.
+to return an initialized unittest.TestSuite instance.
-Tests for the command classes in the distutils.command package are
-included in distutils.tests as well, instead of using a separate
-distutils.command.tests package, since command identification is done
+Tests for the command classes in the distutils2.command package are
+included in distutils2.tests as well, instead of using a separate
+distutils2.command.tests package, since command identification is done
by import rather than matching pre-defined names.
+Utility code is included in distutils2.tests.support. Always import
+unittest from that module, it will be the right version (standard
+library unittest for 2.7 and higher, third-party unittest2 release for
+older versions).
"""
+
import os
import sys
import warnings
-import unittest2
+from distutils2.tests.support import unittest
from test.test_support import TESTFN # use TESTFN from stdlib/test_support.
@@ -23,7 +28,7 @@ here = os.path.dirname(__file__)
verbose = 1
def test_suite():
- suite = unittest2.TestSuite()
+ suite = unittest.TestSuite()
for fn in os.listdir(here):
if fn.startswith("test") and fn.endswith(".py"):
modname = "distutils2.tests." + fn[:-3]
@@ -42,17 +47,17 @@ class TestFailed(Error):
class BasicTestRunner:
def run(self, test):
- result = unittest2.TestResult()
+ result = unittest.TestResult()
test(result)
return result
def _run_suite(suite, verbose_=1):
- """Run tests from a unittest2.TestSuite-derived class."""
+ """Run tests from a unittest.TestSuite-derived class."""
global verbose
verbose = verbose_
if verbose_:
- runner = unittest2.TextTestRunner(sys.stdout, verbosity=2)
+ runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
else:
runner = BasicTestRunner()
@@ -68,22 +73,22 @@ def _run_suite(suite, verbose_=1):
def run_unittest(classes, verbose_=1):
- """Run tests from unittest2.TestCase-derived classes.
+ """Run tests from unittest.TestCase-derived classes.
- Extracted from stdlib test.test_support and modified to support unittest2.
+ Extracted from stdlib test.test_support and modified to support unittest.
"""
- valid_types = (unittest2.TestSuite, unittest2.TestCase)
- suite = unittest2.TestSuite()
+ valid_types = (unittest.TestSuite, unittest.TestCase)
+ suite = unittest.TestSuite()
for cls in classes:
if isinstance(cls, str):
if cls in sys.modules:
- suite.addTest(unittest2.findTestCases(sys.modules[cls]))
+ suite.addTest(unittest.findTestCases(sys.modules[cls]))
else:
raise ValueError("str arguments must be keys in sys.modules")
elif isinstance(cls, valid_types):
suite.addTest(cls)
else:
- suite.addTest(unittest2.makeSuite(cls))
+ suite.addTest(unittest.makeSuite(cls))
_run_suite(suite, verbose_)
@@ -128,4 +133,4 @@ def unload(name):
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/support.py b/src/distutils2/tests/support.py
index 0681053..fd0dc2d 100644
--- a/src/distutils2/tests/support.py
+++ b/src/distutils2/tests/support.py
@@ -1,5 +1,12 @@
-"""Support code for distutils test cases."""
+"""Support code for distutils2 test cases.
+
+Always import unittest from this module, it will be the right version
+(standard library unittest for 2.7 and higher, third-party unittest2
+release for older versions).
+"""
+
import os
+import sys
import shutil
import tempfile
from copy import deepcopy
@@ -9,6 +16,13 @@ from distutils2 import log
from distutils2.log import DEBUG, INFO, WARN, ERROR, FATAL
from distutils2.core import Distribution
+if sys.version_info >= (2, 7):
+ # improved unittest package from 2.7's standard library
+ import unittest
+else:
+ # external release of same package for older versions
+ import unittest2 as unittest
+
class LoggingSilencer(object):
def setUp(self):
diff --git a/src/distutils2/tests/test_bdist.py b/src/distutils2/tests/test_bdist.py
index dccc2a5..345c74c 100644
--- a/src/distutils2/tests/test_bdist.py
+++ b/src/distutils2/tests/test_bdist.py
@@ -1,21 +1,19 @@
"""Tests for distutils.command.bdist."""
-import unittest2
import sys
import os
-import tempfile
-import shutil
from distutils2.tests import run_unittest
from distutils2.core import Distribution
from distutils2.command.bdist import bdist
from distutils2.tests import support
+from distutils2.tests.support import unittest
from distutils2.spawn import find_executable
from distutils2 import spawn
from distutils2.errors import DistutilsExecError
class BuildTestCase(support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
def test_formats(self):
@@ -25,7 +23,7 @@ class BuildTestCase(support.TempdirManager,
cmd = bdist(dist)
cmd.formats = ['msi']
cmd.ensure_finalized()
- self.assertEquals(cmd.formats, ['msi'])
+ self.assertEqual(cmd.formats, ['msi'])
# what format bdist offers ?
# XXX an explicit list in bdist is
@@ -33,12 +31,12 @@ class BuildTestCase(support.TempdirManager,
# we should add a registry
formats = ['zip', 'gztar', 'bztar', 'ztar', 'tar', 'wininst', 'msi']
formats.sort()
- founded = cmd.format_command.keys()
- founded.sort()
- self.assertEquals(founded, formats)
+ found = cmd.format_command.keys()
+ found.sort()
+ self.assertEqual(found, formats)
def test_suite():
- return unittest2.makeSuite(BuildTestCase)
+ return unittest.makeSuite(BuildTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_bdist_dumb.py b/src/distutils2/tests/test_bdist_dumb.py
index 826950e..770827c 100644
--- a/src/distutils2/tests/test_bdist_dumb.py
+++ b/src/distutils2/tests/test_bdist_dumb.py
@@ -1,6 +1,5 @@
"""Tests for distutils.command.bdist_dumb."""
-import unittest2
import sys
import os
@@ -12,6 +11,7 @@ except ImportError:
zlib = None
from distutils2.tests import run_unittest
+from distutils2.tests.support import unittest
from distutils2.core import Distribution
from distutils2.command.bdist_dumb import bdist_dumb
@@ -29,7 +29,7 @@ setup(name='foo', version='0.1', py_modules=['foo'],
class BuildDumbTestCase(support.TempdirManager,
support.LoggingSilencer,
support.EnvironGuard,
- unittest2.TestCase):
+ unittest.TestCase):
def setUp(self):
super(BuildDumbTestCase, self).setUp()
@@ -42,7 +42,7 @@ class BuildDumbTestCase(support.TempdirManager,
sys.argv[:] = self.old_sys_argv[1]
super(BuildDumbTestCase, self).tearDown()
- @unittest2.skipUnless(zlib, "requires zlib")
+ @unittest.skipUnless(zlib, "requires zlib")
def test_simple_built(self):
# let's create a simple package
@@ -78,7 +78,7 @@ class BuildDumbTestCase(support.TempdirManager,
base = base.replace(':', '-')
wanted = ['%s.zip' % base]
- self.assertEquals(dist_created, wanted)
+ self.assertEqual(dist_created, wanted)
# now let's check what we have in the zip file
# XXX to be done
@@ -87,19 +87,19 @@ class BuildDumbTestCase(support.TempdirManager,
pkg_dir, dist = self.create_dist()
os.chdir(pkg_dir)
cmd = bdist_dumb(dist)
- self.assertEquals(cmd.bdist_dir, None)
+ self.assertEqual(cmd.bdist_dir, None)
cmd.finalize_options()
# bdist_dir is initialized to bdist_base/dumb if not set
base = cmd.get_finalized_command('bdist').bdist_base
- self.assertEquals(cmd.bdist_dir, os.path.join(base, 'dumb'))
+ self.assertEqual(cmd.bdist_dir, os.path.join(base, 'dumb'))
# the format is set to a default value depending on the os.name
default = cmd.default_format[os.name]
- self.assertEquals(cmd.format, default)
+ self.assertEqual(cmd.format, default)
def test_suite():
- return unittest2.makeSuite(BuildDumbTestCase)
+ return unittest.makeSuite(BuildDumbTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_bdist_msi.py b/src/distutils2/tests/test_bdist_msi.py
index 4f23fd9..ebde4db 100644
--- a/src/distutils2/tests/test_bdist_msi.py
+++ b/src/distutils2/tests/test_bdist_msi.py
@@ -1,16 +1,16 @@
"""Tests for distutils.command.bdist_msi."""
-import unittest2
import sys
from distutils2.tests import run_unittest
from distutils2.tests import support
+from distutils2.tests.support import unittest
class BDistMSITestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
- @unittest2.skipUnless(sys.platform=="win32", "These tests are only for win32")
+ @unittest.skipUnless(sys.platform=="win32", "These tests are only for win32")
def test_minial(self):
# minimal test XXX need more tests
from distutils2.command.bdist_msi import bdist_msi
@@ -19,7 +19,7 @@ class BDistMSITestCase(support.TempdirManager,
cmd.ensure_finalized()
def test_suite():
- return unittest2.makeSuite(BDistMSITestCase)
+ return unittest.makeSuite(BDistMSITestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_bdist_wininst.py b/src/distutils2/tests/test_bdist_wininst.py
index 32db4c0..bd4f87e 100644
--- a/src/distutils2/tests/test_bdist_wininst.py
+++ b/src/distutils2/tests/test_bdist_wininst.py
@@ -1,14 +1,14 @@
"""Tests for distutils.command.bdist_wininst."""
-import unittest2
from distutils2.tests import run_unittest
from distutils2.command.bdist_wininst import bdist_wininst
from distutils2.tests import support
+from distutils2.tests.support import unittest
class BuildWinInstTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_get_exe_bytes(self):
@@ -26,7 +26,7 @@ class BuildWinInstTestCase(support.TempdirManager,
self.assertTrue(len(exe_file) > 10)
def test_suite():
- return unittest2.makeSuite(BuildWinInstTestCase)
+ return unittest.makeSuite(BuildWinInstTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_build.py b/src/distutils2/tests/test_build.py
index 0669583..abf9ef8 100644
--- a/src/distutils2/tests/test_build.py
+++ b/src/distutils2/tests/test_build.py
@@ -1,10 +1,10 @@
"""Tests for distutils.command.build."""
-import unittest2
import os
import sys
from distutils2.command.build import build
from distutils2.tests import support
+from distutils2.tests.support import unittest
try:
from sysconfig import get_platform
except ImportError:
@@ -12,7 +12,7 @@ except ImportError:
class BuildTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_finalize_options(self):
pkg_dir, dist = self.create_dist()
@@ -20,11 +20,11 @@ class BuildTestCase(support.TempdirManager,
cmd.finalize_options()
# if not specified, plat_name gets the current platform
- self.assertEquals(cmd.plat_name, get_platform())
+ self.assertEqual(cmd.plat_name, get_platform())
# build_purelib is build + lib
wanted = os.path.join(cmd.build_base, 'lib')
- self.assertEquals(cmd.build_purelib, wanted)
+ self.assertEqual(cmd.build_purelib, wanted)
# build_platlib is 'build/lib.platform-x.x[-pydebug]'
# examples:
@@ -34,24 +34,24 @@ class BuildTestCase(support.TempdirManager,
self.assertTrue(cmd.build_platlib.endswith('-pydebug'))
plat_spec += '-pydebug'
wanted = os.path.join(cmd.build_base, 'lib' + plat_spec)
- self.assertEquals(cmd.build_platlib, wanted)
+ self.assertEqual(cmd.build_platlib, wanted)
# by default, build_lib = build_purelib
- self.assertEquals(cmd.build_lib, cmd.build_purelib)
+ self.assertEqual(cmd.build_lib, cmd.build_purelib)
# build_temp is build/temp.<plat>
wanted = os.path.join(cmd.build_base, 'temp' + plat_spec)
- self.assertEquals(cmd.build_temp, wanted)
+ self.assertEqual(cmd.build_temp, wanted)
# build_scripts is build/scripts-x.x
wanted = os.path.join(cmd.build_base, 'scripts-' + sys.version[0:3])
- self.assertEquals(cmd.build_scripts, wanted)
+ self.assertEqual(cmd.build_scripts, wanted)
# executable is os.path.normpath(sys.executable)
- self.assertEquals(cmd.executable, os.path.normpath(sys.executable))
+ self.assertEqual(cmd.executable, os.path.normpath(sys.executable))
def test_suite():
- return unittest2.makeSuite(BuildTestCase)
+ return unittest.makeSuite(BuildTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_build_clib.py b/src/distutils2/tests/test_build_clib.py
index 1320c8d..48af7e1 100644
--- a/src/distutils2/tests/test_build_clib.py
+++ b/src/distutils2/tests/test_build_clib.py
@@ -1,5 +1,4 @@
"""Tests for distutils.command.build_clib."""
-import unittest2
import os
import sys
@@ -7,10 +6,11 @@ from distutils2.command.build_clib import build_clib
from distutils2.errors import DistutilsSetupError
from distutils2.tests import support
from distutils2.spawn import find_executable
+from distutils2.tests.support import unittest
class BuildCLibTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_check_library_dist(self):
pkg_dir, dist = self.create_dist()
@@ -55,14 +55,14 @@ class BuildCLibTestCase(support.TempdirManager,
self.assertRaises(DistutilsSetupError, cmd.get_source_files)
cmd.libraries = [('name', {'sources': ['a', 'b']})]
- self.assertEquals(cmd.get_source_files(), ['a', 'b'])
+ self.assertEqual(cmd.get_source_files(), ['a', 'b'])
cmd.libraries = [('name', {'sources': ('a', 'b')})]
- self.assertEquals(cmd.get_source_files(), ['a', 'b'])
+ self.assertEqual(cmd.get_source_files(), ['a', 'b'])
cmd.libraries = [('name', {'sources': ('a', 'b')}),
('name2', {'sources': ['c', 'd']})]
- self.assertEquals(cmd.get_source_files(), ['a', 'b', 'c', 'd'])
+ self.assertEqual(cmd.get_source_files(), ['a', 'b', 'c', 'd'])
def test_build_libraries(self):
@@ -91,11 +91,11 @@ class BuildCLibTestCase(support.TempdirManager,
cmd.include_dirs = 'one-dir'
cmd.finalize_options()
- self.assertEquals(cmd.include_dirs, ['one-dir'])
+ self.assertEqual(cmd.include_dirs, ['one-dir'])
cmd.include_dirs = None
cmd.finalize_options()
- self.assertEquals(cmd.include_dirs, [])
+ self.assertEqual(cmd.include_dirs, [])
cmd.distribution.libraries = 'WONTWORK'
self.assertRaises(DistutilsSetupError, cmd.finalize_options)
@@ -137,7 +137,7 @@ class BuildCLibTestCase(support.TempdirManager,
self.assertTrue('libfoo.a' in os.listdir(build_temp))
def test_suite():
- return unittest2.makeSuite(BuildCLibTestCase)
+ return unittest.makeSuite(BuildCLibTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_build_ext.py b/src/distutils2/tests/test_build_ext.py
index 12087e2..de419dd 100644
--- a/src/distutils2/tests/test_build_ext.py
+++ b/src/distutils2/tests/test_build_ext.py
@@ -1,11 +1,11 @@
import sys
import os
-import tempfile
import shutil
from StringIO import StringIO
import warnings
import distutils2.tests
+from distutils2.tests.support import unittest
from distutils2.core import Extension, Distribution
from distutils2.command.build_ext import build_ext
from distutils2.tests import support
@@ -17,7 +17,6 @@ try:
except ImportError:
from distutils2._backport import sysconfig
-import unittest2
# http://bugs.python.org/issue4373
# Don't load the xx module more than once.
@@ -29,7 +28,7 @@ def _get_source_filename():
class BuildExtTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def setUp(self):
# Create a simple test environment
# Note that we're making changes to sys.path
@@ -46,7 +45,7 @@ class BuildExtTestCase(support.TempdirManager,
build_ext.USER_BASE = site.USER_BASE
# XXX only works with 2.6 > -- dunno why yet
- @unittest2.skipUnless(sys.version_info >= (2, 6,), 'works for >= 2.6')
+ @unittest.skipUnless(sys.version_info >= (2, 6,), 'works for >= 2.6')
def test_build_ext(self):
global ALREADY_TESTED
xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
@@ -81,11 +80,11 @@ class BuildExtTestCase(support.TempdirManager,
for attr in ('error', 'foo', 'new', 'roj'):
self.assertTrue(hasattr(xx, attr))
- self.assertEquals(xx.foo(2, 5), 7)
- self.assertEquals(xx.foo(13,15), 28)
- self.assertEquals(xx.new().demo(), None)
+ self.assertEqual(xx.foo(2, 5), 7)
+ self.assertEqual(xx.foo(13,15), 28)
+ self.assertEqual(xx.new().demo(), None)
doc = 'This is a template module just for instruction.'
- self.assertEquals(xx.__doc__, doc)
+ self.assertEqual(xx.__doc__, doc)
self.assertTrue(isinstance(xx.Null(), xx.Null))
self.assertTrue(isinstance(xx.Str(), xx.Str))
@@ -195,7 +194,7 @@ class BuildExtTestCase(support.TempdirManager,
cmd = build_ext(dist)
cmd.libraries = 'my_lib'
cmd.finalize_options()
- self.assertEquals(cmd.libraries, ['my_lib'])
+ self.assertEqual(cmd.libraries, ['my_lib'])
# make sure cmd.library_dirs is turned into a list
# if it's a string
@@ -209,7 +208,7 @@ class BuildExtTestCase(support.TempdirManager,
cmd = build_ext(dist)
cmd.rpath = os.pathsep.join(['one', 'two'])
cmd.finalize_options()
- self.assertEquals(cmd.rpath, ['one', 'two'])
+ self.assertEqual(cmd.rpath, ['one', 'two'])
# XXX more tests to perform for win32
@@ -218,25 +217,25 @@ class BuildExtTestCase(support.TempdirManager,
cmd = build_ext(dist)
cmd.define = 'one,two'
cmd.finalize_options()
- self.assertEquals(cmd.define, [('one', '1'), ('two', '1')])
+ self.assertEqual(cmd.define, [('one', '1'), ('two', '1')])
# make sure undef is turned into a list of
# strings if they are ','-separated strings
cmd = build_ext(dist)
cmd.undef = 'one,two'
cmd.finalize_options()
- self.assertEquals(cmd.undef, ['one', 'two'])
+ self.assertEqual(cmd.undef, ['one', 'two'])
# make sure swig_opts is turned into a list
cmd = build_ext(dist)
cmd.swig_opts = None
cmd.finalize_options()
- self.assertEquals(cmd.swig_opts, [])
+ self.assertEqual(cmd.swig_opts, [])
cmd = build_ext(dist)
cmd.swig_opts = '1 2'
cmd.finalize_options()
- self.assertEquals(cmd.swig_opts, ['1', '2'])
+ self.assertEqual(cmd.swig_opts, ['1', '2'])
def test_check_extensions_list(self):
dist = Distribution()
@@ -272,7 +271,7 @@ class BuildExtTestCase(support.TempdirManager,
# check_extensions_list adds in ext the values passed
# when they are in ('include_dirs', 'library_dirs', 'libraries'
# 'extra_objects', 'extra_compile_args', 'extra_link_args')
- self.assertEquals(ext.libraries, 'foo')
+ self.assertEqual(ext.libraries, 'foo')
self.assertTrue(not hasattr(ext, 'some'))
# 'macros' element of build info dict must be 1- or 2-tuple
@@ -282,15 +281,15 @@ class BuildExtTestCase(support.TempdirManager,
exts[0][1]['macros'] = [('1', '2'), ('3',)]
cmd.check_extensions_list(exts)
- self.assertEquals(exts[0].undef_macros, ['3'])
- self.assertEquals(exts[0].define_macros, [('1', '2')])
+ self.assertEqual(exts[0].undef_macros, ['3'])
+ self.assertEqual(exts[0].define_macros, [('1', '2')])
def test_get_source_files(self):
modules = [Extension('foo', ['xxx'], optional=False)]
dist = Distribution({'name': 'xx', 'ext_modules': modules})
cmd = build_ext(dist)
cmd.ensure_finalized()
- self.assertEquals(cmd.get_source_files(), ['xxx'])
+ self.assertEqual(cmd.get_source_files(), ['xxx'])
def test_compiler_option(self):
# cmd.compiler is an option and
@@ -301,7 +300,7 @@ class BuildExtTestCase(support.TempdirManager,
cmd.compiler = 'unix'
cmd.ensure_finalized()
cmd.run()
- self.assertEquals(cmd.compiler, 'unix')
+ self.assertEqual(cmd.compiler, 'unix')
def test_get_outputs(self):
tmp_dir = self.mkdtemp()
@@ -312,7 +311,7 @@ class BuildExtTestCase(support.TempdirManager,
'ext_modules': [ext]})
cmd = build_ext(dist)
cmd.ensure_finalized()
- self.assertEquals(len(cmd.get_outputs()), 1)
+ self.assertEqual(len(cmd.get_outputs()), 1)
if os.name == "nt":
cmd.debug = sys.executable.endswith("_d.exe")
@@ -332,19 +331,19 @@ class BuildExtTestCase(support.TempdirManager,
finally:
os.chdir(old_wd)
self.assertTrue(os.path.exists(so_file))
- self.assertEquals(os.path.splitext(so_file)[-1],
+ self.assertEqual(os.path.splitext(so_file)[-1],
sysconfig.get_config_var('SO'))
so_dir = os.path.dirname(so_file)
- self.assertEquals(so_dir, other_tmp_dir)
+ self.assertEqual(so_dir, other_tmp_dir)
cmd.inplace = 0
cmd.run()
so_file = cmd.get_outputs()[0]
self.assertTrue(os.path.exists(so_file))
- self.assertEquals(os.path.splitext(so_file)[-1],
+ self.assertEqual(os.path.splitext(so_file)[-1],
sysconfig.get_config_var('SO'))
so_dir = os.path.dirname(so_file)
- self.assertEquals(so_dir, cmd.build_lib)
+ self.assertEqual(so_dir, cmd.build_lib)
# inplace = 0, cmd.package = 'bar'
build_py = cmd.get_finalized_command('build_py')
@@ -352,7 +351,7 @@ class BuildExtTestCase(support.TempdirManager,
path = cmd.get_ext_fullpath('foo')
# checking that the last directory is the build_dir
path = os.path.split(path)[0]
- self.assertEquals(path, cmd.build_lib)
+ self.assertEqual(path, cmd.build_lib)
# inplace = 1, cmd.package = 'bar'
cmd.inplace = 1
@@ -366,7 +365,7 @@ class BuildExtTestCase(support.TempdirManager,
# checking that the last directory is bar
path = os.path.split(path)[0]
lastdir = os.path.split(path)[-1]
- self.assertEquals(lastdir, 'bar')
+ self.assertEqual(lastdir, 'bar')
def test_ext_fullpath(self):
ext = sysconfig.get_config_vars()['SO']
@@ -382,14 +381,14 @@ class BuildExtTestCase(support.TempdirManager,
curdir = os.getcwd()
wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
path = cmd.get_ext_fullpath('lxml.etree')
- self.assertEquals(wanted, path)
+ self.assertEqual(wanted, path)
# building lxml.etree not inplace
cmd.inplace = 0
cmd.build_lib = os.path.join(curdir, 'tmpdir')
wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
path = cmd.get_ext_fullpath('lxml.etree')
- self.assertEquals(wanted, path)
+ self.assertEqual(wanted, path)
# building twisted.runner.portmap not inplace
build_py = cmd.get_finalized_command('build_py')
@@ -398,13 +397,13 @@ class BuildExtTestCase(support.TempdirManager,
path = cmd.get_ext_fullpath('twisted.runner.portmap')
wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
'portmap' + ext)
- self.assertEquals(wanted, path)
+ self.assertEqual(wanted, path)
# building twisted.runner.portmap inplace
cmd.inplace = 1
path = cmd.get_ext_fullpath('twisted.runner.portmap')
wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
- self.assertEquals(wanted, path)
+ self.assertEqual(wanted, path)
def test_suite():
src = _get_source_filename()
@@ -412,8 +411,8 @@ def test_suite():
if distutils2.tests.verbose:
print ('test_build_ext: Cannot find source code (test'
' must run in python build dir)')
- return unittest2.TestSuite()
- else: return unittest2.makeSuite(BuildExtTestCase)
+ return unittest.TestSuite()
+ else: return unittest.makeSuite(BuildExtTestCase)
if __name__ == '__main__':
distsutils2.tests.run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_build_py.py b/src/distutils2/tests/test_build_py.py
index ecc0069..7f7e1ec 100644
--- a/src/distutils2/tests/test_build_py.py
+++ b/src/distutils2/tests/test_build_py.py
@@ -3,18 +3,18 @@
import os
import sys
import StringIO
-import unittest2
from distutils2.command.build_py import build_py
from distutils2.core import Distribution
from distutils2.errors import DistutilsFileError
from distutils2.tests import support
+from distutils2.tests.support import unittest
class BuildPyTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_package_data(self):
sources = self.mkdtemp()
@@ -90,7 +90,7 @@ class BuildPyTestCase(support.TempdirManager,
os.chdir(cwd)
sys.stdout = old_stdout
- @unittest2.skipUnless(hasattr(sys, 'dont_write_bytecode'),
+ @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'),
'dont_write_bytecode support')
def test_dont_write_bytecode(self):
# makes sure byte_compile is not used
@@ -109,7 +109,7 @@ class BuildPyTestCase(support.TempdirManager,
self.assertTrue('byte-compiling is disabled' in self.logs[0][1])
def test_suite():
- return unittest2.makeSuite(BuildPyTestCase)
+ return unittest.makeSuite(BuildPyTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_build_scripts.py b/src/distutils2/tests/test_build_scripts.py
index 63ccdcc..2167ac1 100644
--- a/src/distutils2/tests/test_build_scripts.py
+++ b/src/distutils2/tests/test_build_scripts.py
@@ -1,7 +1,6 @@
"""Tests for distutils.command.build_scripts."""
import os
-import unittest2
from distutils2.command.build_scripts import build_scripts
from distutils2.core import Distribution
@@ -11,11 +10,12 @@ except ImportError:
from distutils2._backport import sysconfig
from distutils2.tests import support
+from distutils2.tests.support import unittest
class BuildScriptsTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_default_settings(self):
cmd = self.get_build_scripts_cmd("/foo/bar", [])
@@ -106,7 +106,7 @@ class BuildScriptsTestCase(support.TempdirManager,
self.assertTrue(name in built)
def test_suite():
- return unittest2.makeSuite(BuildScriptsTestCase)
+ return unittest.makeSuite(BuildScriptsTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_ccompiler.py b/src/distutils2/tests/test_ccompiler.py
index 1f3d25d..df25253 100644
--- a/src/distutils2/tests/test_ccompiler.py
+++ b/src/distutils2/tests/test_ccompiler.py
@@ -1,11 +1,11 @@
"""Tests for distutils.ccompiler."""
import os
-import unittest2
from distutils2.tests import captured_stdout
from distutils2.compiler.ccompiler import (gen_lib_options, CCompiler,
get_default_compiler, customize_compiler)
from distutils2.tests import support
+from distutils2.tests.support import unittest
class FakeCompiler(object):
def library_dir_option(self, dir):
@@ -20,7 +20,7 @@ class FakeCompiler(object):
def library_option(self, lib):
return "-l" + lib
-class CCompilerTestCase(support.EnvironGuard, unittest2.TestCase):
+class CCompilerTestCase(support.EnvironGuard, unittest.TestCase):
def test_gen_lib_options(self):
compiler = FakeCompiler()
@@ -31,7 +31,7 @@ class CCompilerTestCase(support.EnvironGuard, unittest2.TestCase):
opts = gen_lib_options(compiler, libdirs, runlibdirs, libs)
wanted = ['-Llib1', '-Llib2', '-cool', '-Rrunlib1', 'found',
'-lname2']
- self.assertEquals(opts, wanted)
+ self.assertEqual(opts, wanted)
def test_customize_compiler(self):
@@ -51,10 +51,10 @@ class CCompilerTestCase(support.EnvironGuard, unittest2.TestCase):
comp = compiler()
customize_compiler(comp)
- self.assertEquals(comp.exes['archiver'], 'my_ar -arflags')
+ self.assertEqual(comp.exes['archiver'], 'my_ar -arflags')
def test_suite():
- return unittest2.makeSuite(CCompilerTestCase)
+ return unittest.makeSuite(CCompilerTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_check.py b/src/distutils2/tests/test_check.py
index 45f5d21..7a672e1 100644
--- a/src/distutils2/tests/test_check.py
+++ b/src/distutils2/tests/test_check.py
@@ -1,14 +1,14 @@
"""Tests for distutils.command.check."""
-import unittest2
from distutils2.command.check import check
from distutils2.metadata import _HAS_DOCUTILS
from distutils2.tests import support
+from distutils2.tests.support import unittest
from distutils2.errors import DistutilsSetupError
class CheckTestCase(support.LoggingSilencer,
support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
def _run(self, metadata=None, **options):
if metadata is None:
@@ -27,7 +27,7 @@ class CheckTestCase(support.LoggingSilencer,
# by default, check is checking the metadata
# should have some warnings
cmd = self._run()
- self.assert_(len(cmd._warnings) > 0)
+ self.assertTrue(len(cmd._warnings) > 0)
# now let's add the required fields
# and run it again, to make sure we don't get
@@ -37,7 +37,7 @@ class CheckTestCase(support.LoggingSilencer,
'name': 'xxx', 'version': 'xxx'
}
cmd = self._run(metadata)
- self.assertEquals(len(cmd._warnings), 0)
+ self.assertEqual(len(cmd._warnings), 0)
# now with the strict mode, we should
# get an error if there are missing metadata
@@ -45,7 +45,7 @@ class CheckTestCase(support.LoggingSilencer,
# and of course, no error when all metadata are present
cmd = self._run(metadata, strict=1)
- self.assertEquals(len(cmd._warnings), 0)
+ self.assertEqual(len(cmd._warnings), 0)
def test_check_restructuredtext(self):
if not _HAS_DOCUTILS: # won't test without docutils
@@ -55,7 +55,7 @@ class CheckTestCase(support.LoggingSilencer,
pkg_info, dist = self.create_dist(description=broken_rest)
cmd = check(dist)
cmd.check_restructuredtext()
- self.assertEquals(len(cmd._warnings), 1)
+ self.assertEqual(len(cmd._warnings), 1)
# let's see if we have an error with strict=1
metadata = {'home_page': 'xxx', 'author': 'xxx',
@@ -69,7 +69,7 @@ class CheckTestCase(support.LoggingSilencer,
# and non-broken rest
metadata['description'] = 'title\n=====\n\ntest'
cmd = self._run(metadata, strict=1, restructuredtext=1)
- self.assertEquals(len(cmd._warnings), 0)
+ self.assertEqual(len(cmd._warnings), 0)
def test_check_all(self):
@@ -79,7 +79,7 @@ class CheckTestCase(support.LoggingSilencer,
'restructuredtext': 1})
def test_suite():
- return unittest2.makeSuite(CheckTestCase)
+ return unittest.makeSuite(CheckTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_clean.py b/src/distutils2/tests/test_clean.py
index 641e70b..dacf20a 100755
--- a/src/distutils2/tests/test_clean.py
+++ b/src/distutils2/tests/test_clean.py
@@ -1,15 +1,15 @@
"""Tests for distutils.command.clean."""
import sys
import os
-import unittest2
import getpass
from distutils2.command.clean import clean
from distutils2.tests import support
+from distutils2.tests.support import unittest
class cleanTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_simple_run(self):
pkg_dir, dist = self.create_dist()
@@ -44,7 +44,7 @@ class cleanTestCase(support.TempdirManager,
cmd.run()
def test_suite():
- return unittest2.makeSuite(cleanTestCase)
+ return unittest.makeSuite(cleanTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_cmd.py b/src/distutils2/tests/test_cmd.py
index e0e3241..aa4a709 100644
--- a/src/distutils2/tests/test_cmd.py
+++ b/src/distutils2/tests/test_cmd.py
@@ -1,17 +1,17 @@
"""Tests for distutils.cmd."""
-import unittest2
import os
from distutils2.tests import captured_stdout, run_unittest
-from distutils2.cmd import Command
+from distutils2.command.cmd import Command
from distutils2.dist import Distribution
from distutils2.errors import DistutilsOptionError
+from distutils2.tests.support import unittest
class MyCmd(Command):
def initialize_options(self):
pass
-class CommandTestCase(unittest2.TestCase):
+class CommandTestCase(unittest.TestCase):
def setUp(self):
dist = Distribution()
@@ -43,7 +43,7 @@ class CommandTestCase(unittest2.TestCase):
# making sure execute gets called properly
def _execute(func, args, exec_msg, level):
- self.assertEquals(exec_msg, 'generating out from in')
+ self.assertEqual(exec_msg, 'generating out from in')
cmd.force = True
cmd.execute = _execute
cmd.make_file(infiles='in', outfile='out', func='func', args=())
@@ -62,7 +62,7 @@ class CommandTestCase(unittest2.TestCase):
wanted = ["command options for 'MyCmd':", ' option1 = 1',
' option2 = 1']
- self.assertEquals(msgs, wanted)
+ self.assertEqual(msgs, wanted)
def test_ensure_string(self):
cmd = self.cmd
@@ -80,7 +80,7 @@ class CommandTestCase(unittest2.TestCase):
cmd = self.cmd
cmd.option1 = 'ok,dok'
cmd.ensure_string_list('option1')
- self.assertEquals(cmd.option1, ['ok', 'dok'])
+ self.assertEqual(cmd.option1, ['ok', 'dok'])
cmd.option2 = ['xxx', 'www']
cmd.ensure_string_list('option2')
@@ -104,7 +104,7 @@ class CommandTestCase(unittest2.TestCase):
self.assertRaises(DistutilsOptionError, cmd.ensure_dirname, 'option2')
def test_suite():
- return unittest2.makeSuite(CommandTestCase)
+ return unittest.makeSuite(CommandTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_config.py b/src/distutils2/tests/test_config.py
index 25b48b0..09b6d02 100644
--- a/src/distutils2/tests/test_config.py
+++ b/src/distutils2/tests/test_config.py
@@ -1,8 +1,6 @@
"""Tests for distutils.pypirc.pypirc."""
import sys
import os
-import unittest2
-import tempfile
import shutil
from distutils2.core import PyPIRCCommand
@@ -11,6 +9,7 @@ from distutils2.log import set_threshold
from distutils2.log import WARN
from distutils2.tests import support
+from distutils2.tests.support import unittest
PYPIRC = """\
[distutils]
@@ -50,7 +49,7 @@ password:xxx
class PyPIRCCommandTestCase(support.TempdirManager,
support.LoggingSilencer,
support.EnvironGuard,
- unittest2.TestCase):
+ unittest.TestCase):
def setUp(self):
"""Patches the environment."""
@@ -87,20 +86,20 @@ class PyPIRCCommandTestCase(support.TempdirManager,
config = config.items()
config.sort()
- waited = [('password', 'secret'), ('realm', 'pypi'),
- ('repository', 'http://pypi.python.org/pypi'),
- ('server', 'server1'), ('username', 'me')]
- self.assertEquals(config, waited)
+ expected = [('password', 'secret'), ('realm', 'pypi'),
+ ('repository', 'http://pypi.python.org/pypi'),
+ ('server', 'server1'), ('username', 'me')]
+ self.assertEqual(config, expected)
# old format
self.write_file(self.rc, PYPIRC_OLD)
config = cmd._read_pypirc()
config = config.items()
config.sort()
- waited = [('password', 'secret'), ('realm', 'pypi'),
- ('repository', 'http://pypi.python.org/pypi'),
- ('server', 'server-login'), ('username', 'tarek')]
- self.assertEquals(config, waited)
+ expected = [('password', 'secret'), ('realm', 'pypi'),
+ ('repository', 'http://pypi.python.org/pypi'),
+ ('server', 'server-login'), ('username', 'tarek')]
+ self.assertEqual(config, expected)
def test_server_empty_registration(self):
cmd = self._cmd(self.dist)
@@ -109,10 +108,10 @@ class PyPIRCCommandTestCase(support.TempdirManager,
cmd._store_pypirc('tarek', 'xxx')
self.assertTrue(os.path.exists(rc))
content = open(rc).read()
- self.assertEquals(content, WANTED)
+ self.assertEqual(content, WANTED)
def test_suite():
- return unittest2.makeSuite(PyPIRCCommandTestCase)
+ return unittest.makeSuite(PyPIRCCommandTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_config_cmd.py b/src/distutils2/tests/test_config_cmd.py
index 51a816e..1995b0c 100644
--- a/src/distutils2/tests/test_config_cmd.py
+++ b/src/distutils2/tests/test_config_cmd.py
@@ -1,15 +1,15 @@
"""Tests for distutils.command.config."""
-import unittest2
import os
import sys
from distutils2.command.config import dump_file, config
from distutils2.tests import support
+from distutils2.tests.support import unittest
from distutils2 import log
class ConfigTestCase(support.LoggingSilencer,
support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
def _info(self, msg, *args):
for line in msg.splitlines():
@@ -34,7 +34,7 @@ class ConfigTestCase(support.LoggingSilencer,
f.close()
dump_file(this_file, 'I am the header')
- self.assertEquals(len(self._logs), numlines+1)
+ self.assertEqual(len(self._logs), numlines+1)
def test_search_cpp(self):
if sys.platform == 'win32':
@@ -44,10 +44,10 @@ class ConfigTestCase(support.LoggingSilencer,
# simple pattern searches
match = cmd.search_cpp(pattern='xxx', body='// xxx')
- self.assertEquals(match, 0)
+ self.assertEqual(match, 0)
match = cmd.search_cpp(pattern='_configtest', body='// xxx')
- self.assertEquals(match, 1)
+ self.assertEqual(match, 1)
def test_finalize_options(self):
# finalize_options does a bit of transformation
@@ -59,9 +59,9 @@ class ConfigTestCase(support.LoggingSilencer,
cmd.library_dirs = 'three%sfour' % os.pathsep
cmd.ensure_finalized()
- self.assertEquals(cmd.include_dirs, ['one', 'two'])
- self.assertEquals(cmd.libraries, ['one'])
- self.assertEquals(cmd.library_dirs, ['three', 'four'])
+ self.assertEqual(cmd.include_dirs, ['one', 'two'])
+ self.assertEqual(cmd.libraries, ['one'])
+ self.assertEqual(cmd.library_dirs, ['three', 'four'])
def test_clean(self):
# _clean removes files
@@ -83,7 +83,7 @@ class ConfigTestCase(support.LoggingSilencer,
self.assertTrue(not os.path.exists(f))
def test_suite():
- return unittest2.makeSuite(ConfigTestCase)
+ return unittest.makeSuite(ConfigTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_converter.py b/src/distutils2/tests/test_converter.py
index 23cd475..f0717cc 100644
--- a/src/distutils2/tests/test_converter.py
+++ b/src/distutils2/tests/test_converter.py
@@ -1,8 +1,8 @@
"""Tests for distutils.converter."""
import os
import sys
-import unittest2
from distutils2.converter import DistutilsRefactoringTool
+from distutils2.tests.support import unittest
_CURDIR = os.path.dirname(__file__)
@@ -15,9 +15,9 @@ def _read_file(path):
f.close()
-class ConverterTestCase(unittest2.TestCase):
+class ConverterTestCase(unittest.TestCase):
- @unittest2.skipUnless(not sys.version < '2.6', 'Needs Python >=2.6')
+ @unittest.skipUnless(not sys.version < '2.6', 'Needs Python >=2.6')
def test_conversions(self):
# for all XX_before in the conversions/ dir
# we run the refactoring tool
@@ -30,10 +30,10 @@ class ConverterTestCase(unittest2.TestCase):
wanted = file_.replace('before', 'after')
wanted = _read_file(os.path.join(convdir, wanted))
res = ref.refactor_string(original, 'setup.py')
- self.assertEquals(str(res), wanted)
+ self.assertEqual(str(res), wanted)
def test_suite():
- return unittest2.makeSuite(ConverterTestCase)
+ return unittest.makeSuite(ConverterTestCase)
if __name__ == '__main__':
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_core.py b/src/distutils2/tests/test_core.py
index 6b062f3..9f4ad27 100644
--- a/src/distutils2/tests/test_core.py
+++ b/src/distutils2/tests/test_core.py
@@ -6,8 +6,8 @@ import os
import shutil
import sys
from distutils2.tests import captured_stdout
-import unittest2
from distutils2.tests import support
+from distutils2.tests.support import unittest
# setup script that uses __file__
setup_using___file__ = """\
@@ -28,7 +28,7 @@ setup()
"""
-class CoreTestCase(support.EnvironGuard, unittest2.TestCase):
+class CoreTestCase(support.EnvironGuard, unittest.TestCase):
def setUp(self):
super(CoreTestCase, self).setUp()
@@ -92,7 +92,7 @@ class CoreTestCase(support.EnvironGuard, unittest2.TestCase):
self.assertEqual(cwd, output)
def test_suite():
- return unittest2.makeSuite(CoreTestCase)
+ return unittest.makeSuite(CoreTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_cygwinccompiler.py b/src/distutils2/tests/test_cygwinccompiler.py
index 2ecbbc9..e16a309 100644
--- a/src/distutils2/tests/test_cygwinccompiler.py
+++ b/src/distutils2/tests/test_cygwinccompiler.py
@@ -1,5 +1,4 @@
"""Tests for distutils.cygwinccompiler."""
-import unittest2
import sys
import os
import warnings
@@ -18,9 +17,10 @@ from distutils2.compiler.cygwinccompiler import (CygwinCCompiler, check_config_h
get_msvcr, RE_VERSION)
from distutils2.util import get_compiler_versions
from distutils2.tests import support
+from distutils2.tests.support import unittest
class CygwinCCompilerTestCase(support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
def setUp(self):
super(CygwinCCompilerTestCase, self).setUp()
@@ -44,48 +44,48 @@ class CygwinCCompilerTestCase(support.TempdirManager,
sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) \n[GCC '
'4.0.1 (Apple Computer, Inc. build 5370)]')
- self.assertEquals(check_config_h()[0], CONFIG_H_OK)
+ self.assertEqual(check_config_h()[0], CONFIG_H_OK)
# then it tries to see if it can find "__GNUC__" in pyconfig.h
sys.version = 'something without the *CC word'
# if the file doesn't exist it returns CONFIG_H_UNCERTAIN
- self.assertEquals(check_config_h()[0], CONFIG_H_UNCERTAIN)
+ self.assertEqual(check_config_h()[0], CONFIG_H_UNCERTAIN)
# if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK
self.write_file(self.python_h, 'xxx')
- self.assertEquals(check_config_h()[0], CONFIG_H_NOTOK)
+ self.assertEqual(check_config_h()[0], CONFIG_H_NOTOK)
# and CONFIG_H_OK if __GNUC__ is found
self.write_file(self.python_h, 'xxx __GNUC__ xxx')
- self.assertEquals(check_config_h()[0], CONFIG_H_OK)
+ self.assertEqual(check_config_h()[0], CONFIG_H_OK)
def test_get_msvcr(self):
# none
sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) '
'\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]')
- self.assertEquals(get_msvcr(), None)
+ self.assertEqual(get_msvcr(), None)
# MSVC 7.0
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1300 32 bits (Intel)]')
- self.assertEquals(get_msvcr(), ['msvcr70'])
+ self.assertEqual(get_msvcr(), ['msvcr70'])
# MSVC 7.1
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1310 32 bits (Intel)]')
- self.assertEquals(get_msvcr(), ['msvcr71'])
+ self.assertEqual(get_msvcr(), ['msvcr71'])
# VS2005 / MSVC 8.0
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1400 32 bits (Intel)]')
- self.assertEquals(get_msvcr(), ['msvcr80'])
+ self.assertEqual(get_msvcr(), ['msvcr80'])
# VS2008 / MSVC 9.0
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1500 32 bits (Intel)]')
- self.assertEquals(get_msvcr(), ['msvcr90'])
+ self.assertEqual(get_msvcr(), ['msvcr90'])
# unknown
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
@@ -94,7 +94,7 @@ class CygwinCCompilerTestCase(support.TempdirManager,
def test_suite():
- return unittest2.makeSuite(CygwinCCompilerTestCase)
+ return unittest.makeSuite(CygwinCCompilerTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_depgraph.py b/src/distutils2/tests/test_depgraph.py
new file mode 100644
index 0000000..8bc8111
--- /dev/null
+++ b/src/distutils2/tests/test_depgraph.py
@@ -0,0 +1,187 @@
+"""Tests for distutils.depgraph """
+
+from distutils2.tests import support
+from distutils2.tests.support import unittest
+from distutils2 import depgraph
+from distutils2._backport import pkgutil
+
+import os
+import sys
+import re
+try:
+ import cStringIO as StringIO
+except ImportErorr:
+ import StringIO
+
+class DepGraphTestCase(support.LoggingSilencer,
+ unittest.TestCase):
+
+ DISTROS_DIST = ('choxie', 'grammar', 'towel-stuff')
+ DISTROS_EGG = ('bacon', 'banana', 'strawberry', 'cheese')
+ EDGE = re.compile(
+ r'"(?P<from>.*)" -> "(?P<to>.*)" \[label="(?P<label>.*)"\]'
+ )
+
+ def checkLists(self, l1, l2):
+ """ Compare two lists without taking the order into consideration """
+ self.assertListEqual(sorted(l1), sorted(l2))
+
+ def setUp(self):
+ super(unittest.TestCase, self).setUp()
+ path = os.path.join(os.path.dirname(__file__), '..', '_backport',
+ 'tests', 'fake_dists')
+ path = os.path.abspath(path)
+ self.sys_path = sys.path[:]
+ sys.path[0:0] = [path]
+
+ def test_generate_graph(self):
+ dists = []
+ for name in self.DISTROS_DIST:
+ dist = pkgutil.get_distribution(name)
+ self.assertNotEqual(dist, None)
+ dists.append(dist)
+
+ choxie, grammar, towel = dists
+
+ graph = depgraph.generate_graph(dists)
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[choxie]]
+ self.checkLists([('towel-stuff', 'towel-stuff (0.1)')], deps)
+ self.assertTrue(choxie in graph.reverse_list[towel])
+ self.checkLists(graph.missing[choxie], [])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[grammar]]
+ self.checkLists([], deps)
+ self.checkLists(graph.missing[grammar], ['truffles (>=1.2)'])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[towel]]
+ self.checkLists([], deps)
+ self.checkLists(graph.missing[towel], ['bacon (<=0.2)'])
+
+ def test_generate_graph_egg(self):
+ dists = []
+ for name in self.DISTROS_DIST + self.DISTROS_EGG:
+ dist = pkgutil.get_distribution(name, use_egg_info=True)
+ self.assertNotEqual(dist, None)
+ dists.append(dist)
+
+ choxie, grammar, towel, bacon, banana, strawberry, cheese = dists
+
+ graph = depgraph.generate_graph(dists)
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[choxie]]
+ self.checkLists([('towel-stuff', 'towel-stuff (0.1)')], deps)
+ self.assertTrue(choxie in graph.reverse_list[towel])
+ self.checkLists(graph.missing[choxie], [])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[grammar]]
+ self.checkLists([('bacon', 'truffles (>=1.2)')], deps)
+ self.checkLists(graph.missing[grammar], [])
+ self.assertTrue(grammar in graph.reverse_list[bacon])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[towel]]
+ self.checkLists([('bacon', 'bacon (<=0.2)')], deps)
+ self.checkLists(graph.missing[towel], [])
+ self.assertTrue(towel in graph.reverse_list[bacon])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[bacon]]
+ self.checkLists([], deps)
+ self.checkLists(graph.missing[bacon], [])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[banana]]
+ self.checkLists([('strawberry', 'strawberry (>=0.5)')], deps)
+ self.checkLists(graph.missing[banana], [])
+ self.assertTrue(banana in graph.reverse_list[strawberry])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[strawberry]]
+ self.checkLists([], deps)
+ self.checkLists(graph.missing[strawberry], [])
+
+ deps = [(x.name, y) for (x,y) in graph.adjacency_list[cheese]]
+ self.checkLists([], deps)
+ self.checkLists(graph.missing[cheese], [])
+
+ def test_dependent_dists(self):
+ dists = []
+ for name in self.DISTROS_DIST:
+ dist = pkgutil.get_distribution(name)
+ self.assertNotEqual(dist, None)
+ dists.append(dist)
+
+ choxie, grammar, towel = dists
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, choxie)]
+ self.checkLists([], deps)
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, grammar)]
+ self.checkLists([], deps)
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, towel)]
+ self.checkLists(['choxie'], deps)
+
+
+ def test_dependent_dists_egg(self):
+ dists = []
+ for name in self.DISTROS_DIST + self.DISTROS_EGG:
+ dist = pkgutil.get_distribution(name, use_egg_info=True)
+ self.assertNotEqual(dist, None)
+ dists.append(dist)
+
+ choxie, grammar, towel, bacon, banana, strawberry, cheese = dists
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, choxie)]
+ self.checkLists([], deps)
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, grammar)]
+ self.checkLists([], deps)
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, towel)]
+ self.checkLists(['choxie'], deps)
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, bacon)]
+ self.checkLists(['choxie', 'towel-stuff', 'grammar'], deps)
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, strawberry)]
+ self.checkLists(['banana'], deps)
+
+ deps = [d.name for d in depgraph.dependent_dists(dists, cheese)]
+ self.checkLists([], deps)
+
+ def test_graph_to_dot(self):
+ expected = (
+ ('towel-stuff', 'bacon', 'bacon (<=0.2)'),
+ ('grammar', 'bacon', 'truffles (>=1.2)'),
+ ('choxie', 'towel-stuff', 'towel-stuff (0.1)'),
+ ('banana', 'strawberry', 'strawberry (>=0.5)')
+ )
+
+ dists = []
+ for name in self.DISTROS_DIST + self.DISTROS_EGG:
+ dist = pkgutil.get_distribution(name, use_egg_info=True)
+ self.assertNotEqual(dist, None)
+ dists.append(dist)
+
+ graph = depgraph.generate_graph(dists)
+ buf = StringIO.StringIO()
+ depgraph.graph_to_dot(graph, buf)
+ buf.seek(0)
+ matches = []
+ lines = buf.readlines()
+ for line in lines[1:-1]: # skip the first and the last lines
+ if line[-1] == '\n':
+ line = line[:-1]
+ match = self.EDGE.match(line.strip())
+ self.assertTrue(match is not None)
+ matches.append(match.groups())
+
+ self.checkLists(matches, expected)
+
+ def tearDown(self):
+ super(unittest.TestCase, self).tearDown()
+ sys.path = self.sys_path
+
+def test_suite():
+ return unittest.makeSuite(DepGraphTestCase)
+
+if __name__ == "__main__":
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_dist.py b/src/distutils2/tests/test_dist.py
index 89efcdc..b52d1cb 100644
--- a/src/distutils2/tests/test_dist.py
+++ b/src/distutils2/tests/test_dist.py
@@ -4,15 +4,15 @@
import os
import StringIO
import sys
-import unittest2
import warnings
import textwrap
from distutils2.dist import Distribution, fix_help_options, DistributionMetadata
-from distutils2.cmd import Command
+from distutils2.command.cmd import Command
import distutils2.dist
from distutils2.tests import TESTFN, captured_stdout
from distutils2.tests import support
+from distutils2.tests.support import unittest
class test_dist(Command):
"""Sample distutils2 extension command."""
@@ -40,7 +40,7 @@ class TestDistribution(Distribution):
class DistributionTestCase(support.TempdirManager,
support.LoggingSilencer,
support.EnvironGuard,
- unittest2.TestCase):
+ unittest.TestCase):
def setUp(self):
super(DistributionTestCase, self).setUp()
@@ -71,11 +71,11 @@ class DistributionTestCase(support.TempdirManager,
sys.argv.append("build")
__, stdout = captured_stdout(self.create_distribution, files)
- self.assertEquals(stdout, '')
+ self.assertEqual(stdout, '')
distutils2.dist.DEBUG = True
try:
__, stdout = captured_stdout(self.create_distribution, files)
- self.assertEquals(stdout, '')
+ self.assertEqual(stdout, '')
finally:
distutils2.dist.DEBUG = False
@@ -174,7 +174,7 @@ class DistributionTestCase(support.TempdirManager,
finally:
warnings.warn = old_warn
- self.assertEquals(len(warns), 0)
+ self.assertEqual(len(warns), 0)
def test_finalize_options(self):
@@ -185,20 +185,20 @@ class DistributionTestCase(support.TempdirManager,
dist.finalize_options()
# finalize_option splits platforms and keywords
- self.assertEquals(dist.metadata['platform'], ['one', 'two'])
- self.assertEquals(dist.metadata['keywords'], ['one', 'two'])
+ self.assertEqual(dist.metadata['platform'], ['one', 'two'])
+ self.assertEqual(dist.metadata['keywords'], ['one', 'two'])
def test_get_command_packages(self):
dist = Distribution()
- self.assertEquals(dist.command_packages, None)
+ self.assertEqual(dist.command_packages, None)
cmds = dist.get_command_packages()
- self.assertEquals(cmds, ['distutils2.command'])
- self.assertEquals(dist.command_packages,
+ self.assertEqual(cmds, ['distutils2.command'])
+ self.assertEqual(dist.command_packages,
['distutils2.command'])
dist.command_packages = 'one,two'
cmds = dist.get_command_packages()
- self.assertEquals(cmds, ['distutils2.command', 'one', 'two'])
+ self.assertEqual(cmds, ['distutils2.command', 'one', 'two'])
def test_announce(self):
@@ -238,11 +238,11 @@ class DistributionTestCase(support.TempdirManager,
os.path.expanduser = old_expander
# make sure --no-user-cfg disables the user cfg file
- self.assertEquals(len(all_files)-1, len(files))
+ self.assertEqual(len(all_files)-1, len(files))
class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
- unittest2.TestCase):
+ unittest.TestCase):
def setUp(self):
super(MetadataTestCase, self).setUp()
@@ -365,8 +365,8 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
def test_fix_help_options(self):
help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
fancy_options = fix_help_options(help_tuples)
- self.assertEquals(fancy_options[0], ('a', 'b', 'c'))
- self.assertEquals(fancy_options[1], (1, 2, 3))
+ self.assertEqual(fancy_options[0], ('a', 'b', 'c'))
+ self.assertEqual(fancy_options[1], (1, 2, 3))
def test_show_help(self):
# smoke test, just makes sure some help is displayed
@@ -412,20 +412,20 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
PKG_INFO.seek(0)
metadata.read_file(PKG_INFO)
- self.assertEquals(metadata['name'], "package")
- self.assertEquals(metadata['version'], "1.0")
- self.assertEquals(metadata['summary'], "xxx")
- self.assertEquals(metadata['download_url'], 'http://example.com')
- self.assertEquals(metadata['keywords'], ['one', 'two'])
- self.assertEquals(metadata['platform'], [])
- self.assertEquals(metadata['obsoletes'], [])
- self.assertEquals(metadata['requires-dist'], ['foo'])
+ self.assertEqual(metadata['name'], "package")
+ self.assertEqual(metadata['version'], "1.0")
+ self.assertEqual(metadata['summary'], "xxx")
+ self.assertEqual(metadata['download_url'], 'http://example.com')
+ self.assertEqual(metadata['keywords'], ['one', 'two'])
+ self.assertEqual(metadata['platform'], [])
+ self.assertEqual(metadata['obsoletes'], [])
+ self.assertEqual(metadata['requires-dist'], ['foo'])
def test_suite():
- suite = unittest2.TestSuite()
- suite.addTest(unittest2.makeSuite(DistributionTestCase))
- suite.addTest(unittest2.makeSuite(MetadataTestCase))
+ suite = unittest.TestSuite()
+ suite.addTest(unittest.makeSuite(DistributionTestCase))
+ suite.addTest(unittest.makeSuite(MetadataTestCase))
return suite
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_emxccompiler.py b/src/distutils2/tests/test_emxccompiler.py
index 86b7c6d..117e005 100644
--- a/src/distutils2/tests/test_emxccompiler.py
+++ b/src/distutils2/tests/test_emxccompiler.py
@@ -1,5 +1,4 @@
"""Tests for distutils.emxccompiler."""
-import unittest2
import sys
import os
import warnings
@@ -10,14 +9,15 @@ from distutils2.tests import captured_stdout
from distutils2.compiler.emxccompiler import get_versions
from distutils2.util import get_compiler_versions
from distutils2.tests import support
+from distutils2.tests.support import unittest
class EmxCCompilerTestCase(support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
pass
def test_suite():
- return unittest2.makeSuite(EmxCCompilerTestCase)
+ return unittest.makeSuite(EmxCCompilerTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_extension.py b/src/distutils2/tests/test_extension.py
index 0194f52..ac19c6a 100755
--- a/src/distutils2/tests/test_extension.py
+++ b/src/distutils2/tests/test_extension.py
@@ -1,16 +1,16 @@
"""Tests for distutils.extension."""
-import unittest2
import os
import warnings
from distutils2.extension import Extension
+from distutils2.tests.support import unittest
-class ExtensionTestCase(unittest2.TestCase):
+class ExtensionTestCase(unittest.TestCase):
pass
def test_suite():
- return unittest2.makeSuite(ExtensionTestCase)
+ return unittest.makeSuite(ExtensionTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_install.py b/src/distutils2/tests/test_install.py
index 9f63abc..5cf6cd9 100644
--- a/src/distutils2/tests/test_install.py
+++ b/src/distutils2/tests/test_install.py
@@ -3,7 +3,6 @@
import os
import os.path
import sys
-import unittest2
import site
from distutils2._backport import sysconfig
@@ -22,11 +21,12 @@ from distutils2.core import Distribution
from distutils2.errors import DistutilsOptionError
from distutils2.tests import support
+from distutils2.tests.support import unittest
class InstallTestCase(support.TempdirManager,
support.EnvironGuard,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_home_installation_scheme(self):
# This ensure two things:
@@ -139,23 +139,23 @@ class InstallTestCase(support.TempdirManager,
# two elements
cmd.handle_extra_path()
- self.assertEquals(cmd.extra_path, ['path', 'dirs'])
- self.assertEquals(cmd.extra_dirs, 'dirs')
- self.assertEquals(cmd.path_file, 'path')
+ self.assertEqual(cmd.extra_path, ['path', 'dirs'])
+ self.assertEqual(cmd.extra_dirs, 'dirs')
+ self.assertEqual(cmd.path_file, 'path')
# one element
cmd.extra_path = ['path']
cmd.handle_extra_path()
- self.assertEquals(cmd.extra_path, ['path'])
- self.assertEquals(cmd.extra_dirs, 'path')
- self.assertEquals(cmd.path_file, 'path')
+ self.assertEqual(cmd.extra_path, ['path'])
+ self.assertEqual(cmd.extra_dirs, 'path')
+ self.assertEqual(cmd.path_file, 'path')
# none
dist.extra_path = cmd.extra_path = None
cmd.handle_extra_path()
- self.assertEquals(cmd.extra_path, None)
- self.assertEquals(cmd.extra_dirs, '')
- self.assertEquals(cmd.path_file, None)
+ self.assertEqual(cmd.extra_path, None)
+ self.assertEqual(cmd.extra_dirs, '')
+ self.assertEqual(cmd.path_file, None)
# three elements (no way !)
cmd.extra_path = 'path,dirs,again'
@@ -199,7 +199,7 @@ class InstallTestCase(support.TempdirManager,
# line (the egg info file)
f = open(cmd.record)
try:
- self.assertEquals(len(f.readlines()), 1)
+ self.assertEqual(len(f.readlines()), 1)
finally:
f.close()
@@ -214,7 +214,7 @@ class InstallTestCase(support.TempdirManager,
self.assertTrue(len(self.logs) > old_logs_len)
def test_suite():
- return unittest2.makeSuite(InstallTestCase)
+ return unittest.makeSuite(InstallTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_install_data.py b/src/distutils2/tests/test_install_data.py
index 16d5917..48cea63 100644
--- a/src/distutils2/tests/test_install_data.py
+++ b/src/distutils2/tests/test_install_data.py
@@ -1,16 +1,16 @@
"""Tests for distutils.command.install_data."""
import sys
import os
-import unittest2
import getpass
from distutils2.command.install_data import install_data
from distutils2.tests import support
+from distutils2.tests.support import unittest
class InstallDataTestCase(support.TempdirManager,
support.LoggingSilencer,
support.EnvironGuard,
- unittest2.TestCase):
+ unittest.TestCase):
def test_simple_run(self):
pkg_dir, dist = self.create_dist()
@@ -27,14 +27,14 @@ class InstallDataTestCase(support.TempdirManager,
self.write_file(two, 'xxx')
cmd.data_files = [one, (inst2, [two])]
- self.assertEquals(cmd.get_inputs(), [one, (inst2, [two])])
+ self.assertEqual(cmd.get_inputs(), [one, (inst2, [two])])
# let's run the command
cmd.ensure_finalized()
cmd.run()
# let's check the result
- self.assertEquals(len(cmd.get_outputs()), 2)
+ self.assertEqual(len(cmd.get_outputs()), 2)
rtwo = os.path.split(two)[-1]
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
rone = os.path.split(one)[-1]
@@ -47,7 +47,7 @@ class InstallDataTestCase(support.TempdirManager,
cmd.run()
# let's check the result
- self.assertEquals(len(cmd.get_outputs()), 2)
+ self.assertEqual(len(cmd.get_outputs()), 2)
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
self.assertTrue(os.path.exists(os.path.join(inst, rone)))
cmd.outfiles = []
@@ -65,12 +65,12 @@ class InstallDataTestCase(support.TempdirManager,
cmd.run()
# let's check the result
- self.assertEquals(len(cmd.get_outputs()), 4)
+ self.assertEqual(len(cmd.get_outputs()), 4)
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
self.assertTrue(os.path.exists(os.path.join(inst, rone)))
def test_suite():
- return unittest2.makeSuite(InstallDataTestCase)
+ return unittest.makeSuite(InstallDataTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_install_headers.py b/src/distutils2/tests/test_install_headers.py
index 222269d..4e0dce7 100644
--- a/src/distutils2/tests/test_install_headers.py
+++ b/src/distutils2/tests/test_install_headers.py
@@ -1,16 +1,16 @@
"""Tests for distutils.command.install_headers."""
import sys
import os
-import unittest2
import getpass
from distutils2.command.install_headers import install_headers
from distutils2.tests import support
+from distutils2.tests.support import unittest
class InstallHeadersTestCase(support.TempdirManager,
support.LoggingSilencer,
support.EnvironGuard,
- unittest2.TestCase):
+ unittest.TestCase):
def test_simple_run(self):
# we have two headers
@@ -23,7 +23,7 @@ class InstallHeadersTestCase(support.TempdirManager,
pkg_dir, dist = self.create_dist(headers=headers)
cmd = install_headers(dist)
- self.assertEquals(cmd.get_inputs(), headers)
+ self.assertEqual(cmd.get_inputs(), headers)
# let's run the command
cmd.install_dir = os.path.join(pkg_dir, 'inst')
@@ -31,10 +31,10 @@ class InstallHeadersTestCase(support.TempdirManager,
cmd.run()
# let's check the results
- self.assertEquals(len(cmd.get_outputs()), 2)
+ self.assertEqual(len(cmd.get_outputs()), 2)
def test_suite():
- return unittest2.makeSuite(InstallHeadersTestCase)
+ return unittest.makeSuite(InstallHeadersTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_install_lib.py b/src/distutils2/tests/test_install_lib.py
index 9f6f7fe..680eaf1 100644
--- a/src/distutils2/tests/test_install_lib.py
+++ b/src/distutils2/tests/test_install_lib.py
@@ -1,12 +1,12 @@
"""Tests for distutils.command.install_data."""
import sys
import os
-import unittest2
from distutils2.command.install_lib import install_lib
from distutils2.extension import Extension
from distutils2.tests import support
from distutils2.errors import DistutilsOptionError
+from distutils2.tests.support import unittest
try:
no_bytecode = sys.dont_write_bytecode
@@ -18,15 +18,15 @@ except AttributeError:
class InstallLibTestCase(support.TempdirManager,
support.LoggingSilencer,
support.EnvironGuard,
- unittest2.TestCase):
+ unittest.TestCase):
def test_finalize_options(self):
pkg_dir, dist = self.create_dist()
cmd = install_lib(dist)
cmd.finalize_options()
- self.assertEquals(cmd.compile, 1)
- self.assertEquals(cmd.optimize, 0)
+ self.assertEqual(cmd.compile, 1)
+ self.assertEqual(cmd.optimize, 0)
# optimize must be 0, 1, or 2
cmd.optimize = 'foo'
@@ -36,9 +36,9 @@ class InstallLibTestCase(support.TempdirManager,
cmd.optimize = '2'
cmd.finalize_options()
- self.assertEquals(cmd.optimize, 2)
+ self.assertEqual(cmd.optimize, 2)
- @unittest2.skipIf(no_bytecode, 'byte-compile not supported')
+ @unittest.skipIf(no_bytecode, 'byte-compile not supported')
def test_byte_compile(self):
pkg_dir, dist = self.create_dist()
cmd = install_lib(dist)
@@ -82,9 +82,9 @@ class InstallLibTestCase(support.TempdirManager,
cmd.distribution.script_name = 'setup.py'
# get_input should return 2 elements
- self.assertEquals(len(cmd.get_inputs()), 2)
+ self.assertEqual(len(cmd.get_inputs()), 2)
- @unittest2.skipUnless(bytecode_support, 'sys.dont_write_bytecode not supported')
+ @unittest.skipUnless(bytecode_support, '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()
@@ -102,7 +102,7 @@ class InstallLibTestCase(support.TempdirManager,
self.assertTrue('byte-compiling is disabled' in self.logs[0][1])
def test_suite():
- return unittest2.makeSuite(InstallLibTestCase)
+ return unittest.makeSuite(InstallLibTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_install_scripts.py b/src/distutils2/tests/test_install_scripts.py
index 9ffd43f..32c800d 100644
--- a/src/distutils2/tests/test_install_scripts.py
+++ b/src/distutils2/tests/test_install_scripts.py
@@ -1,17 +1,17 @@
"""Tests for distutils.command.install_scripts."""
import os
-import unittest2
from distutils2.command.install_scripts import install_scripts
from distutils2.core import Distribution
from distutils2.tests import support
+from distutils2.tests.support import unittest
class InstallScriptsTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_default_settings(self):
dist = Distribution()
@@ -73,7 +73,7 @@ class InstallScriptsTestCase(support.TempdirManager,
def test_suite():
- return unittest2.makeSuite(InstallScriptsTestCase)
+ return unittest.makeSuite(InstallScriptsTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_manifest.py b/src/distutils2/tests/test_manifest.py
index 5a74d9e..e7d1ca2 100644
--- a/src/distutils2/tests/test_manifest.py
+++ b/src/distutils2/tests/test_manifest.py
@@ -1,10 +1,10 @@
"""Tests for distutils.manifest."""
-import unittest2
import os
import sys
import logging
from distutils2.tests import support
+from distutils2.tests.support import unittest
from distutils2.manifest import Manifest
_MANIFEST = """\
@@ -18,7 +18,7 @@ recursive-include bar \\
"""
class ManifestTestCase(support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
def test_manifest_reader(self):
@@ -44,14 +44,14 @@ class ManifestTestCase(support.TempdirManager,
# the manifest should have been read
# and 3 warnings issued (we ddidn't provided the files)
- self.assertEquals(len(warns), 3)
+ self.assertEqual(len(warns), 3)
for warn in warns:
self.assertIn('warning: no files found matching', warn)
def test_suite():
- return unittest2.makeSuite(ManifestTestCase)
+ return unittest.makeSuite(ManifestTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_metadata.py b/src/distutils2/tests/test_metadata.py
index 347b9f5..8c15d58 100644
--- a/src/distutils2/tests/test_metadata.py
+++ b/src/distutils2/tests/test_metadata.py
@@ -1,13 +1,13 @@
"""Tests for distutils.command.bdist."""
-import unittest2
import os
import sys
from StringIO import StringIO
from distutils2.metadata import (DistributionMetadata, _interpret,
PKG_INFO_PREFERRED_VERSION)
+from distutils2.tests.support import unittest
-class DistributionMetadataTestCase(unittest2.TestCase):
+class DistributionMetadataTestCase(unittest.TestCase):
def test_interpret(self):
@@ -15,15 +15,15 @@ class DistributionMetadataTestCase(unittest2.TestCase):
version = sys.version.split()[0]
os_name = os.name
- assert _interpret("sys.platform == '%s'" % platform)
- assert _interpret("sys.platform == '%s' or python_version == '2.4'" \
- % platform)
- assert _interpret("sys.platform == '%s' and "
- "python_full_version == '%s'"\
- % (platform, version))
- assert _interpret("'%s' == sys.platform" % platform)
+ self.assertTrue(_interpret("sys.platform == '%s'" % platform))
+ self.assertTrue(_interpret(
+ "sys.platform == '%s' or python_version == '2.4'" % platform))
+ self.assertTrue(_interpret(
+ "sys.platform == '%s' and python_full_version == '%s'" %
+ (platform, version)))
+ self.assertTrue(_interpret("'%s' == sys.platform" % platform))
- assert _interpret('os.name == "%s"' % os_name)
+ self.assertTrue(_interpret('os.name == "%s"' % os_name))
# stuff that need to raise a syntax error
ops = ('os.name == os.name', 'os.name == 2', "'2' == '2'",
@@ -35,24 +35,25 @@ class DistributionMetadataTestCase(unittest2.TestCase):
OP = 'os.name == "%s"' % os_name
AND = ' and '
OR = ' or '
- assert _interpret(OP+AND+OP)
- assert _interpret(OP+AND+OP+AND+OP)
- assert _interpret(OP+OR+OP)
- assert _interpret(OP+OR+OP+OR+OP)
+ self.assertTrue(_interpret(OP + AND + OP))
+ self.assertTrue(_interpret(OP + AND + OP + AND + OP))
+ self.assertTrue(_interpret(OP + OR + OP))
+ self.assertTrue(_interpret(OP + OR + OP + OR + OP))
# other operators
- assert _interpret("os.name != 'buuuu'")
- assert _interpret("python_version > '1.0'")
- assert _interpret("python_version < '5.0'")
- assert _interpret("python_version <= '5.0'")
- assert _interpret("python_version >= '1.0'")
- assert _interpret("'%s' in os.name" % os_name)
- assert _interpret("'buuuu' not in os.name")
- assert _interpret("'buuuu' not in os.name and '%s' in os.name" \
- % os_name)
+ self.assertTrue(_interpret("os.name != 'buuuu'"))
+ self.assertTrue(_interpret("python_version > '1.0'"))
+ self.assertTrue(_interpret("python_version < '5.0'"))
+ self.assertTrue(_interpret("python_version <= '5.0'"))
+ self.assertTrue(_interpret("python_version >= '1.0'"))
+ self.assertTrue(_interpret("'%s' in os.name" % os_name))
+ self.assertTrue(_interpret("'buuuu' not in os.name"))
+ self.assertTrue(_interpret(
+ "'buuuu' not in os.name and '%s' in os.name" % os_name))
# execution context
- assert _interpret('python_version == "0.1"', {'python_version': '0.1'})
+ self.assertTrue(_interpret('python_version == "0.1"',
+ {'python_version': '0.1'}))
def test_metadata_read_write(self):
@@ -64,7 +65,7 @@ class DistributionMetadataTestCase(unittest2.TestCase):
res = res.read()
f = open(PKG_INFO)
wanted = f.read()
- self.assert_('Keywords: keyring,password,crypt' in res)
+ self.assertTrue('Keywords: keyring,password,crypt' in res)
f.close()
def test_metadata_markers(self):
@@ -72,16 +73,16 @@ class DistributionMetadataTestCase(unittest2.TestCase):
PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO')
content = open(PKG_INFO).read()
content = content % sys.platform
- metadata = DistributionMetadata(platform_dependant=True)
+ metadata = DistributionMetadata(platform_dependent=True)
metadata.read_file(StringIO(content))
- self.assertEquals(metadata['Requires-Dist'], ['bar'])
+ self.assertEqual(metadata['Requires-Dist'], ['bar'])
# test with context
context = {'sys.platform': 'okook'}
- metadata = DistributionMetadata(platform_dependant=True,
+ metadata = DistributionMetadata(platform_dependent=True,
execution_context=context)
metadata.read_file(StringIO(content))
- self.assertEquals(metadata['Requires-Dist'], ['foo'])
+ self.assertEqual(metadata['Requires-Dist'], ['foo'])
def test_description(self):
PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO')
@@ -93,14 +94,14 @@ class DistributionMetadataTestCase(unittest2.TestCase):
# see if we can read the description now
DESC = os.path.join(os.path.dirname(__file__), 'LONG_DESC.txt')
wanted = open(DESC).read()
- self.assertEquals(wanted, metadata['Description'])
+ self.assertEqual(wanted, metadata['Description'])
# save the file somewhere and make sure we can read it back
out = StringIO()
metadata.write_file(out)
out.seek(0)
metadata.read_file(out)
- self.assertEquals(wanted, metadata['Description'])
+ self.assertEqual(wanted, metadata['Description'])
def test_mapper_apis(self):
PKG_INFO = os.path.join(os.path.dirname(__file__), 'PKG-INFO')
@@ -115,25 +116,25 @@ class DistributionMetadataTestCase(unittest2.TestCase):
def test_versions(self):
metadata = DistributionMetadata()
metadata['Obsoletes'] = 'ok'
- self.assertEquals(metadata['Metadata-Version'], '1.1')
+ self.assertEqual(metadata['Metadata-Version'], '1.1')
del metadata['Obsoletes']
metadata['Obsoletes-Dist'] = 'ok'
- self.assertEquals(metadata['Metadata-Version'], '1.2')
+ self.assertEqual(metadata['Metadata-Version'], '1.2')
del metadata['Obsoletes-Dist']
metadata['Version'] = '1'
- self.assertEquals(metadata['Metadata-Version'], '1.0')
+ self.assertEqual(metadata['Metadata-Version'], '1.0')
PKG_INFO = os.path.join(os.path.dirname(__file__),
'SETUPTOOLS-PKG-INFO')
metadata.read_file(StringIO(open(PKG_INFO).read()))
- self.assertEquals(metadata['Metadata-Version'], '1.0')
+ self.assertEqual(metadata['Metadata-Version'], '1.0')
PKG_INFO = os.path.join(os.path.dirname(__file__),
'SETUPTOOLS-PKG-INFO2')
metadata.read_file(StringIO(open(PKG_INFO).read()))
- self.assertEquals(metadata['Metadata-Version'], '1.1')
+ self.assertEqual(metadata['Metadata-Version'], '1.1')
def test_warnings(self):
metadata = DistributionMetadata()
@@ -161,7 +162,7 @@ class DistributionMetadataTestCase(unittest2.TestCase):
# we should have a certain amount of warnings
num_wanted = len(values)
- self.assertEquals(num_wanted, res)
+ self.assertEqual(num_wanted, res)
def test_multiple_predicates(self):
metadata = DistributionMetadata()
@@ -184,29 +185,29 @@ class DistributionMetadataTestCase(unittest2.TestCase):
res = m.warns
del m.warns
- self.assertEquals(res, 0)
+ self.assertEqual(res, 0)
def test_project_url(self):
metadata = DistributionMetadata()
metadata['Project-URL'] = [('one', 'http://ok')]
- self.assertEquals(metadata['Project-URL'],
+ self.assertEqual(metadata['Project-URL'],
[('one', 'http://ok')])
- self.assertEquals(metadata.version, '1.2')
+ self.assertEqual(metadata.version, '1.2')
def test_check(self):
metadata = DistributionMetadata()
metadata['Version'] = 'rr'
metadata['Requires-dist'] = ['Foo (a)']
missing, warnings = metadata.check()
- self.assertEquals(missing, ['Name', 'Home-page'])
- self.assertEquals(len(warnings), 2)
+ self.assertEqual(missing, ['Name', 'Home-page'])
+ self.assertEqual(len(warnings), 2)
def test_best_choice(self):
metadata = DistributionMetadata()
metadata['Version'] = '1.0'
- self.assertEquals(metadata.version, PKG_INFO_PREFERRED_VERSION)
+ self.assertEqual(metadata.version, PKG_INFO_PREFERRED_VERSION)
metadata['Classifier'] = ['ok']
- self.assertEquals(metadata.version, '1.2')
+ self.assertEqual(metadata.version, '1.2')
def test_project_urls(self):
# project-url is a bit specific, make sure we write it
@@ -214,7 +215,7 @@ class DistributionMetadataTestCase(unittest2.TestCase):
metadata = DistributionMetadata()
metadata['Version'] = '1.0'
metadata['Project-Url'] = [('one', 'http://ok')]
- self.assertEquals(metadata['Project-Url'], [('one', 'http://ok')])
+ self.assertEqual(metadata['Project-Url'], [('one', 'http://ok')])
file_ = StringIO()
metadata.write_file(file_)
file_.seek(0)
@@ -224,11 +225,11 @@ class DistributionMetadataTestCase(unittest2.TestCase):
file_.seek(0)
metadata = DistributionMetadata()
metadata.read_file(file_)
- self.assertEquals(metadata['Project-Url'], [('one', 'http://ok')])
+ self.assertEqual(metadata['Project-Url'], [('one', 'http://ok')])
def test_suite():
- return unittest2.makeSuite(DistributionMetadataTestCase)
+ return unittest.makeSuite(DistributionMetadataTestCase)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_msvc9compiler.py b/src/distutils2/tests/test_msvc9compiler.py
index 1c1e8c2..42dea21 100644
--- a/src/distutils2/tests/test_msvc9compiler.py
+++ b/src/distutils2/tests/test_msvc9compiler.py
@@ -1,10 +1,10 @@
"""Tests for distutils.msvc9compiler."""
import sys
-import unittest2
import os
from distutils2.errors import DistutilsPlatformError
from distutils2.tests import support
+from distutils2.tests.support import unittest
_MANIFEST = """\
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
@@ -62,9 +62,9 @@ _CLEANED_MANIFEST = """\
class msvc9compilerTestCase(support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
- @unittest2.skipUnless(sys.platform=="win32", "These tests are only for win32")
+ @unittest.skipUnless(sys.platform=="win32", "These tests are only for win32")
def test_no_compiler(self):
# makes sure query_vcvarsall throws
# a DistutilsPlatformError if the compiler
@@ -86,7 +86,7 @@ class msvc9compilerTestCase(support.TempdirManager,
finally:
msvc9compiler.find_vcvarsall = old_find_vcvarsall
- @unittest2.skipUnless(sys.platform=="win32", "These tests are only for win32")
+ @unittest.skipUnless(sys.platform=="win32", "These tests are only for win32")
def test_reg_class(self):
from distutils2.msvccompiler import get_build_version
if get_build_version() < 8.0:
@@ -105,12 +105,12 @@ class msvc9compilerTestCase(support.TempdirManager,
import _winreg
HKCU = _winreg.HKEY_CURRENT_USER
keys = Reg.read_keys(HKCU, 'xxxx')
- self.assertEquals(keys, None)
+ self.assertEqual(keys, None)
keys = Reg.read_keys(HKCU, r'Control Panel')
self.assertTrue('Desktop' in keys)
- @unittest2.skipUnless(sys.platform=="win32", "These tests are only for win32")
+ @unittest.skipUnless(sys.platform=="win32", "These tests are only for win32")
def test_remove_visual_c_ref(self):
from distutils2.msvc9compiler import MSVCCompiler
tempdir = self.mkdtemp()
@@ -129,11 +129,11 @@ class msvc9compilerTestCase(support.TempdirManager,
f.close()
# makes sure the manifest was properly cleaned
- self.assertEquals(content, _CLEANED_MANIFEST)
+ self.assertEqual(content, _CLEANED_MANIFEST)
def test_suite():
- return unittest2.makeSuite(msvc9compilerTestCase)
+ return unittest.makeSuite(msvc9compilerTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_pypi_versions.py b/src/distutils2/tests/test_pypi_versions.py
index 0a851e4..4e97147 100644
--- a/src/distutils2/tests/test_pypi_versions.py
+++ b/src/distutils2/tests/test_pypi_versions.py
@@ -17,9 +17,9 @@ except:
import xmlrpclib
import os.path
-import unittest2
from distutils2.version import suggest_normalized_version
+from distutils2.tests.support import unittest
def test_pypi():
#
@@ -121,11 +121,11 @@ def test_pypi():
print "Have Suggestion : ", have_sugg, pct % (have_sugg/total_versions*100,)
print "No Suggestion : ", no_sugg, pct % (no_sugg/total_versions*100,)
-class TestPyPI(unittest2.TestCase):
+class TestPyPI(unittest.TestCase):
pass
def test_suite():
- return unittest2.makeSuite(TestPyPI)
+ return unittest.makeSuite(TestPyPI)
if __name__ == '__main__':
run_unittest(test_suite())
diff --git a/src/distutils2/tests/test_register.py b/src/distutils2/tests/test_register.py
index c6dc1f6..be782d1 100644
--- a/src/distutils2/tests/test_register.py
+++ b/src/distutils2/tests/test_register.py
@@ -2,7 +2,6 @@
# -*- encoding: utf8 -*-
import sys
import os
-import unittest2
import getpass
import urllib2
import warnings
@@ -19,6 +18,7 @@ from distutils2.core import Distribution
from distutils2.errors import DistutilsSetupError
from distutils2.tests import support
+from distutils2.tests.support import unittest
from distutils2.tests.test_config import PYPIRC, PyPIRCCommandTestCase
PYPIRC_NOPASSWORD = """\
@@ -124,7 +124,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
# with the content similar to WANTED_PYPIRC
content = open(self.rc).read()
- self.assertEquals(content, WANTED_PYPIRC)
+ self.assertEqual(content, WANTED_PYPIRC)
# now let's make sure the .pypirc file generated
# really works : we shouldn't be asked anything
@@ -141,7 +141,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
self.assertTrue(self.conn.reqs, 2)
req1 = dict(self.conn.reqs[0].headers)
req2 = dict(self.conn.reqs[1].headers)
- self.assertEquals(req2['Content-length'], req1['Content-length'])
+ self.assertEqual(req2['Content-length'], req1['Content-length'])
self.assertTrue('xxx' in self.conn.reqs[1].data)
def test_password_not_in_file(self):
@@ -154,7 +154,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
# dist.password should be set
# therefore used afterwards by other commands
- self.assertEquals(cmd.distribution.password, 'password')
+ self.assertEqual(cmd.distribution.password, 'password')
def test_registering(self):
# this test runs choice 2
@@ -171,7 +171,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
self.assertTrue(self.conn.reqs, 1)
req = self.conn.reqs[0]
headers = dict(req.headers)
- self.assertEquals(headers['Content-length'], '608')
+ self.assertEqual(headers['Content-length'], '608')
self.assertTrue('tarek' in req.data)
def test_password_reset(self):
@@ -189,10 +189,10 @@ class RegisterTestCase(PyPIRCCommandTestCase):
self.assertTrue(self.conn.reqs, 1)
req = self.conn.reqs[0]
headers = dict(req.headers)
- self.assertEquals(headers['Content-length'], '290')
+ self.assertEqual(headers['Content-length'], '290')
self.assertTrue('tarek' in req.data)
- @unittest2.skipUnless(DOCUTILS_SUPPORT, 'needs docutils')
+ @unittest.skipUnless(DOCUTILS_SUPPORT, 'needs docutils')
def test_strict(self):
# testing the script option
# when on, the register command stops if
@@ -246,11 +246,11 @@ class RegisterTestCase(PyPIRCCommandTestCase):
cmd.ensure_finalized()
cmd.distribution.metadata['Requires-Dist'] = ['lxml']
data = cmd.build_post_data('submit')
- self.assertEquals(data['metadata_version'], '1.2')
- self.assertEquals(data['requires_dist'], ['lxml'])
+ self.assertEqual(data['metadata_version'], '1.2')
+ self.assertEqual(data['requires_dist'], ['lxml'])
def test_suite():
- return unittest2.makeSuite(RegisterTestCase)
+ return unittest.makeSuite(RegisterTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_sdist.py b/src/distutils2/tests/test_sdist.py
index ed7d6e2..ec4c87a 100644
--- a/src/distutils2/tests/test_sdist.py
+++ b/src/distutils2/tests/test_sdist.py
@@ -1,6 +1,5 @@
"""Tests for distutils.command.sdist."""
import os
-import unittest2
import shutil
import zipfile
import tarfile
@@ -21,7 +20,6 @@ except ImportError:
from os.path import join
import sys
-import tempfile
import warnings
from distutils2.tests import captured_stdout
@@ -29,6 +27,7 @@ from distutils2.tests import captured_stdout
from distutils2.command.sdist import sdist
from distutils2.command.sdist import show_formats
from distutils2.core import Distribution
+from distutils2.tests.support import unittest
from distutils2.tests.test_config import PyPIRCCommandTestCase
from distutils2.errors import DistutilsExecError, DistutilsOptionError
from distutils2.spawn import find_executable
@@ -97,7 +96,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
cmd.warn = _warn
return dist, cmd
- @unittest2.skipUnless(zlib, "requires zlib")
+ @unittest.skipUnless(zlib, "requires zlib")
def test_prune_file_list(self):
# this test creates a package with some vcs dirs in it
# and launch sdist to make sure they get pruned
@@ -128,7 +127,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
# now let's check what we have
dist_folder = join(self.tmp_dir, 'dist')
files = os.listdir(dist_folder)
- self.assertEquals(files, ['fake-1.0.zip'])
+ self.assertEqual(files, ['fake-1.0.zip'])
zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
try:
@@ -137,9 +136,9 @@ class SDistTestCase(PyPIRCCommandTestCase):
zip_file.close()
# making sure everything has been pruned correctly
- self.assertEquals(len(content), 4)
+ self.assertEqual(len(content), 4)
- @unittest2.skipUnless(zlib, "requires zlib")
+ @unittest.skipUnless(zlib, "requires zlib")
def test_make_distribution(self):
# check if tar and gzip are installed
@@ -159,7 +158,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
dist_folder = join(self.tmp_dir, 'dist')
result = os.listdir(dist_folder)
result.sort()
- self.assertEquals(result,
+ self.assertEqual(result,
['fake-1.0.tar', 'fake-1.0.tar.gz'] )
os.remove(join(dist_folder, 'fake-1.0.tar'))
@@ -173,10 +172,10 @@ class SDistTestCase(PyPIRCCommandTestCase):
result = os.listdir(dist_folder)
result.sort()
- self.assertEquals(result,
+ self.assertEqual(result,
['fake-1.0.tar', 'fake-1.0.tar.gz'])
- @unittest2.skipUnless(zlib, "requires zlib")
+ @unittest.skipUnless(zlib, "requires zlib")
def test_add_defaults(self):
# http://bugs.python.org/issue2279
@@ -223,7 +222,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
# now let's check what we have
dist_folder = join(self.tmp_dir, 'dist')
files = os.listdir(dist_folder)
- self.assertEquals(files, ['fake-1.0.zip'])
+ self.assertEqual(files, ['fake-1.0.zip'])
zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
try:
@@ -232,13 +231,13 @@ class SDistTestCase(PyPIRCCommandTestCase):
zip_file.close()
# making sure everything was added
- self.assertEquals(len(content), 11)
+ self.assertEqual(len(content), 11)
# checking the MANIFEST
manifest = open(join(self.tmp_dir, 'MANIFEST')).read()
- self.assertEquals(manifest, MANIFEST % {'sep': os.sep})
+ self.assertEqual(manifest, MANIFEST % {'sep': os.sep})
- @unittest2.skipUnless(zlib, "requires zlib")
+ @unittest.skipUnless(zlib, "requires zlib")
def test_metadata_check_option(self):
# testing the `medata-check` option
dist, cmd = self.get_cmd(metadata={})
@@ -248,7 +247,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
cmd.ensure_finalized()
cmd.run()
warnings = self.get_logs(WARN)
- self.assertEquals(len(warnings), 1)
+ self.assertEqual(len(warnings), 1)
# trying with a complete set of metadata
self.clear_logs()
@@ -260,7 +259,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
# removing manifest generated warnings
warnings = [warn for warn in warnings if
not warn.endswith('-- skipping')]
- self.assertEquals(len(warnings), 0)
+ self.assertEqual(len(warnings), 0)
def test_show_formats(self):
@@ -270,7 +269,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
num_formats = len(get_archive_formats())
output = [line for line in stdout.split('\n')
if line.strip().startswith('--formats=')]
- self.assertEquals(len(output), num_formats)
+ self.assertEqual(len(output), num_formats)
def test_finalize_options(self):
@@ -278,9 +277,9 @@ class SDistTestCase(PyPIRCCommandTestCase):
cmd.finalize_options()
# default options set by finalize
- self.assertEquals(cmd.manifest, 'MANIFEST')
- self.assertEquals(cmd.template, 'MANIFEST.in')
- self.assertEquals(cmd.dist_dir, 'dist')
+ self.assertEqual(cmd.manifest, 'MANIFEST')
+ self.assertEqual(cmd.template, 'MANIFEST.in')
+ self.assertEqual(cmd.dist_dir, 'dist')
# formats has to be a string splitable on (' ', ',') or
# a stringlist
@@ -293,8 +292,8 @@ class SDistTestCase(PyPIRCCommandTestCase):
cmd.formats = 'supazipa'
self.assertRaises(DistutilsOptionError, cmd.finalize_options)
- @unittest2.skipUnless(zlib, "requires zlib")
- @unittest2.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
+ @unittest.skipUnless(zlib, "requires zlib")
+ @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
def test_make_distribution_owner_group(self):
# check if tar and gzip are installed
@@ -317,8 +316,8 @@ class SDistTestCase(PyPIRCCommandTestCase):
archive = tarfile.open(archive_name)
try:
for member in archive.getmembers():
- self.assertEquals(member.uid, 0)
- self.assertEquals(member.gid, 0)
+ self.assertEqual(member.uid, 0)
+ self.assertEqual(member.gid, 0)
finally:
archive.close()
@@ -339,7 +338,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
# rights (see #7408)
try:
for member in archive.getmembers():
- self.assertEquals(member.uid, os.getuid())
+ self.assertEqual(member.uid, os.getuid())
finally:
archive.close()
@@ -357,7 +356,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
self.assertIn('MANIFEST.in', cmd.filelist.files)
def test_suite():
- return unittest2.makeSuite(SDistTestCase)
+ return unittest.makeSuite(SDistTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_spawn.py b/src/distutils2/tests/test_spawn.py
index 0688543..2c7f1ad 100644
--- a/src/distutils2/tests/test_spawn.py
+++ b/src/distutils2/tests/test_spawn.py
@@ -1,5 +1,4 @@
"""Tests for distutils.spawn."""
-import unittest2
import os
import time
from distutils2.tests import captured_stdout
@@ -8,10 +7,11 @@ from distutils2.spawn import _nt_quote_args
from distutils2.spawn import spawn, find_executable
from distutils2.errors import DistutilsExecError
from distutils2.tests import support
+from distutils2.tests.support import unittest
class SpawnTestCase(support.TempdirManager,
support.LoggingSilencer,
- unittest2.TestCase):
+ unittest.TestCase):
def test_nt_quote_args(self):
@@ -20,10 +20,10 @@ class SpawnTestCase(support.TempdirManager,
(['nochange', 'nospace'],
['nochange', 'nospace'])):
res = _nt_quote_args(args)
- self.assertEquals(res, wanted)
+ self.assertEqual(res, wanted)
- @unittest2.skipUnless(os.name in ('nt', 'posix'),
+ @unittest.skipUnless(os.name in ('nt', 'posix'),
'Runs only under posix or nt')
def test_spawn(self):
tmpdir = self.mkdtemp()
@@ -54,7 +54,7 @@ class SpawnTestCase(support.TempdirManager,
spawn([exe]) # should work without any error
def test_suite():
- return unittest2.makeSuite(SpawnTestCase)
+ return unittest.makeSuite(SpawnTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_unixccompiler.py b/src/distutils2/tests/test_unixccompiler.py
index 2fa691e..6de616a 100644
--- a/src/distutils2/tests/test_unixccompiler.py
+++ b/src/distutils2/tests/test_unixccompiler.py
@@ -1,6 +1,5 @@
"""Tests for distutils.unixccompiler."""
import sys
-import unittest2
try:
import sysconfig
@@ -8,8 +7,9 @@ except ImportError:
from distutils2._backport import sysconfig
from distutils2.compiler.unixccompiler import UnixCCompiler
+from distutils2.tests.support import unittest
-class UnixCCompilerTestCase(unittest2.TestCase):
+class UnixCCompilerTestCase(unittest.TestCase):
def setUp(self):
self._backup_platform = sys.platform
@@ -127,7 +127,7 @@ class UnixCCompilerTestCase(unittest2.TestCase):
def test_suite():
- return unittest2.makeSuite(UnixCCompilerTestCase)
+ return unittest.makeSuite(UnixCCompilerTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_upload.py b/src/distutils2/tests/test_upload.py
index 29f5297..2e4a97e 100644
--- a/src/distutils2/tests/test_upload.py
+++ b/src/distutils2/tests/test_upload.py
@@ -2,13 +2,13 @@
# -*- encoding: utf8 -*-
import sys
import os
-import unittest2
from distutils2.command import upload as upload_mod
from distutils2.command.upload import upload
from distutils2.core import Distribution
from distutils2.tests import support
+from distutils2.tests.support import unittest
from distutils2.tests.test_config import PYPIRC, PyPIRCCommandTestCase
PYPIRC_LONG_PASSWORD = """\
@@ -77,10 +77,10 @@ class uploadTestCase(PyPIRCCommandTestCase):
dist = Distribution()
cmd = upload(dist)
cmd.finalize_options()
- for attr, waited in (('username', 'me'), ('password', 'secret'),
- ('realm', 'pypi'),
- ('repository', 'http://pypi.python.org/pypi')):
- self.assertEquals(getattr(cmd, attr), waited)
+ for attr, expected in (('username', 'me'), ('password', 'secret'),
+ ('realm', 'pypi'),
+ ('repository', 'http://pypi.python.org/pypi')):
+ self.assertEqual(getattr(cmd, attr), expected)
def test_saved_password(self):
# file with no password
@@ -90,14 +90,14 @@ class uploadTestCase(PyPIRCCommandTestCase):
dist = Distribution()
cmd = upload(dist)
cmd.finalize_options()
- self.assertEquals(cmd.password, None)
+ self.assertEqual(cmd.password, None)
# make sure we get it as well, if another command
# initialized it at the dist level
dist.password = 'xxx'
cmd = upload(dist)
cmd.finalize_options()
- self.assertEquals(cmd.password, 'xxx')
+ self.assertEqual(cmd.password, 'xxx')
def test_upload(self):
tmp = self.mkdtemp()
@@ -116,17 +116,17 @@ class uploadTestCase(PyPIRCCommandTestCase):
# what did we send ?
self.assertIn('dédé', self.last_open.req.data)
headers = dict(self.last_open.req.headers)
- self.assert_(headers['Content-length'] > 2000)
+ self.assertTrue(int(headers['Content-length']) < 2000)
self.assertTrue(headers['Content-type'].startswith('multipart/form-data'))
- self.assertEquals(self.last_open.req.get_method(), 'POST')
- self.assertEquals(self.last_open.req.get_full_url(),
+ self.assertEqual(self.last_open.req.get_method(), 'POST')
+ self.assertEqual(self.last_open.req.get_full_url(),
'http://pypi.python.org/pypi')
self.assertTrue('xxx' in self.last_open.req.data)
auth = self.last_open.req.headers['Authorization']
self.assertFalse('\n' in auth)
def test_suite():
- return unittest2.makeSuite(uploadTestCase)
+ return unittest.makeSuite(uploadTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_util.py b/src/distutils2/tests/test_util.py
index 0690d3a..4fc120e 100644
--- a/src/distutils2/tests/test_util.py
+++ b/src/distutils2/tests/test_util.py
@@ -1,7 +1,6 @@
"""Tests for distutils.util."""
import os
import sys
-import unittest2
from copy import copy
from StringIO import StringIO
import subprocess
@@ -17,6 +16,7 @@ from distutils2.util import (convert_path, change_root,
byte_compile, find_packages)
from distutils2 import util
from distutils2.tests import support
+from distutils2.tests.support import unittest
class FakePopen(object):
test_class = None
@@ -34,7 +34,7 @@ class FakePopen(object):
class UtilTestCase(support.EnvironGuard,
support.TempdirManager,
- unittest2.TestCase):
+ unittest.TestCase):
def setUp(self):
super(UtilTestCase, self).setUp()
@@ -100,7 +100,7 @@ class UtilTestCase(support.EnvironGuard,
return '/'.join(path)
os.path.join = _join
- self.assertEquals(convert_path('/home/to/my/stuff'),
+ self.assertEqual(convert_path('/home/to/my/stuff'),
'/home/to/my/stuff')
# win
@@ -112,9 +112,9 @@ class UtilTestCase(support.EnvironGuard,
self.assertRaises(ValueError, convert_path, '/home/to/my/stuff')
self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/')
- self.assertEquals(convert_path('home/to/my/stuff'),
+ self.assertEqual(convert_path('home/to/my/stuff'),
'home\\to\\my\\stuff')
- self.assertEquals(convert_path('.'),
+ self.assertEqual(convert_path('.'),
os.curdir)
def test_change_root(self):
@@ -127,9 +127,9 @@ class UtilTestCase(support.EnvironGuard,
return '/'.join(path)
os.path.join = _join
- self.assertEquals(change_root('/root', '/old/its/here'),
+ self.assertEqual(change_root('/root', '/old/its/here'),
'/root/old/its/here')
- self.assertEquals(change_root('/root', 'its/here'),
+ self.assertEqual(change_root('/root', 'its/here'),
'/root/its/here')
# windows
@@ -146,9 +146,9 @@ class UtilTestCase(support.EnvironGuard,
return '\\'.join(path)
os.path.join = _join
- self.assertEquals(change_root('c:\\root', 'c:\\old\\its\\here'),
+ self.assertEqual(change_root('c:\\root', 'c:\\old\\its\\here'),
'c:\\root\\old\\its\\here')
- self.assertEquals(change_root('c:\\root', 'its\\here'),
+ self.assertEqual(change_root('c:\\root', 'its\\here'),
'c:\\root\\its\\here')
# BugsBunny os (it's a great os)
@@ -159,7 +159,7 @@ class UtilTestCase(support.EnvironGuard,
# XXX platforms to be covered: os2, mac
def test_split_quoted(self):
- self.assertEquals(split_quoted('""one"" "two" \'three\' \\four'),
+ self.assertEqual(split_quoted('""one"" "two" \'three\' \\four'),
['one', 'two', 'three', 'four'])
def test_strtobool(self):
@@ -177,7 +177,7 @@ class UtilTestCase(support.EnvironGuard,
res = rfc822_escape(header)
wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s'
'header%(8s)s') % {'8s': '\n'+8*' '}
- self.assertEquals(res, wanted)
+ self.assertEqual(res, wanted)
def test_find_exe_version(self):
# the ld version scheme under MAC OS is:
@@ -195,7 +195,7 @@ class UtilTestCase(support.EnvironGuard,
('@(#)PROGRAM:ld PROJECT:ld64-95.2.12',
'95.2.12')):
result = _MAC_OS_X_LD_VERSION.search(output)
- self.assertEquals(result.group(1), version)
+ self.assertEqual(result.group(1), version)
def _find_executable(self, name):
if name in self._exes:
@@ -205,45 +205,45 @@ class UtilTestCase(support.EnvironGuard,
def test_get_compiler_versions(self):
# get_versions calls distutils.spawn.find_executable on
# 'gcc', 'ld' and 'dllwrap'
- self.assertEquals(get_compiler_versions(), (None, None, None))
+ self.assertEqual(get_compiler_versions(), (None, None, None))
# Let's fake we have 'gcc' and it returns '3.4.5'
self._exes['gcc'] = 'gcc (GCC) 3.4.5 (mingw special)\nFSF'
res = get_compiler_versions()
- self.assertEquals(str(res[0]), '3.4.5')
+ self.assertEqual(str(res[0]), '3.4.5')
# and let's see what happens when the version
# doesn't match the regular expression
# (\d+\.\d+(\.\d+)*)
self._exes['gcc'] = 'very strange output'
res = get_compiler_versions()
- self.assertEquals(res[0], None)
+ self.assertEqual(res[0], None)
# same thing for ld
if sys.platform != 'darwin':
self._exes['ld'] = 'GNU ld version 2.17.50 20060824'
res = get_compiler_versions()
- self.assertEquals(str(res[1]), '2.17.50')
+ self.assertEqual(str(res[1]), '2.17.50')
self._exes['ld'] = '@(#)PROGRAM:ld PROJECT:ld64-77'
res = get_compiler_versions()
- self.assertEquals(res[1], None)
+ self.assertEqual(res[1], None)
else:
self._exes['ld'] = 'GNU ld version 2.17.50 20060824'
res = get_compiler_versions()
- self.assertEquals(res[1], None)
+ self.assertEqual(res[1], None)
self._exes['ld'] = '@(#)PROGRAM:ld PROJECT:ld64-77'
res = get_compiler_versions()
- self.assertEquals(str(res[1]), '77')
+ self.assertEqual(str(res[1]), '77')
# and dllwrap
self._exes['dllwrap'] = 'GNU dllwrap 2.17.50 20060824\nFSF'
res = get_compiler_versions()
- self.assertEquals(str(res[2]), '2.17.50')
+ self.assertEqual(str(res[2]), '2.17.50')
self._exes['dllwrap'] = 'Cheese Wrap'
res = get_compiler_versions()
- self.assertEquals(res[2], None)
+ self.assertEqual(res[2], None)
- @unittest2.skipUnless(hasattr(sys, 'dont_write_bytecode'),
+ @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'),
'no dont_write_bytecode support')
def test_dont_write_bytecode(self):
# makes sure byte_compile raise a DistutilsError
@@ -294,11 +294,11 @@ class UtilTestCase(support.EnvironGuard,
self.write_file(os.path.join(pkg5, '__init__.py'))
res = find_packages([root], ['pkg1.pkg2'])
- self.assertEquals(set(res), set(['pkg1', 'pkg5', 'pkg1.pkg3', 'pkg1.pkg3.pkg6']))
+ self.assertEqual(set(res), set(['pkg1', 'pkg5', 'pkg1.pkg3', 'pkg1.pkg3.pkg6']))
def test_suite():
- return unittest2.makeSuite(UtilTestCase)
+ return unittest.makeSuite(UtilTestCase)
if __name__ == "__main__":
- unittest2.main(defaultTest="test_suite")
+ unittest.main(defaultTest="test_suite")
diff --git a/src/distutils2/tests/test_version.py b/src/distutils2/tests/test_version.py
index 4c10858..f97111d 100644
--- a/src/distutils2/tests/test_version.py
+++ b/src/distutils2/tests/test_version.py
@@ -1,5 +1,4 @@
"""Tests for distutils.version."""
-import unittest
import doctest
import os
@@ -7,6 +6,7 @@ from distutils2.version import NormalizedVersion as V
from distutils2.version import IrrationalVersionError
from distutils2.version import suggest_normalized_version as suggest
from distutils2.version import VersionPredicate
+from distutils2.tests.support import unittest
class VersionTestCase(unittest.TestCase):
@@ -25,15 +25,15 @@ class VersionTestCase(unittest.TestCase):
def test_basic_versions(self):
for v, s in self.versions:
- self.assertEquals(str(v), s)
+ self.assertEqual(str(v), s)
def test_from_parts(self):
for v, s in self.versions:
parts = v.parts
v2 = V.from_parts(*v.parts)
- self.assertEquals(v, v2)
- self.assertEquals(str(v), str(v2))
+ self.assertEqual(v, v2)
+ self.assertEqual(str(v), str(v2))
def test_irrational_versions(self):
@@ -96,34 +96,34 @@ class VersionTestCase(unittest.TestCase):
def test_suggest_normalized_version(self):
- self.assertEquals(suggest('1.0'), '1.0')
- self.assertEquals(suggest('1.0-alpha1'), '1.0a1')
- self.assertEquals(suggest('1.0c2'), '1.0c2')
- self.assertEquals(suggest('walla walla washington'), None)
- self.assertEquals(suggest('2.4c1'), '2.4c1')
+ self.assertEqual(suggest('1.0'), '1.0')
+ self.assertEqual(suggest('1.0-alpha1'), '1.0a1')
+ self.assertEqual(suggest('1.0c2'), '1.0c2')
+ self.assertEqual(suggest('walla walla washington'), None)
+ self.assertEqual(suggest('2.4c1'), '2.4c1')
# from setuptools
- self.assertEquals(suggest('0.4a1.r10'), '0.4a1.post10')
- self.assertEquals(suggest('0.7a1dev-r66608'), '0.7a1.dev66608')
- self.assertEquals(suggest('0.6a9.dev-r41475'), '0.6a9.dev41475')
- self.assertEquals(suggest('2.4preview1'), '2.4c1')
- self.assertEquals(suggest('2.4pre1') , '2.4c1')
- self.assertEquals(suggest('2.1-rc2'), '2.1c2')
+ self.assertEqual(suggest('0.4a1.r10'), '0.4a1.post10')
+ self.assertEqual(suggest('0.7a1dev-r66608'), '0.7a1.dev66608')
+ self.assertEqual(suggest('0.6a9.dev-r41475'), '0.6a9.dev41475')
+ self.assertEqual(suggest('2.4preview1'), '2.4c1')
+ self.assertEqual(suggest('2.4pre1') , '2.4c1')
+ self.assertEqual(suggest('2.1-rc2'), '2.1c2')
# from pypi
- self.assertEquals(suggest('0.1dev'), '0.1.dev0')
- self.assertEquals(suggest('0.1.dev'), '0.1.dev0')
+ self.assertEqual(suggest('0.1dev'), '0.1.dev0')
+ self.assertEqual(suggest('0.1.dev'), '0.1.dev0')
# we want to be able to parse Twisted
# development versions are like post releases in Twisted
- self.assertEquals(suggest('9.0.0+r2363'), '9.0.0.post2363')
+ self.assertEqual(suggest('9.0.0+r2363'), '9.0.0.post2363')
# pre-releases are using markers like "pre1"
- self.assertEquals(suggest('9.0.0pre1'), '9.0.0c1')
+ self.assertEqual(suggest('9.0.0pre1'), '9.0.0c1')
# we want to be able to parse Tcl-TK
# they us "p1" "p2" for post releases
- self.assertEquals(suggest('1.4p1'), '1.4.post1')
+ self.assertEqual(suggest('1.4p1'), '1.4.post1')
def test_predicate(self):
# VersionPredicate knows how to parse stuff like:
diff --git a/src/distutils2/util.py b/src/distutils2/util.py
index 0ab2e3e..63cbf0f 100644
--- a/src/distutils2/util.py
+++ b/src/distutils2/util.py
@@ -1,7 +1,6 @@
"""distutils.util
-Miscellaneous utility functions -- anything that doesn't fit into
-one of the other *util.py modules.
+Miscellaneous utility functions.
"""
__revision__ = "$Id: util.py 77761 2010-01-26 22:46:15Z tarek.ziade $"
diff --git a/src/distutils2/version.py b/src/distutils2/version.py
index 2977c8c..bf74ecf 100644
--- a/src/distutils2/version.py
+++ b/src/distutils2/version.py
@@ -3,6 +3,10 @@ import re
from distutils2.errors import IrrationalVersionError, HugeMajorVersionNumError
+__all__ = ['NormalizedVersion', 'suggest_normalized_version',
+ 'VersionPredicate', 'is_valid_version', 'is_valid_versions',
+ 'is_valid_predicate']
+
# A marker used in the second and third parts of the `parts` tuple, for
# versions that don't have those segments, to sort properly. An example
# of versions in sort order ('highest' last):
@@ -18,9 +22,9 @@ from distutils2.errors import IrrationalVersionError, HugeMajorVersionNumError
# |
# 'dev' < 'f' ----------------------------------------------/
# Other letters would do, but 'f' for 'final' is kind of nice.
-FINAL_MARKER = ('f',)
+_FINAL_MARKER = ('f',)
-VERSION_RE = re.compile(r'''
+_VERSION_RE = re.compile(r'''
^
(?P<version>\d+\.\d+) # minimum 'N.N'
(?P<extraversion>(?:\.\d+)*) # any number of extra '.N' segments
@@ -70,13 +74,13 @@ class NormalizedVersion(object):
self._parse(s, error_on_huge_major_num)
@classmethod
- def from_parts(cls, version, prerelease=FINAL_MARKER,
- devpost=FINAL_MARKER):
+ def from_parts(cls, version, prerelease=_FINAL_MARKER,
+ devpost=_FINAL_MARKER):
return cls(cls.parts_to_str((version, prerelease, devpost)))
def _parse(self, s, error_on_huge_major_num=True):
"""Parses a string version into parts."""
- match = VERSION_RE.search(s)
+ match = _VERSION_RE.search(s)
if not match:
raise IrrationalVersionError(s)
@@ -98,7 +102,7 @@ class NormalizedVersion(object):
pad_zeros_length=1)
parts.append(tuple(block))
else:
- parts.append(FINAL_MARKER)
+ parts.append(_FINAL_MARKER)
# postdev
if groups.get('postdev'):
@@ -106,14 +110,14 @@ class NormalizedVersion(object):
dev = groups.get('dev')
postdev = []
if post is not None:
- postdev.extend([FINAL_MARKER[0], 'post', int(post)])
+ postdev.extend([_FINAL_MARKER[0], 'post', int(post)])
if dev is None:
- postdev.append(FINAL_MARKER[0])
+ postdev.append(_FINAL_MARKER[0])
if dev is not None:
postdev.extend(['dev', int(dev)])
parts.append(tuple(postdev))
else:
- parts.append(FINAL_MARKER)
+ parts.append(_FINAL_MARKER)
self.parts = tuple(parts)
if error_on_huge_major_num and self.parts[0][0] > 1980:
raise HugeMajorVersionNumError("huge major version number, %r, "
@@ -154,10 +158,10 @@ class NormalizedVersion(object):
# XXX This doesn't check for invalid tuples
main, prerel, postdev = parts
s = '.'.join(str(v) for v in main)
- if prerel is not FINAL_MARKER:
+ if prerel is not _FINAL_MARKER:
s += prerel[0]
s += '.'.join(str(v) for v in prerel[1:])
- if postdev and postdev is not FINAL_MARKER:
+ if postdev and postdev is not _FINAL_MARKER:
if postdev[0] == 'f':
postdev = postdev[1:]
i = 0
@@ -197,6 +201,9 @@ class NormalizedVersion(object):
def __ge__(self, other):
return self.__eq__(other) or self.__gt__(other)
+ # See http://docs.python.org/reference/datamodel#object.__hash__
+ __hash__ = object.__hash__
+
def suggest_normalized_version(s):
"""Suggest a normalized version close to the given version string.
@@ -361,7 +368,7 @@ class VersionPredicate(object):
return False
return True
-class Versions(VersionPredicate):
+class _Versions(VersionPredicate):
def __init__(self, predicate):
predicate = predicate.strip()
match = _PLAIN_VERSIONS.match(predicate)
@@ -372,7 +379,7 @@ class Versions(VersionPredicate):
self.predicates = [_split_predicate(pred.strip())
for pred in predicates.split(',')]
-class Version(VersionPredicate):
+class _Version(VersionPredicate):
def __init__(self, predicate):
predicate = predicate.strip()
match = _PLAIN_VERSIONS.match(predicate)
@@ -391,7 +398,7 @@ def is_valid_predicate(predicate):
def is_valid_versions(predicate):
try:
- Versions(predicate)
+ _Versions(predicate)
except (ValueError, IrrationalVersionError):
return False
else:
@@ -399,7 +406,7 @@ def is_valid_versions(predicate):
def is_valid_version(predicate):
try:
- Version(predicate)
+ _Version(predicate)
except (ValueError, IrrationalVersionError):
return False
else: