• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import sys
2import unittest
3
4from contextlib import ExitStack
5from importlib.metadata import (
6    PackageNotFoundError,
7    distribution,
8    distributions,
9    entry_points,
10    files,
11    version,
12)
13from importlib import resources
14
15from test.support import requires_zlib
16
17
18@requires_zlib()
19class TestZip(unittest.TestCase):
20    root = 'test.test_importlib.data'
21
22    def _fixture_on_path(self, filename):
23        pkg_file = resources.files(self.root).joinpath(filename)
24        file = self.resources.enter_context(resources.as_file(pkg_file))
25        assert file.name.startswith('example-'), file.name
26        sys.path.insert(0, str(file))
27        self.resources.callback(sys.path.pop, 0)
28
29    def setUp(self):
30        # Find the path to the example-*.whl so we can add it to the front of
31        # sys.path, where we'll then try to find the metadata thereof.
32        self.resources = ExitStack()
33        self.addCleanup(self.resources.close)
34        self._fixture_on_path('example-21.12-py3-none-any.whl')
35
36    def test_zip_version(self):
37        self.assertEqual(version('example'), '21.12')
38
39    def test_zip_version_does_not_match(self):
40        with self.assertRaises(PackageNotFoundError):
41            version('definitely-not-installed')
42
43    def test_zip_entry_points(self):
44        scripts = entry_points(group='console_scripts')
45        entry_point = scripts['example']
46        self.assertEqual(entry_point.value, 'example:main')
47        entry_point = scripts['Example']
48        self.assertEqual(entry_point.value, 'example:main')
49
50    def test_missing_metadata(self):
51        self.assertIsNone(distribution('example').read_text('does not exist'))
52
53    def test_case_insensitive(self):
54        self.assertEqual(version('Example'), '21.12')
55
56    def test_files(self):
57        for file in files('example'):
58            path = str(file.dist.locate_file(file))
59            assert '.whl/' in path, path
60
61    def test_one_distribution(self):
62        dists = list(distributions(path=sys.path[:1]))
63        assert len(dists) == 1
64
65
66@requires_zlib()
67class TestEgg(TestZip):
68    def setUp(self):
69        # Find the path to the example-*.egg so we can add it to the front of
70        # sys.path, where we'll then try to find the metadata thereof.
71        self.resources = ExitStack()
72        self.addCleanup(self.resources.close)
73        self._fixture_on_path('example-21.12-py3.6.egg')
74
75    def test_files(self):
76        for file in files('example'):
77            path = str(file.dist.locate_file(file))
78            assert '.egg/' in path, path
79
80    def test_normalized_name(self):
81        dist = distribution('example')
82        assert dist._normalized_name == 'example'
83