[Python-checkins] distutils2: Added more tests

tarek.ziade python-checkins at python.org
Sun Aug 8 11:50:46 CEST 2010


tarek.ziade pushed aaf2faeb75e5 to distutils2:

http://hg.python.org/distutils2/rev/aaf2faeb75e5
changeset:   433:aaf2faeb75e5
user:        Josip Djolonga
date:        Thu Jul 22 16:20:49 2010 +0200
summary:     Added more tests
files:       src/distutils2/_backport/pkgutil.py, src/distutils2/_backport/tests/test_pkgutil.py, src/distutils2/command/install_distinfo.py, src/distutils2/tests/support.py, src/distutils2/tests/test_install_distinfo.py

diff --git a/src/distutils2/_backport/pkgutil.py b/src/distutils2/_backport/pkgutil.py
--- a/src/distutils2/_backport/pkgutil.py
+++ b/src/distutils2/_backport/pkgutil.py
@@ -1009,7 +1009,7 @@
     :rtype: iterator of :class:`Distribution` and :class:`EggInfoDistribution`
             instances"""
     if not _cache_enabled:
-        for dist in _yield_distributions(use_egg_info):
+        for dist in _yield_distributions(True, use_egg_info):
             yield dist
     else:
         _generate_cache(use_egg_info)
@@ -1039,7 +1039,7 @@
 
     :rtype: :class:`Distribution` or :class:`EggInfoDistribution` or None"""
     if not _cache_enabled:
-        for dist in _yield_distributions(use_egg_info):
+        for dist in _yield_distributions(True, use_egg_info):
             if dist.name == name:
                 return dist
     else:
diff --git a/src/distutils2/_backport/tests/test_pkgutil.py b/src/distutils2/_backport/tests/test_pkgutil.py
--- a/src/distutils2/_backport/tests/test_pkgutil.py
+++ b/src/distutils2/_backport/tests/test_pkgutil.py
@@ -25,12 +25,14 @@
     except ImportError:
         from unittest2.compatibility import relpath
 
+# Adapted from Python 2.7's trunk
+
 # 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(unittest.TestCase):
 
     def setUp(self):
@@ -108,10 +110,14 @@
 
         del sys.modules[pkg]
 
+
 # Adapted from Python 2.7's trunk
+
+
 class TestPkgUtilPEP302(unittest.TestCase):
 
     class MyTestLoader(object):
+
         def load_module(self, fullname):
             # Create an empty module
             mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
@@ -120,13 +126,14 @@
             # Make it a package
             mod.__path__ = []
             # Count how many times the module is reloaded
-            mod.__dict__['loads'] = mod.__dict__.get('loads',0) + 1
+            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()
 
@@ -319,7 +326,7 @@
         current_path = os.path.abspath(os.path.dirname(__file__))
         self.sys_path = sys.path[:]
         self.fake_dists_path = os.path.join(current_path, 'fake_dists')
-        sys.path[0:0] = [self.fake_dists_path]
+        sys.path.insert(0, self.fake_dists_path)
 
     def tearDown(self):
         sys.path[:] = self.sys_path
@@ -366,8 +373,12 @@
             if not isinstance(dist, Distribution):
                 self.fail("item received was not a Distribution instance: "
                     "%s" % type(dist))
-            if dist.name in dict(fake_dists).keys():
+            if dist.name in dict(fake_dists).keys() and \
+               dist.path.startswith(self.fake_dists_path):
                 found_dists.append((dist.name, dist.metadata['version'],))
+            else:
+                # check that it doesn't find anything more than this
+                self.assertFalse(dist.path.startswith(self.fake_dists_path))
             # otherwise we don't care what other distributions are found
 
         # Finally, test that we found all that we were looking for
@@ -375,7 +386,8 @@
 
         # Now, test if the egg-info distributions are found correctly as well
         fake_dists += [('bacon', '0.1'), ('cheese', '2.0.2'),
-                       ('banana', '0.4'), ('strawberry', '0.6')]
+                       ('banana', '0.4'), ('strawberry', '0.6'),
+                       ('truffles', '5.0')]
         found_dists = []
 
         dists = [dist for dist in get_distributions(use_egg_info=True)]
@@ -384,8 +396,11 @@
                     isinstance(dist, EggInfoDistribution)):
                 self.fail("item received was not a Distribution or "
                           "EggInfoDistribution instance: %s" % type(dist))
-            if dist.name in dict(fake_dists).keys():
+            if dist.name in dict(fake_dists).keys() and \
+               dist.path.startswith(self.fake_dists_path):
                 found_dists.append((dist.name, dist.metadata['version']))
+            else:
+                self.assertFalse(dist.path.startswith(self.fake_dists_path))
 
         self.assertListEqual(sorted(fake_dists), sorted(found_dists))
 
@@ -549,6 +564,33 @@
         l = [dist.name for dist in obsoletes_distribution('truffles', '0.2')]
         checkLists(l, ['towel-stuff'])
 
+    def test_yield_distribution(self):
+        # tests the internal function _yield_distributions
+        from distutils2._backport.pkgutil import _yield_distributions
+        checkLists = lambda x, y: self.assertListEqual(sorted(x), sorted(y))
+
+        eggs = [('bacon', '0.1'), ('banana', '0.4'), ('strawberry', '0.6'),
+                ('truffles', '5.0'), ('cheese', '2.0.2')]
+        dists = [('choxie', '2.0.0.9'), ('grammar', '1.0a4'),
+                 ('towel-stuff', '0.1')]
+
+        checkLists([], _yield_distributions(False, False))
+
+        found = [(dist.name, dist.metadata['Version'])
+                for dist in _yield_distributions(False, True)
+                if dist.path.startswith(self.fake_dists_path)]
+        checkLists(eggs, found)
+
+        found = [(dist.name, dist.metadata['Version'])
+                for dist in _yield_distributions(True, False)
+                if dist.path.startswith(self.fake_dists_path)]
+        checkLists(dists, found)
+
+        found = [(dist.name, dist.metadata['Version'])
+                for dist in _yield_distributions(True, True)
+                if dist.path.startswith(self.fake_dists_path)]
+        checkLists(dists + eggs, found)
+
 
 def test_suite():
     suite = unittest.TestSuite()
diff --git a/src/distutils2/command/install_distinfo.py b/src/distutils2/command/install_distinfo.py
--- a/src/distutils2/command/install_distinfo.py
+++ b/src/distutils2/command/install_distinfo.py
@@ -27,13 +27,13 @@
     description = 'Install a .dist-info directory for the package'
 
     user_options = [
-        ('dist-info-dir=', None,
+        ('distinfo-dir=', None,
                            'directory where the the .dist-info directory will '
                            'be installed'),
         ('installer=', None, 'the name of the installer'),
         ('requested', None, 'generate a REQUESTED file'),
         ('no-requested', None, 'do not generate a REQUESTED file'),
-        ('no-dist-record', None, 'do not generate a RECORD file'),
+        ('no-distinfo-record', None, 'do not generate a RECORD file'),
     ]
 
     boolean_options = [
diff --git a/src/distutils2/tests/support.py b/src/distutils2/tests/support.py
--- a/src/distutils2/tests/support.py
+++ b/src/distutils2/tests/support.py
@@ -75,9 +75,9 @@
             if os.path.exists(file_):
                 os.remove(file_)
 
-    def mktempfile(self):
+    def mktempfile(self, *args, **kwargs):
         """Create a temporary file that will be cleaned up."""
-        tempfile_ = tempfile.NamedTemporaryFile()
+        tempfile_ = tempfile.NamedTemporaryFile(*args, **kwargs)
         self.tempfiles.append(tempfile_.name)
         return tempfile_
 
diff --git a/src/distutils2/tests/test_install_distinfo.py b/src/distutils2/tests/test_install_distinfo.py
new file mode 100644
--- /dev/null
+++ b/src/distutils2/tests/test_install_distinfo.py
@@ -0,0 +1,198 @@
+"""Tests for ``distutils2.command.install_distinfo``. """
+
+import sys
+import os
+import hashlib
+import csv
+
+from distutils2.command.install_distinfo import install_distinfo
+from distutils2.tests import support
+from distutils2.tests.support import unittest
+from distutils2.core import Command
+from distutils2.metadata import DistributionMetadata
+
+
+class DummyInstallCmd(Command):
+
+    def __init__(self, dist=None):
+        self.outputs = []
+        self.distribution = dist
+
+    def __getattr__(self, name):
+            return None
+
+    def ensure_finalized(self):
+        pass
+
+    def get_outputs(self):
+        return self.outputs + \
+               self.get_finalized_command('install_distinfo').get_outputs()
+
+
+class InstallDistinfoTestCase(support.TempdirManager,
+                              support.LoggingSilencer,
+                              support.EnvironGuard,
+                              unittest.TestCase):
+
+    checkLists = lambda self, x, y: self.assertListEqual(sorted(x), sorted(y))
+
+    def test_empty_install(self):
+        pkg_dir, dist = self.create_dist(name='foo',
+                                         version='1.0')
+        install_dir = self.mkdtemp()
+
+        install = DummyInstallCmd(dist)
+        dist.command_obj['install'] = install
+
+        cmd = install_distinfo(dist)
+        dist.command_obj['install_distinfo'] = cmd
+
+        cmd.initialize_options()
+        cmd.distinfo_dir = install_dir
+        cmd.ensure_finalized()
+        cmd.run()
+
+        self.checkLists(os.listdir(install_dir), ['foo-1.0.dist-info'])
+
+        dist_info = os.path.join(install_dir, 'foo-1.0.dist-info')
+        self.checkLists(os.listdir(dist_info),
+                        ['METADATA', 'RECORD', 'REQUESTED', 'INSTALLER'])
+        self.assertEqual(open(os.path.join(dist_info, 'INSTALLER')).read(),
+                         'distutils')
+        self.assertEqual(open(os.path.join(dist_info, 'REQUESTED')).read(),
+                         '')
+        meta_path = os.path.join(dist_info, 'METADATA')
+        self.assertTrue(DistributionMetadata(path=meta_path).check())
+
+    def test_installer(self):
+        pkg_dir, dist = self.create_dist(name='foo',
+                                         version='1.0')
+        install_dir = self.mkdtemp()
+
+        install = DummyInstallCmd(dist)
+        dist.command_obj['install'] = install
+
+        cmd = install_distinfo(dist)
+        dist.command_obj['install_distinfo'] = cmd
+
+        cmd.initialize_options()
+        cmd.distinfo_dir = install_dir
+        cmd.installer = 'bacon-python'
+        cmd.ensure_finalized()
+        cmd.run()
+
+        dist_info = os.path.join(install_dir, 'foo-1.0.dist-info')
+        self.assertEqual(open(os.path.join(dist_info, 'INSTALLER')).read(),
+                         'bacon-python')
+
+    def test_requested(self):
+        pkg_dir, dist = self.create_dist(name='foo',
+                                         version='1.0')
+        install_dir = self.mkdtemp()
+
+        install = DummyInstallCmd(dist)
+        dist.command_obj['install'] = install
+
+        cmd = install_distinfo(dist)
+        dist.command_obj['install_distinfo'] = cmd
+
+        cmd.initialize_options()
+        cmd.distinfo_dir = install_dir
+        cmd.requested = False
+        cmd.ensure_finalized()
+        cmd.run()
+
+        dist_info = os.path.join(install_dir, 'foo-1.0.dist-info')
+        self.checkLists(os.listdir(dist_info),
+                        ['METADATA', 'RECORD', 'INSTALLER'])
+
+    def test_no_record(self):
+        pkg_dir, dist = self.create_dist(name='foo',
+                                         version='1.0')
+        install_dir = self.mkdtemp()
+
+        install = DummyInstallCmd(dist)
+        dist.command_obj['install'] = install
+
+        cmd = install_distinfo(dist)
+        dist.command_obj['install_distinfo'] = cmd
+
+        cmd.initialize_options()
+        cmd.distinfo_dir = install_dir
+        cmd.no_distinfo_record = True
+        cmd.ensure_finalized()
+        cmd.run()
+
+        dist_info = os.path.join(install_dir, 'foo-1.0.dist-info')
+        self.checkLists(os.listdir(dist_info),
+                        ['METADATA', 'REQUESTED', 'INSTALLER'])
+
+    def test_record(self):
+        pkg_dir, dist = self.create_dist(name='foo',
+                                         version='1.0')
+        install_dir = self.mkdtemp()
+
+        install = DummyInstallCmd(dist)
+        dist.command_obj['install'] = install
+
+        fake_dists = os.path.join(os.path.dirname(__file__), '..',
+                                  '_backport', 'tests', 'fake_dists')
+        fake_dists = os.path.realpath(fake_dists)
+
+        # for testing, we simply add all files from _backport's fake_dists
+        dirs = []
+        for dir in os.listdir(fake_dists):
+                full_path = os.path.join(fake_dists, dir)
+                if not dir.endswith(('.egg', '.egg-info', '.dist-info')) \
+                   and os.path.isdir(full_path):
+                        dirs.append(full_path)
+
+        for dir in dirs:
+            for (path, subdirs, files) in os.walk(dir):
+                install.outputs += [os.path.join(path, f) for f in files]
+                install.outputs += [os.path.join('path', f + 'c')
+                                    for f in files if f.endswith('.py')]
+
+
+        cmd = install_distinfo(dist)
+        dist.command_obj['install_distinfo'] = cmd
+
+        cmd.initialize_options()
+        cmd.distinfo_dir = install_dir
+        cmd.ensure_finalized()
+        cmd.run()
+
+        dist_info = os.path.join(install_dir, 'foo-1.0.dist-info')
+
+        expected = []
+        for f in install.get_outputs():
+            if f.endswith('.pyc') or \
+               f == os.path.join(install_dir, 'foo-1.0.dist-info', 'RECORD'):
+                expected.append([f, '', ''])
+            else:
+                size = os.path.getsize(f)
+                md5 = hashlib.md5()
+                md5.update(open(f).read())
+                hash = md5.hexdigest()
+                expected.append([f, hash, str(size)])
+
+        parsed = []
+        f = open(os.path.join(dist_info, 'RECORD'), 'rb')
+        try:
+            reader = csv.reader(f, delimiter=',',
+                                   lineterminator=os.linesep,
+                                   quotechar='"')
+            parsed = list(reader)
+        finally:
+            f.close()
+
+        self.maxDiff = None
+        self.checkLists(parsed, expected)
+
+
+def test_suite():
+    return unittest.makeSuite(InstallDistinfoTestCase)
+
+
+if __name__ == "__main__":
+    unittest.main(defaultTest="test_suite")

--
Repository URL: http://hg.python.org/distutils2


More information about the Python-checkins mailing list