PageRenderTime 426ms CodeModel.GetById 181ms app.highlight 88ms RepoModel.GetById 154ms app.codeStats 0ms

/Lib/distutils/tests/test_dist.py

http://unladen-swallow.googlecode.com/
Python | 293 lines | 260 code | 20 blank | 13 comment | 0 complexity | 8dd2ca1ab80ce19c5498613f2d54bda6 MD5 | raw file
  1# -*- coding: latin-1 -*-
  2
  3"""Tests for distutils.dist."""
  4
  5import distutils.cmd
  6import distutils.dist
  7import os
  8import StringIO
  9import sys
 10import unittest
 11import warnings
 12
 13from test.test_support import TESTFN
 14
 15
 16class test_dist(distutils.cmd.Command):
 17    """Sample distutils extension command."""
 18
 19    user_options = [
 20        ("sample-option=", "S", "help text"),
 21        ]
 22
 23    def initialize_options(self):
 24        self.sample_option = None
 25
 26
 27class TestDistribution(distutils.dist.Distribution):
 28    """Distribution subclasses that avoids the default search for
 29    configuration files.
 30
 31    The ._config_files attribute must be set before
 32    .parse_config_files() is called.
 33    """
 34
 35    def find_config_files(self):
 36        return self._config_files
 37
 38
 39class DistributionTestCase(unittest.TestCase):
 40
 41    def setUp(self):
 42        self.argv = sys.argv[:]
 43        del sys.argv[1:]
 44
 45    def tearDown(self):
 46        sys.argv[:] = self.argv
 47
 48    def create_distribution(self, configfiles=()):
 49        d = TestDistribution()
 50        d._config_files = configfiles
 51        d.parse_config_files()
 52        d.parse_command_line()
 53        return d
 54
 55    def test_command_packages_unspecified(self):
 56        sys.argv.append("build")
 57        d = self.create_distribution()
 58        self.assertEqual(d.get_command_packages(), ["distutils.command"])
 59
 60    def test_command_packages_cmdline(self):
 61        from distutils.tests.test_dist import test_dist
 62        sys.argv.extend(["--command-packages",
 63                         "foo.bar,distutils.tests",
 64                         "test_dist",
 65                         "-Ssometext",
 66                         ])
 67        d = self.create_distribution()
 68        # let's actually try to load our test command:
 69        self.assertEqual(d.get_command_packages(),
 70                         ["distutils.command", "foo.bar", "distutils.tests"])
 71        cmd = d.get_command_obj("test_dist")
 72        self.assert_(isinstance(cmd, test_dist))
 73        self.assertEqual(cmd.sample_option, "sometext")
 74
 75    def test_command_packages_configfile(self):
 76        sys.argv.append("build")
 77        f = open(TESTFN, "w")
 78        try:
 79            print >>f, "[global]"
 80            print >>f, "command_packages = foo.bar, splat"
 81            f.close()
 82            d = self.create_distribution([TESTFN])
 83            self.assertEqual(d.get_command_packages(),
 84                             ["distutils.command", "foo.bar", "splat"])
 85
 86            # ensure command line overrides config:
 87            sys.argv[1:] = ["--command-packages", "spork", "build"]
 88            d = self.create_distribution([TESTFN])
 89            self.assertEqual(d.get_command_packages(),
 90                             ["distutils.command", "spork"])
 91
 92            # Setting --command-packages to '' should cause the default to
 93            # be used even if a config file specified something else:
 94            sys.argv[1:] = ["--command-packages", "", "build"]
 95            d = self.create_distribution([TESTFN])
 96            self.assertEqual(d.get_command_packages(), ["distutils.command"])
 97
 98        finally:
 99            os.unlink(TESTFN)
100
101    def test_write_pkg_file(self):
102        # Check DistributionMetadata handling of Unicode fields
103        my_file = os.path.join(os.path.dirname(__file__), 'f')
104        klass = distutils.dist.Distribution
105
106        dist = klass(attrs={'author': u'Mister Café',
107                            'name': 'my.package',
108                            'maintainer': u'Café Junior',
109                            'description': u'Café torréfié',
110                            'long_description': u'Héhéhé'})
111
112
113        # let's make sure the file can be written
114        # with Unicode fields. they are encoded with
115        # PKG_INFO_ENCODING
116        try:
117            dist.metadata.write_pkg_file(open(my_file, 'w'))
118        finally:
119            if os.path.exists(my_file):
120                os.remove(my_file)
121
122        # regular ascii is of course always usable
123        dist = klass(attrs={'author': 'Mister Cafe',
124                            'name': 'my.package',
125                            'maintainer': 'Cafe Junior',
126                            'description': 'Cafe torrefie',
127                            'long_description': 'Hehehe'})
128
129        try:
130            dist.metadata.write_pkg_file(open(my_file, 'w'))
131        finally:
132            if os.path.exists(my_file):
133                os.remove(my_file)
134
135    def test_empty_options(self):
136        # an empty options dictionary should not stay in the
137        # list of attributes
138        klass = distutils.dist.Distribution
139
140        # catching warnings
141        warns = []
142        def _warn(msg):
143            warns.append(msg)
144
145        old_warn = warnings.warn
146        warnings.warn = _warn
147        try:
148            dist = klass(attrs={'author': 'xxx',
149                                'name': 'xxx',
150                                'version': 'xxx',
151                                'url': 'xxxx',
152                                'options': {}})
153        finally:
154            warnings.warn = old_warn
155
156        self.assertEquals(len(warns), 0)
157
158class MetadataTestCase(unittest.TestCase):
159
160    def test_simple_metadata(self):
161        attrs = {"name": "package",
162                 "version": "1.0"}
163        dist = distutils.dist.Distribution(attrs)
164        meta = self.format_metadata(dist)
165        self.assert_("Metadata-Version: 1.0" in meta)
166        self.assert_("provides:" not in meta.lower())
167        self.assert_("requires:" not in meta.lower())
168        self.assert_("obsoletes:" not in meta.lower())
169
170    def test_provides(self):
171        attrs = {"name": "package",
172                 "version": "1.0",
173                 "provides": ["package", "package.sub"]}
174        dist = distutils.dist.Distribution(attrs)
175        self.assertEqual(dist.metadata.get_provides(),
176                         ["package", "package.sub"])
177        self.assertEqual(dist.get_provides(),
178                         ["package", "package.sub"])
179        meta = self.format_metadata(dist)
180        self.assert_("Metadata-Version: 1.1" in meta)
181        self.assert_("requires:" not in meta.lower())
182        self.assert_("obsoletes:" not in meta.lower())
183
184    def test_provides_illegal(self):
185        self.assertRaises(ValueError,
186                          distutils.dist.Distribution,
187                          {"name": "package",
188                           "version": "1.0",
189                           "provides": ["my.pkg (splat)"]})
190
191    def test_requires(self):
192        attrs = {"name": "package",
193                 "version": "1.0",
194                 "requires": ["other", "another (==1.0)"]}
195        dist = distutils.dist.Distribution(attrs)
196        self.assertEqual(dist.metadata.get_requires(),
197                         ["other", "another (==1.0)"])
198        self.assertEqual(dist.get_requires(),
199                         ["other", "another (==1.0)"])
200        meta = self.format_metadata(dist)
201        self.assert_("Metadata-Version: 1.1" in meta)
202        self.assert_("provides:" not in meta.lower())
203        self.assert_("Requires: other" in meta)
204        self.assert_("Requires: another (==1.0)" in meta)
205        self.assert_("obsoletes:" not in meta.lower())
206
207    def test_requires_illegal(self):
208        self.assertRaises(ValueError,
209                          distutils.dist.Distribution,
210                          {"name": "package",
211                           "version": "1.0",
212                           "requires": ["my.pkg (splat)"]})
213
214    def test_obsoletes(self):
215        attrs = {"name": "package",
216                 "version": "1.0",
217                 "obsoletes": ["other", "another (<1.0)"]}
218        dist = distutils.dist.Distribution(attrs)
219        self.assertEqual(dist.metadata.get_obsoletes(),
220                         ["other", "another (<1.0)"])
221        self.assertEqual(dist.get_obsoletes(),
222                         ["other", "another (<1.0)"])
223        meta = self.format_metadata(dist)
224        self.assert_("Metadata-Version: 1.1" in meta)
225        self.assert_("provides:" not in meta.lower())
226        self.assert_("requires:" not in meta.lower())
227        self.assert_("Obsoletes: other" in meta)
228        self.assert_("Obsoletes: another (<1.0)" in meta)
229
230    def test_obsoletes_illegal(self):
231        self.assertRaises(ValueError,
232                          distutils.dist.Distribution,
233                          {"name": "package",
234                           "version": "1.0",
235                           "obsoletes": ["my.pkg (splat)"]})
236
237    def format_metadata(self, dist):
238        sio = StringIO.StringIO()
239        dist.metadata.write_pkg_file(sio)
240        return sio.getvalue()
241
242    def test_custom_pydistutils(self):
243        # fixes #2166
244        # make sure pydistutils.cfg is found
245        old = {}
246        for env in ('HOME', 'HOMEPATH', 'HOMEDRIVE'):
247            value = os.environ.get(env)
248            old[env] = value
249            if value is not None:
250                del os.environ[env]
251
252        if os.name == 'posix':
253            user_filename = ".pydistutils.cfg"
254        else:
255            user_filename = "pydistutils.cfg"
256
257        curdir = os.path.dirname(__file__)
258        user_filename = os.path.join(curdir, user_filename)
259        f = open(user_filename, 'w')
260        f.write('.')
261        f.close()
262
263        try:
264            dist = distutils.dist.Distribution()
265
266            # linux-style
267            if sys.platform in ('linux', 'darwin'):
268                os.environ['HOME'] = curdir
269                files = dist.find_config_files()
270                self.assert_(user_filename in files)
271
272            # win32-style
273            if sys.platform == 'win32':
274                # home drive should be found
275                os.environ['HOME'] = curdir
276                files = dist.find_config_files()
277                self.assert_(user_filename in files,
278                             '%r not found in %r' % (user_filename, files))
279        finally:
280            for key, value in old.items():
281                if value is None:
282                    continue
283                os.environ[key] = value
284            os.remove(user_filename)
285
286def test_suite():
287    suite = unittest.TestSuite()
288    suite.addTest(unittest.makeSuite(DistributionTestCase))
289    suite.addTest(unittest.makeSuite(MetadataTestCase))
290    return suite
291
292if __name__ == "__main__":
293    unittest.main(defaultTest="test_suite")