Debian Codegraph @

tests/test_database.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2012-2013 The Python Software Foundation.
4 # See LICENSE.txt and CONTRIBUTORS.txt.
5 #
6 from __future__ import unicode_literals
7
8 import base64
9 import io
10 import os
11 import hashlib
12 import logging
13 import random
14 import re
15 import shutil
16 import sys
17 import tempfile
18
19 from compat import unittest
20
21 from distlib import DistlibException
22 from distlib.compat import text_type, StringIO
23 from distlib.metadata import Metadata, METADATA_FILENAME, LEGACY_METADATA_FILENAME
24 from distlib.database import (InstalledDistribution, EggInfoDistribution, BaseInstalledDistribution, EXPORTS_FILENAME,
25 DistributionPath, make_graph, get_required_dists, get_dependent_dists)
26 from distlib.util import get_resources_dests, CSVReader, read_exports
27
28 from test_util import GlobTestCaseBase
29 from support import LoggingCatcher, requires_zlib, DistlibTestCase
30
31 logger = logging.getLogger(__name__)
32
33 # TODO Add a test for getting a distribution provided by another distribution
34 # TODO Add a test for absolute path RECORD items (e.g. /etc/myapp/config.ini)
35 # TODO Add tests from the former pep376 project (zipped site-packages, etc.)
36
37
38 class FakeDistsMixin(object):
39
40 def setUp(self):
41 super(FakeDistsMixin, self).setUp()
42
43 # make a copy that we can write into for our fake installed
44 # distributions
45 tmpdir = tempfile.mkdtemp()
46 self.addCleanup(shutil.rmtree, tmpdir)
47 self.fake_dists_path = os.path.realpath(os.path.join(tmpdir, 'fake_dists'))
48 fake_dists_src = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fake_dists'))
49 shutil.copytree(fake_dists_src, self.fake_dists_path)
50 # XXX ugly workaround: revert copystat calls done by shutil behind our
51 # back (to avoid getting a read-only copy of a read-only file). we
52 # could pass a custom copy_function to change the mode of files, but
53 # shutil gives no control over the mode of directories :(
54 # see http://bugs.python.org/issue1666318
55 for root, dirs, files in os.walk(self.fake_dists_path):
56 os.chmod(root, 0o755)
57 for f in files:
58 os.chmod(os.path.join(root, f), 0o644)
59 for d in dirs:
60 os.chmod(os.path.join(root, d), 0o755)
61
62
63 class CommonDistributionTests(FakeDistsMixin):
64 """Mixin used to test the interface common to InstalledDistribution
65 and EggInfoDistribution classes.
66
67 Derived classes define cls, sample_dist, dirs and records. These
68 attributes are used in test methods. See source code for details.
69 """
70
71 def _get_dist_path(self, distdir):
72 here = os.path.abspath(os.path.dirname(__file__))
73 return os.path.join(here, 'fake_dists', distdir)
74
75 def test_instantiation(self):
76 # check that useful attributes are here
77 name, version, distdir = self.sample_dist
78 dist_path = self._get_dist_path(distdir)
79 dist = self.dist = self.cls(dist_path)
80 self.assertEqual(dist.path, dist_path)
81 self.assertEqual(dist.name, name)
82 self.assertEqual(dist.metadata.name, name)
83 self.assertIsInstance(dist.metadata, Metadata)
84 self.assertEqual(dist.version, version)
85 self.assertEqual(dist.metadata.version, version)
86
87 @requires_zlib
88 def test_repr(self):
89 dist = self.cls(self.dirs[0])
90 # just check that the class name is in the repr
91 self.assertIn(self.cls.__name__, repr(dist))
92
93 @requires_zlib
94 def test_str(self):
95 name, version, distdir = self.sample_dist
96 dist = self.cls(self._get_dist_path(distdir))
97 self.assertEqual(name, dist.name)
98 # Sanity test: dist.name is unicode,
99 # but str output contains no u prefix.
100 self.assertIsInstance(dist.name, text_type)
101 self.assertEqual(version, dist.version)
102 self.assertEqual(str(dist), self.expected_str_output)
103
104 @requires_zlib
105 def test_comparison(self):
106 # tests for __eq__ and __hash__
107 dist = self.cls(self.dirs[0])
108 dist2 = self.cls(self.dirs[0])
109 dist3 = self.cls(self.dirs[1])
110 self.assertIn(dist, {dist: True})
111 self.assertEqual(dist, dist)
112
113 self.assertIsNot(dist, dist2)
114 self.assertEqual(dist, dist2)
115 self.assertNotEqual(dist, dist3)
116 self.assertNotEqual(dist, ())
117
118 def test_list_installed_files(self):
119 for dir_ in self.dirs:
120 dist = self.cls(dir_)
121 for path, hash, size in dist.list_installed_files():
122 record_data = self.records[dist.path]
123 self.assertIn(path, record_data)
124 self.assertEqual(hash, record_data[path][0])
125 self.assertEqual(size, record_data[path][1])
126
127 def test_hash(self):
128 datalen = random.randrange(0, 500)
129 data = os.urandom(datalen)
130 for dir_ in self.dirs:
131 dist = self.cls(dir_)
132 for hasher in ('sha1', 'sha224', 'sha384', 'sha256', 'sha512', None):
133 dist.hasher = hasher
134 actual = dist.get_hash(data)
135 if hasher is None:
136 digester = hashlib.md5(data)
137 else:
138 digester = getattr(hashlib, hasher)(data)
139 digest = digester.digest()
140 digest = base64.urlsafe_b64encode(digest).rstrip(b'=')
141 digest = digest.decode('ascii')
142 if hasher is None:
143 expected = digest
144 else:
145 expected = '%s=%s' % (hasher, digest)
146 self.assertEqual(actual, expected)
147
148
149 class TestDistribution(CommonDistributionTests, DistlibTestCase):
150
151 cls = InstalledDistribution
152 sample_dist = 'choxie', '2.0.0.9', 'choxie-2.0.0.9.dist-info'
153 expected_str_output = 'choxie 2.0.0.9'
154
155 def setUp(self):
156
157 def get_files(location):
158 for path in ('REQUESTED', 'INSTALLER', LEGACY_METADATA_FILENAME, METADATA_FILENAME, EXPORTS_FILENAME):
159 p = os.path.join(location + '.dist-info', path)
160 if os.path.exists(p):
161 yield p
162 for path, dirs, files in os.walk(location):
163 for f in files:
164 yield os.path.join(path, f)
165
166 super(TestDistribution, self).setUp()
167 self.dirs = [
168 os.path.join(self.fake_dists_path, f) for f in os.listdir(self.fake_dists_path) if f.endswith('.dist-info')
169 ]
170
171 self.records = {}
172 for distinfo_dir in self.dirs:
173 dist_location = distinfo_dir.replace('.dist-info', '')
174 record_file = os.path.join(distinfo_dir, 'RECORD')
175
176 # Write the files using write_installed_files.
177 # list_installed_files should read and match.
178 dist = self.cls(distinfo_dir)
179 prefix = os.path.dirname(dist_location)
180 dist.write_installed_files(get_files(dist_location), prefix)
181
182 with CSVReader(path=record_file) as record_reader:
183 record_data = {}
184 for row in record_reader:
185 if row == []:
186 continue
187 path, hash, size = (row[:] + [None for i in range(len(row), 3)])
188 record_data[path] = hash, size
189 self.records[distinfo_dir] = record_data
190
191 def test_instantiation(self):
192 super(TestDistribution, self).test_instantiation()
193 self.assertIsInstance(self.dist.requested, bool)
194
195 def test_get_distinfo_file(self):
196 # Test the retrieval of dist-info file objects.
197 distinfo_name = 'choxie-2.0.0.9'
198 other_distinfo_name = 'grammar-1.0a4'
199 distinfo_dir = os.path.join(self.fake_dists_path, distinfo_name + '.dist-info')
200 dist = InstalledDistribution(distinfo_dir)
201 # Test for known good file matches
202 distinfo_files = [
203 # Relative paths
204 'INSTALLER',
205 METADATA_FILENAME,
206 # Absolute paths
207 os.path.join(distinfo_dir, 'RECORD'),
208 os.path.join(distinfo_dir, 'REQUESTED'),
209 ]
210
211 for distfile in distinfo_files:
212 value = dist.get_distinfo_file(distfile)
213 self.assertTrue(os.path.isfile(value))
214 self.assertEqual(value, os.path.join(distinfo_dir, distfile))
215
216 # Test an absolute path that is part of another distributions dist-info
217 other_distinfo_file = os.path.join(self.fake_dists_path, other_distinfo_name + '.dist-info', 'REQUESTED')
218 self.assertRaises(DistlibException, dist.get_distinfo_file, other_distinfo_file)
219 # Test for a file that should not exist
220 self.assertRaises(DistlibException, dist.get_distinfo_file, 'MAGICFILE')
221
222 def test_list_distinfo_files(self):
223 distinfo_name = 'towel_stuff-0.1'
224 distinfo_dir = os.path.join(self.fake_dists_path, distinfo_name + '.dist-info')
225 dist = InstalledDistribution(distinfo_dir)
226 # Test for the iteration of the raw path
227 distinfo_files = [os.path.join(distinfo_dir, filename) for filename in os.listdir(distinfo_dir)]
228 found = list(dist.list_distinfo_files())
229 base = self.fake_dists_path
230 for i, p in enumerate(found):
231 if not os.path.isabs(p):
232 found[i] = os.path.join(base, p)
233 self.assertEqual(sorted(found), sorted(distinfo_files))
234 # Test for the iteration of local absolute paths
235 distinfo_files = [os.path.join(sys.prefix, distinfo_dir, path) for path in distinfo_files]
236 found = sorted(dist.list_distinfo_files())
237 if os.sep != '/':
238 self.assertNotIn('/', found[0])
239 self.assertIn(os.sep, found[0])
240 self.assertEqual(found, sorted(distinfo_files))
241
242 def test_get_resources_path(self):
243 distinfo_name = 'babar-0.1'
244 distinfo_dir = os.path.join(self.fake_dists_path, distinfo_name + '.dist-info')
245 dist = InstalledDistribution(distinfo_dir)
246 resource_path = dist.get_resource_path('babar.png')
247 self.assertEqual(resource_path, 'babar.png')
248 self.assertRaises(KeyError, dist.get_resource_path, 'notexist')
249
250 def test_check_installed_files(self):
251 for dir_ in self.dirs:
252 dist = self.cls(dir_)
253 mismatches = dist.check_installed_files()
254 self.assertEqual(mismatches, [])
255 # pick a non-empty file at random and change its contents
256 # but not its size. Check the failure returned,
257 # then restore the file.
258 files = [f for f in dist.list_installed_files() if f[-1] not in ('', '0')]
259 bad_file = random.choice(files)
260 bad_file_name = bad_file[0]
261 if not os.path.isabs(bad_file_name):
262 base = os.path.dirname(dir_)
263 bad_file_name = os.path.join(base, bad_file_name)
264 with open(bad_file_name, 'rb') as f:
265 data = f.read()
266 bad_data = bytes(bytearray(reversed(data)))
267 bad_hash = dist.get_hash(bad_data)
268 with open(bad_file_name, 'wb') as f:
269 f.write(bad_data)
270 mismatches = dist.check_installed_files()
271 self.assertEqual(mismatches, [(bad_file_name, 'hash', bad_file[1], bad_hash)])
272 # now truncate the file by one byte and see what's returned
273 with open(bad_file_name, 'wb') as f:
274 f.write(bad_data[:-1])
275 bad_size = str(len(bad_data) - 1)
276 mismatches = dist.check_installed_files()
277 self.assertEqual(mismatches, [(bad_file_name, 'size', bad_file[2], bad_size)])
278
279 # now remove the file and see what's returned
280 os.remove(bad_file_name)
281 mismatches = dist.check_installed_files()
282 self.assertEqual(mismatches, [(bad_file_name, 'exists', True, False)])
283
284 # restore the file
285 with open(bad_file_name, 'wb') as f:
286 f.write(data)
287
288
289 class TestEggInfoDistribution(CommonDistributionTests, LoggingCatcher, DistlibTestCase):
290
291 cls = EggInfoDistribution
292 sample_dist = 'bacon', '0.1', 'bacon-0.1.egg-info'
293 expected_str_output = 'bacon 0.1'
294
295 def setUp(self):
296 super(TestEggInfoDistribution, self).setUp()
297
298 self.dirs = [
299 os.path.join(self.fake_dists_path, f) for f in os.listdir(self.fake_dists_path)
300 if f.endswith('.egg') or f.endswith('.egg-info')
301 ]
302
303 self.records = {}
304 for egginfo_dir in self.dirs:
305 # dist_location = egginfo_dir.replace('.egg-info', '')
306 record_file = os.path.join(egginfo_dir, 'installed-files.txt')
307
308 # dist = self.cls(egginfo_dir)
309 # prefix = os.path.dirname(dist_location)
310 # dist.write_installed_files(get_files(dist_location), prefix)
311
312 record_data = {}
313 if os.path.exists(record_file):
314 with open(record_file) as fp:
315 for line in fp:
316 line = line.strip()
317 if line == './':
318 break
319 record_data[line] = None, None
320 self.records[egginfo_dir] = record_data
321
322 @unittest.skip('not implemented yet')
323 def test_list_installed_files(self):
324 # EggInfoDistribution defines list_installed_files but there is no
325 # test for it yet; someone needs to add a file with the list of
326 # installed files for one of the egg fake dists and write the support
327 # code to populate self.records (and then delete this method)
328 pass
329
330
331 class TestDatabase(LoggingCatcher, FakeDistsMixin, DistlibTestCase):
332
333 def setUp(self):
334 super(TestDatabase, self).setUp()
335 sys.path.insert(0, self.fake_dists_path)
336 self.addCleanup(sys.path.remove, self.fake_dists_path)
337
338 def test_caches(self):
339 # sanity check for internal caches
340 d = DistributionPath()
341 for name in ('_cache', '_cache_egg'):
342 self.assertEqual(getattr(d, name).name, {})
343 self.assertEqual(getattr(d, name).path, {})
344
345 def test_distinfo_dirname(self):
346 # Given a name and a version, we expect the distinfo_dirname function
347 # to return a standard distribution information directory name.
348
349 items = [
350 # (name, version, standard_dirname)
351 # Test for a very simple single word name and decimal version
352 # number
353 ('docutils', '0.5', 'docutils-0.5.dist-info'),
354 # Test for another except this time with a '-' in the name, which
355 # needs to be transformed during the name lookup
356 ('python-ldap', '2.5', 'python_ldap-2.5.dist-info'),
357 # Test for both '-' in the name and a funky version number
358 ('python-ldap', '2.5 a---5', 'python_ldap-2.5 a---5.dist-info'),
359 ]
360
361 # Loop through the items to validate the results
362 for name, version, standard_dirname in items:
363 dirname = DistributionPath.distinfo_dirname(name, version)
364 self.assertEqual(dirname, standard_dirname)
365
366 @requires_zlib
367 def test_get_distributions(self):
368 # Lookup all distributions found in the ``sys.path``.
369 # This test could potentially pick up other installed distributions
370 non_egg_dists = [('grammar', '1.0a4'), ('choxie', '2.0.0.9'), ('towel-stuff', '0.1'), ('babar', '0.1')]
371 egg_dists = [('bacon', '0.1'), ('cheese', '2.0.2'), ('coconuts-aster', '10.3'), ('banana', '0.4'),
372 ('strawberry', '0.6'), ('truffles', '5.0'), ('nut', 'funkyversion')]
373
374 all_dists = non_egg_dists + egg_dists
375
376 d = DistributionPath()
377 ed = DistributionPath(include_egg=True)
378
379 cases = ((d, non_egg_dists, InstalledDistribution), (ed, all_dists, BaseInstalledDistribution))
380
381 fake_dists_path = self.fake_dists_path
382 for enabled in (True, False):
383 if not enabled:
384 d.cache_enabled = False
385 ed.cache_enabled = False
386 d.clear_cache()
387 ed.clear_cache()
388
389 for distset, fake_dists, allowed_class in cases:
390 found_dists = []
391
392 # Verify the fake dists have been found.
393 dists = list(distset.get_distributions())
394 for dist in dists:
395 self.assertIsInstance(dist, allowed_class)
396 if (dist.name in dict(fake_dists) and dist.path.startswith(fake_dists_path)):
397 found_dists.append((dist.name, dist.version))
398 else:
399 # check that it doesn't find anything more than this
400 self.assertFalse(dist.path.startswith(fake_dists_path))
401 # otherwise we don't care what other dists are found
402
403 # Finally, test that we found all that we were looking for
404 self.assertEqual(sorted(found_dists), sorted(fake_dists))
405
406 @requires_zlib
407 def test_get_distribution(self):
408 # Test for looking up a distribution by name.
409 # Test the lookup of the towel-stuff distribution
410 name = 'towel-stuff' # Note: This is different from the directory name
411
412 d = DistributionPath()
413 ed = DistributionPath(include_egg=True)
414
415 # Lookup the distribution
416 dist = d.get_distribution(name)
417 self.assertIsInstance(dist, InstalledDistribution)
418 self.assertEqual(dist.name, name)
419
420 # Verify that an unknown distribution returns None
421 self.assertIsNone(d.get_distribution('bogus'))
422
423 # Verify partial name matching doesn't work
424 self.assertIsNone(d.get_distribution('towel'))
425
426 # Verify that it does not find egg-info distributions, when not
427 # instructed to
428 self.assertIsNone(d.get_distribution('bacon'))
429 self.assertIsNone(d.get_distribution('cheese'))
430 self.assertIsNone(d.get_distribution('strawberry'))
431 self.assertIsNone(d.get_distribution('banana'))
432
433 # Now check that it works well in both situations, when egg-info
434 # is a file and directory respectively.
435
436 for name in ('cheese', 'bacon', 'banana', 'strawberry'):
437 dist = ed.get_distribution(name)
438 self.assertIsInstance(dist, EggInfoDistribution)
439 self.assertEqual(dist.name, name)
440
441 @requires_zlib
442 def test_provides(self):
443 # Test for looking up distributions by what they provide
444 checkLists = lambda x, y: self.assertEqual(sorted(x), sorted(y))
445
446 d = DistributionPath()
447 ed = DistributionPath(include_egg=True)
448
449 test_list = [dist.name for dist in d.provides_distribution('truffles')]
450 checkLists(test_list, ['choxie', 'towel-stuff'])
451
452 test_list = [dist.name for dist in d.provides_distribution('truffles', '1.0')]
453 checkLists(test_list, ['choxie', 'towel-stuff'])
454
455 test_list = [dist.name for dist in ed.provides_distribution('truffles', '1.0')]
456 checkLists(test_list, ['choxie', 'cheese', 'towel-stuff'])
457
458 test_list = [dist.name for dist in d.provides_distribution('truffles', '1.1.2')]
459 checkLists(test_list, ['towel-stuff'])
460
461 test_list = [dist.name for dist in d.provides_distribution('truffles', '1.1')]
462 checkLists(test_list, ['towel-stuff'])
463
464 test_list = [dist.name for dist in d.provides_distribution('truffles', '!=1.1,<=2.0')]
465 checkLists(test_list, ['choxie', 'towel-stuff'])
466
467 test_list = [dist.name for dist in ed.provides_distribution('truffles', '!=1.1,<=2.0')]
468 checkLists(test_list, ['choxie', 'bacon', 'cheese', 'towel-stuff'])
469
470 test_list = [dist.name for dist in d.provides_distribution('truffles', '>1.0')]
471 checkLists(test_list, ['towel-stuff'])
472
473 test_list = [dist.name for dist in d.provides_distribution('truffles', '>1.5')]
474 checkLists(test_list, [])
475
476 test_list = [dist.name for dist in ed.provides_distribution('truffles', '>1.5')]
477 checkLists(test_list, ['bacon', 'truffles'])
478
479 test_list = [dist.name for dist in d.provides_distribution('truffles', '>=1.0')]
480 checkLists(test_list, ['choxie', 'towel-stuff'])
481
482 test_list = [dist.name for dist in ed.provides_distribution('strawberry', '0.6')]
483 checkLists(test_list, ['coconuts-aster', 'strawberry'])
484
485 test_list = [dist.name for dist in ed.provides_distribution('strawberry', '>=0.5')]
486 checkLists(test_list, ['coconuts-aster', 'strawberry'])
487
488 test_list = [dist.name for dist in ed.provides_distribution('strawberry', '>0.6')]
489 checkLists(test_list, [])
490
491 test_list = [dist.name for dist in ed.provides_distribution('banana', '0.4')]
492 checkLists(test_list, ['banana', 'coconuts-aster'])
493
494 test_list = [dist.name for dist in ed.provides_distribution('banana', '>=0.3')]
495 checkLists(test_list, ['banana', 'coconuts-aster'])
496
497 test_list = [dist.name for dist in ed.provides_distribution('banana', '!=0.4')]
498 checkLists(test_list, [])
499
500 @requires_zlib
501 def test_yield_distribution(self):
502 # tests the internal function _yield_distributions
503 checkLists = lambda x, y: self.assertEqual(sorted(x), sorted(y))
504
505 eggs = [('bacon', '0.1'), ('banana', '0.4'), ('strawberry', '0.6'), ('truffles', '5.0'), ('cheese', '2.0.2'),
506 ('coconuts-aster', '10.3'), ('nut', 'funkyversion')]
507 dists = [('choxie', '2.0.0.9'), ('grammar', '1.0a4'), ('towel-stuff', '0.1'), ('babar', '0.1')]
508
509 d = DistributionPath(include_egg=False)
510 d._include_dist = False
511 checkLists([], d._yield_distributions())
512
513 d = DistributionPath(include_egg=True)
514 d._include_dist = False
515 found = [(dist.name, dist.version) for dist in d._yield_distributions()
516 if dist.path.startswith(self.fake_dists_path)]
517 checkLists(eggs, found)
518
519 d = DistributionPath()
520 found = [(dist.name, dist.version) for dist in d._yield_distributions()
521 if dist.path.startswith(self.fake_dists_path)]
522 checkLists(dists, found)
523
524 d = DistributionPath(include_egg=True)
525 found = [(dist.name, dist.version) for dist in d._yield_distributions()
526 if dist.path.startswith(self.fake_dists_path)]
527 checkLists(dists + eggs, found)
528
529 def check_entry(self, entry, name, prefix, suffix, flags):
530 self.assertEqual(entry.name, name)
531 self.assertEqual(entry.prefix, prefix)
532 self.assertEqual(entry.suffix, suffix)
533 self.assertEqual(entry.flags, flags)
534
535 def test_read_exports(self):
536 d = DistributionPath().get_distribution('babar')
537 r = d.exports
538 self.assertIn('foo', r)
539 d = r['foo']
540 self.assertIn('bar', d)
541 self.check_entry(d['bar'], 'bar', 'baz', 'barbaz', ['a=10', 'b'])
542 self.assertIn('bar.baz', r)
543 d = r['bar.baz']
544 self.assertIn('foofoo', d)
545 self.check_entry(d['foofoo'], 'foofoo', 'baz.foo', 'bazbar', [])
546 self.assertIn('real', d)
547 e = d['real']
548 self.check_entry(e, 'real', 'cgi', 'print_directory', [])
549 if sys.version_info[:2] < (3, 12):
550 import cgi
551 self.assertIs(e.value, cgi.print_directory)
552
553 # See issue #78. Test reading an entry_points.txt with leading spaces
554
555 TEST_EXPORTS = b"""
556 [paste.server_runner]
557 main = waitress:serve_paste
558 [console_scripts]
559 waitress-serve = waitress.runner:run
560 """
561 with io.BytesIO(TEST_EXPORTS) as f:
562 exports = read_exports(f)
563 self.assertEqual(set(exports.keys()), set(['paste.server_runner', 'console_scripts']))
564
565 def test_exports_iteration(self):
566 d = DistributionPath()
567 expected = set((
568 ('bar', 'baz', 'barbaz', ('a=10', 'b')),
569 ('bar', 'crunchie', None, ()),
570 ('bar', 'towel', 'towel', ()),
571 ('baz', 'towel', 'beach_towel', ()),
572 ))
573 entries = list(d.get_exported_entries('foo'))
574 for e in entries:
575 t = e.name, e.prefix, e.suffix, tuple(e.flags)
576 self.assertIn(t, expected)
577 expected.remove(t)
578 self.assertFalse(expected) # nothing left
579 expected = set((
580 ('bar', 'baz', 'barbaz', ('a=10', 'b')),
581 ('bar', 'crunchie', None, ()),
582 ('bar', 'towel', 'towel', ()),
583 ))
584 entries = list(d.get_exported_entries('foo', 'bar'))
585 for e in entries:
586 t = e.name, e.prefix, e.suffix, tuple(e.flags)
587 self.assertIn(t, expected)
588 expected.remove(t)
589 self.assertFalse(expected) # nothing left
590
591 expected = set((
592 ('foofoo', 'baz.foo', 'bazbar', ()),
593 ('real', 'cgi', 'print_directory', ()),
594 ('foofoo', 'ferrero', 'rocher', ()),
595 ('foobar', 'hoopy', 'frood', ('dent', )),
596 ))
597 entries = list(d.get_exported_entries('bar.baz'))
598 for e in entries:
599 t = e.name, e.prefix, e.suffix, tuple(e.flags)
600 self.assertIn(t, expected)
601 expected.remove(t)
602 self.assertFalse(expected) # nothing left
603
604 def test_modules(self):
605 dp = DistributionPath(include_egg=True)
606 dist = dp.get_distribution('banana')
607 self.assertIsInstance(dist, EggInfoDistribution)
608 self.assertEqual(dist.modules, ['banana', 'cavendish'])
609
610
611 class DataFilesTestCase(GlobTestCaseBase):
612
613 def assertRulesMatch(self, rules, spec):
614 tempdir = self.build_files_tree(spec)
615 expected = self.clean_tree(spec)
616 result = get_resources_dests(tempdir, rules)
617 self.assertEqual(expected, result)
618
619 def clean_tree(self, spec):
620 files = {}
621 for path, value in spec.items():
622 if value is not None:
623 files[path] = value
624 return files
625
626 def test_simple_glob(self):
627 rules = [('', '*.tpl', '{data}')]
628 spec = {'coucou.tpl': '{data}/coucou.tpl', 'Donotwant': None}
629 self.assertRulesMatch(rules, spec)
630
631 def test_multiple_match(self):
632 rules = [('scripts', '*.bin', '{appdata}'), ('scripts', '*', '{appscript}')]
633 spec = {'scripts/script.bin': '{appscript}/script.bin', 'Babarlikestrawberry': None}
634 self.assertRulesMatch(rules, spec)
635
636 def test_set_match(self):
637 rules = [('scripts', '*.{bin,sh}', '{appscript}')]
638 spec = {
639 'scripts/script.bin': '{appscript}/script.bin',
640 'scripts/babar.sh': '{appscript}/babar.sh',
641 'Babarlikestrawberry': None
642 }
643 self.assertRulesMatch(rules, spec)
644
645 def test_set_match_multiple(self):
646 rules = [('scripts', 'script{s,}.{bin,sh}', '{appscript}')]
647 spec = {
648 'scripts/scripts.bin': '{appscript}/scripts.bin',
649 'scripts/script.sh': '{appscript}/script.sh',
650 'Babarlikestrawberry': None
651 }
652 self.assertRulesMatch(rules, spec)
653
654 def test_set_match_exclude(self):
655 rules = [('scripts', '*', '{appscript}'), ('', os.path.join('**', '*.sh'), None)]
656 spec = {
657 'scripts/scripts.bin': '{appscript}/scripts.bin',
658 'scripts/script.sh': None,
659 'Babarlikestrawberry': None
660 }
661 self.assertRulesMatch(rules, spec)
662
663 def test_glob_in_base(self):
664 rules = [('scrip*', '*.bin', '{appscript}')]
665 spec = {
666 'scripts/scripts.bin': '{appscript}/scripts.bin',
667 'scripouille/babar.bin': '{appscript}/babar.bin',
668 'scriptortu/lotus.bin': '{appscript}/lotus.bin',
669 'Babarlikestrawberry': None
670 }
671 self.assertRulesMatch(rules, spec)
672
673 def test_recursive_glob(self):
674 rules = [('', os.path.join('**', '*.bin'), '{binary}')]
675 spec = {
676 'binary0.bin': '{binary}/binary0.bin',
677 'scripts/binary1.bin': '{binary}/scripts/binary1.bin',
678 'scripts/bin/binary2.bin': '{binary}/scripts/bin/binary2.bin',
679 'you/kill/pandabear.guy': None
680 }
681 self.assertRulesMatch(rules, spec)
682
683 def test_final_example_glob(self):
684 rules = [
685 ('mailman/database/schemas/', '*', '{appdata}/schemas'),
686 ('', os.path.join('**', '*.tpl'), '{appdata}/templates'),
687 ('', os.path.join('developer-docs', '**', '*.txt'), '{doc}'),
688 ('', 'README', '{doc}'),
689 ('mailman/etc/', '*', '{config}'),
690 ('mailman/foo/', os.path.join('**', 'bar', '*.cfg'), '{config}/baz'),
691 ('mailman/foo/', os.path.join('**', '*.cfg'), '{config}/hmm'),
692 ('', 'some-new-semantic.sns', '{funky-crazy-category}'),
693 ]
694 spec = {
695 'README': '{doc}/README',
696 'some.tpl': '{appdata}/templates/some.tpl',
697 'some-new-semantic.sns': '{funky-crazy-category}/some-new-semantic.sns',
698 'mailman/database/mailman.db': None,
699 'mailman/database/schemas/blah.schema': '{appdata}/schemas/blah.schema',
700 'mailman/etc/my.cnf': '{config}/my.cnf',
701 'mailman/foo/some/path/bar/my.cfg': '{config}/hmm/some/path/bar/my.cfg',
702 'mailman/foo/some/path/other.cfg': '{config}/hmm/some/path/other.cfg',
703 'developer-docs/index.txt': '{doc}/developer-docs/index.txt',
704 'developer-docs/api/toc.txt': '{doc}/developer-docs/api/toc.txt',
705 }
706 self.maxDiff = None
707 self.assertRulesMatch(rules, spec)
708
709 def test_get_file(self):
710 # Create a fake dist
711 temp_site_packages = tempfile.mkdtemp()
712 self.addCleanup(shutil.rmtree, temp_site_packages)
713
714 dist_name = 'test'
715 dist_info = os.path.join(temp_site_packages, 'test-0.1.dist-info')
716 os.mkdir(dist_info)
717
718 metadata_path = os.path.join(dist_info, 'pydist.json')
719 resources_path = os.path.join(dist_info, 'RESOURCES')
720 md = Metadata()
721 md.name = 'test'
722 md.version = '0.1'
723 md.summary = 'test'
724 md.write(path=metadata_path)
725 test_path = 'test.cfg'
726
727 fd, test_resource_path = tempfile.mkstemp()
728 os.close(fd)
729 self.addCleanup(os.remove, test_resource_path)
730
731 fp = open(test_resource_path, 'w')
732 try:
733 fp.write('Config')
734 finally:
735 fp.close()
736
737 fp = open(resources_path, 'w')
738 try:
739 fp.write('%s,%s' % (test_path, test_resource_path))
740 finally:
741 fp.close()
742
743 # Add fake site-packages to sys.path to retrieve fake dist
744 self.addCleanup(sys.path.remove, temp_site_packages)
745 sys.path.insert(0, temp_site_packages)
746
747 # Try to retrieve resources paths and files
748 d = DistributionPath()
749 self.assertEqual(d.get_file_path(dist_name, test_path), test_resource_path)
750 self.assertRaises(KeyError, d.get_file_path, dist_name, 'i-dont-exist')
751
752
753 class DepGraphTestCase(LoggingCatcher, DistlibTestCase):
754
755 DISTROS_DIST = ('choxie', 'grammar', 'towel-stuff')
756 DISTROS_EGG = ('bacon', 'banana', 'strawberry', 'cheese')
757 BAD_EGGS = ('nut', )
758
759 EDGE = re.compile(r'"(?P<from>.*)" -> "(?P<to>.*)" \[label="(?P<label>.*)"\]')
760
761 def checkLists(self, l1, l2):
762 """ Compare two lists without taking the order into consideration """
763 self.assertListEqual(sorted(l1), sorted(l2))
764
765 def setUp(self):
766 super(DepGraphTestCase, self).setUp()
767 path = os.path.join(os.path.dirname(__file__), 'fake_dists')
768 path = os.path.abspath(path)
769 sys.path.insert(0, path)
770 self.addCleanup(sys.path.remove, path)
771
772 def get_dists(self, names, include_egg=False):
773 dists = []
774 d = DistributionPath(include_egg=include_egg)
775 for name in names:
776 dist = d.get_distribution(name)
777 self.assertNotEqual(dist, None)
778 dists.append(dist)
779 return dists
780
781 def test_make_graph(self):
782 dists = self.get_dists(self.DISTROS_DIST)
783
784 choxie, grammar, towel = dists
785
786 graph = make_graph(dists)
787
788 deps = [(x.name, y) for x, y in graph.adjacency_list[choxie]]
789 self.checkLists([('towel-stuff', 'towel-stuff (0.1)')], deps)
790 self.assertIn(choxie, graph.reverse_list[towel])
791 self.checkLists(graph.missing[choxie], ['nut'])
792
793 deps = [(x.name, y) for x, y in graph.adjacency_list[grammar]]
794 self.checkLists([], deps)
795 self.checkLists(graph.missing[grammar], ['truffles (>=1.2)'])
796
797 deps = [(x.name, y) for x, y in graph.adjacency_list[towel]]
798 self.checkLists([], deps)
799 self.checkLists(graph.missing[towel], ['bacon (<=0.2)'])
800
801 @requires_zlib
802 def test_make_graph_egg(self):
803 dists = self.get_dists(self.DISTROS_DIST + self.DISTROS_EGG, True)
804
805 choxie, grammar, towel, bacon, banana, strawberry, cheese = dists
806
807 graph = make_graph(dists)
808
809 deps = [(x.name, y) for x, y in graph.adjacency_list[choxie]]
810 self.checkLists([('towel-stuff', 'towel-stuff (0.1)')], deps)
811 self.assertIn(choxie, graph.reverse_list[towel])
812 self.checkLists(graph.missing[choxie], ['nut'])
813
814 deps = [(x.name, y) for x, y in graph.adjacency_list[grammar]]
815 self.checkLists([('bacon', 'truffles (>=1.2)')], deps)
816 self.checkLists(graph.missing.get(grammar, []), [])
817 self.assertIn(grammar, graph.reverse_list[bacon])
818
819 deps = [(x.name, y) for x, y in graph.adjacency_list[towel]]
820 self.checkLists([('bacon', 'bacon (<=0.2)')], deps)
821 self.checkLists(graph.missing.get(towel, []), [])
822 self.assertIn(towel, graph.reverse_list[bacon])
823
824 deps = [(x.name, y) for x, y in graph.adjacency_list[bacon]]
825 self.checkLists([], deps)
826 self.checkLists(graph.missing.get(bacon, []), [])
827
828 deps = [(x.name, y) for x, y in graph.adjacency_list[banana]]
829 self.checkLists([('strawberry', 'strawberry (>=0.5)')], deps)
830 self.checkLists(graph.missing.get(banana, []), [])
831 self.assertIn(banana, graph.reverse_list[strawberry])
832
833 deps = [(x.name, y) for x, y in graph.adjacency_list[strawberry]]
834 self.checkLists([], deps)
835 self.checkLists(graph.missing.get(strawberry, []), [])
836
837 deps = [(x.name, y) for x, y in graph.adjacency_list[cheese]]
838 self.checkLists([], deps)
839 self.checkLists(graph.missing.get(cheese, []), [])
840
841 def test_dependent_dists(self):
842 # import pdb; pdb.set_trace()
843 dists = self.get_dists(self.DISTROS_DIST)
844
845 choxie, grammar, towel = dists
846
847 deps = [d.name for d in get_dependent_dists(dists, choxie)]
848 self.checkLists([], deps)
849
850 deps = [d.name for d in get_dependent_dists(dists, grammar)]
851 self.checkLists([], deps)
852
853 deps = [d.name for d in get_dependent_dists(dists, towel)]
854 self.checkLists(['choxie'], deps)
855
856 def test_required_dists(self):
857 dists = self.get_dists(self.DISTROS_DIST + ('truffles', 'bacon', 'banana', 'coconuts-aster'), True)
858
859 choxie, grammar, towel, truffles, bacon, banana, coco = dists
860
861 reqs = [d.name for d in get_required_dists(dists, choxie)]
862 self.checkLists(['bacon', 'towel-stuff'], reqs)
863
864 reqs = [d.name for d in get_required_dists(dists, grammar)]
865 self.checkLists(['truffles'], reqs)
866
867 reqs = [d.name for d in get_required_dists(dists, banana)]
868 self.checkLists(['coconuts-aster'], reqs)
869
870 reqs = [d.name for d in get_required_dists(dists, towel)]
871 self.checkLists(['bacon'], reqs)
872
873 # Check the invalid case: pass a dist not in the list
874 dists = dists[:-1]
875 self.assertRaises(DistlibException, get_required_dists, dists, coco)
876
877 @requires_zlib
878 def test_dependent_dists_egg(self):
879 dists = self.get_dists(self.DISTROS_DIST + self.DISTROS_EGG, True)
880
881 choxie, grammar, towel, bacon, banana, strawberry, cheese = dists
882
883 deps = [d.name for d in get_dependent_dists(dists, choxie)]
884 self.checkLists([], deps)
885
886 deps = [d.name for d in get_dependent_dists(dists, grammar)]
887 self.checkLists([], deps)
888
889 deps = [d.name for d in get_dependent_dists(dists, towel)]
890 self.checkLists(['choxie'], deps)
891
892 deps = [d.name for d in get_dependent_dists(dists, bacon)]
893 self.checkLists(['choxie', 'towel-stuff', 'grammar'], deps)
894
895 deps = [d.name for d in get_dependent_dists(dists, strawberry)]
896 self.checkLists(['banana'], deps)
897
898 deps = [d.name for d in get_dependent_dists(dists, cheese)]
899 self.checkLists([], deps)
900
901 # Check the invalid case: pass a dist not in the list
902 dists = dists[:-1]
903 self.assertRaises(DistlibException, get_dependent_dists, dists, cheese)
904
905 @requires_zlib
906 def test_graph_to_dot(self):
907 expected = (
908 ('towel-stuff', 'bacon', 'bacon (<=0.2)'),
909 ('grammar', 'bacon', 'truffles (>=1.2)'),
910 ('choxie', 'towel-stuff', 'towel-stuff (0.1)'),
911 ('banana', 'strawberry', 'strawberry (>=0.5)'),
912 )
913
914 dists = self.get_dists(self.DISTROS_DIST + self.DISTROS_EGG, True)
915
916 graph = make_graph(dists)
917 buf = StringIO()
918 graph.to_dot(buf)
919 buf.seek(0)
920 matches = []
921 lines = buf.readlines()
922 for line in lines[1:-1]: # skip the first and the last lines
923 if line[-1] == '\n':
924 line = line[:-1]
925 match = self.EDGE.match(line.strip())
926 self.assertIsNot(match, None)
927 matches.append(match.groups())
928
929 self.checkLists(matches, expected)
930
931 @requires_zlib
932 def test_graph_disconnected_to_dot(self):
933 dependencies_expected = (
934 ('towel-stuff', 'bacon', 'bacon (<=0.2)'),
935 ('grammar', 'bacon', 'truffles (>=1.2)'),
936 ('choxie', 'towel-stuff', 'towel-stuff (0.1)'),
937 ('banana', 'strawberry', 'strawberry (>=0.5)'),
938 )
939 disconnected_expected = ('cheese', 'bacon', 'strawberry')
940
941 dists = self.get_dists(self.DISTROS_DIST + self.DISTROS_EGG, True)
942
943 graph = make_graph(dists)
944 buf = StringIO()
945 graph.to_dot(buf, skip_disconnected=False)
946 buf.seek(0)
947 lines = buf.readlines()
948
949 dependencies_lines = []
950 disconnected_lines = []
951
952 # First sort output lines into dependencies and disconnected lines.
953 # We also skip the attribute lines, and don't include the "{" and "}"
954 # lines.
955 disconnected_active = False
956 for line in lines[1:-1]: # Skip first and last line
957 if line.startswith('subgraph disconnected'):
958 disconnected_active = True
959 continue
960 if line.startswith('}') and disconnected_active:
961 disconnected_active = False
962 continue
963
964 if disconnected_active:
965 # Skip the 'label = "Disconnected"', etc. attribute lines.
966 if ' = ' not in line:
967 disconnected_lines.append(line)
968 else:
969 dependencies_lines.append(line)
970
971 dependencies_matches = []
972 for line in dependencies_lines:
973 if line[-1] == '\n':
974 line = line[:-1]
975 match = self.EDGE.match(line.strip())
976 self.assertIsNot(match, None)
977 dependencies_matches.append(match.groups())
978
979 disconnected_matches = []
980 for line in disconnected_lines:
981 if line[-1] == '\n':
982 line = line[:-1]
983 line = line.strip('"')
984 disconnected_matches.append(line)
985
986 self.checkLists(dependencies_matches, dependencies_expected)
987 self.checkLists(disconnected_matches, disconnected_expected)
988
989 @requires_zlib
990 def test_graph_bad_version_to_dot(self):
991 expected = (
992 ('towel-stuff', 'bacon', 'bacon (<=0.2)'),
993 ('grammar', 'bacon', 'truffles (>=1.2)'),
994 ('choxie', 'towel-stuff', 'towel-stuff (0.1)'),
995 ('banana', 'strawberry', 'strawberry (>=0.5)'),
996 )
997
998 dists = self.get_dists(self.DISTROS_DIST + self.DISTROS_EGG + self.BAD_EGGS, True)
999
1000 graph = make_graph(dists)
1001 buf = StringIO()
1002 graph.to_dot(buf)
1003 buf.seek(0)
1004 matches = []
1005 lines = buf.readlines()
1006 for line in lines[1:-1]: # skip the first and the last lines
1007 if line[-1] == '\n':
1008 line = line[:-1]
1009 match = self.EDGE.match(line.strip())
1010 self.assertIsNot(match, None)
1011 matches.append(match.groups())
1012
1013 self.checkLists(matches, expected)
1014
1015 @requires_zlib
1016 def test_repr(self):
1017 dists = self.get_dists(self.DISTROS_DIST + self.DISTROS_EGG + self.BAD_EGGS, True)
1018
1019 graph = make_graph(dists)
1020 self.assertTrue(repr(graph))
1021
1022
1023 def test_suite():
1024 suite = unittest.TestSuite()
1025 load = unittest.defaultTestLoader.loadTestsFromTestCase
1026 suite.addTest(load(TestDistribution))
1027 suite.addTest(load(TestEggInfoDistribution))
1028 suite.addTest(load(TestDatabase))
1029 suite.addTest(load(DataFilesTestCase))
1030 suite.addTest(load(DepGraphTestCase))
1031 return suite
1032
1033
1034 if __name__ == "__main__": # pragma: no cover
1035 unittest.main(defaultTest='test_suite')