Debian Codegraph @

tests/test_wheel.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2013-2026 Vinay Sajip.
4 # Licensed to the Python Software Foundation under a contributor agreement.
5 # See LICENSE.txt and CONTRIBUTORS.txt.
6 #
7 from __future__ import unicode_literals
8
9 import io
10 import os
11 import re
12 import shutil
13 import subprocess
14 import sys
15 import tempfile
16
17 from compat import unittest
18 from support import DistlibTestCase
19
20 from distlib import __version__, DistlibException
21 from distlib.compat import ZipFile, sysconfig, fsencode
22 from distlib.database import DistributionPath
23 from distlib.manifest import Manifest
24 from distlib.metadata import Metadata, METADATA_FILENAME, LEGACY_METADATA_FILENAME
25 from distlib.scripts import ScriptMaker
26 from distlib.util import get_executable
27 from distlib.wheel import (Wheel, PYVER, IMPVER, ARCH, ABI, COMPATIBLE_TAGS, IMP_PREFIX, VER_SUFFIX,
28 is_compatible, _get_glibc_version)
29
30 try:
31 with open(os.devnull, 'wb') as junk:
32 subprocess.check_call(['pip', '--version'], stdout=junk, stderr=subprocess.STDOUT)
33 PIP_AVAILABLE = True
34 except Exception:
35 PIP_AVAILABLE = False
36
37 HERE = os.path.abspath(os.path.dirname(__file__))
38
39 EGG_INFO_RE = re.compile(r'(-py\d\.\d)?\.egg-info', re.I)
40
41
42 def pip_version():
43 result = None
44 fd, fn = tempfile.mkstemp(prefix='distlib-test-', suffix='.txt')
45 try:
46 os.close(fd)
47 with open(fn, 'wb') as out:
48 subprocess.check_call(['pip', '--version'], stdout=out, stderr=subprocess.STDOUT)
49 with io.open(fn, encoding='utf-8') as f:
50 data = f.read().split()
51 assert data[0] == 'pip'
52 parts = data[1].split('.')
53 result = []
54 for p in parts:
55 if p.isdigit():
56 result.append(int(p))
57 else:
58 result.append(p)
59 result = tuple(result)
60 finally:
61 os.remove(fn)
62 return result
63
64
65 def convert_egg_info(libdir, prefix):
66 files = os.listdir(libdir)
67 ei = list(filter(lambda d: d.endswith('.egg-info'), files))[0]
68 olddn = os.path.join(libdir, ei)
69 di = EGG_INFO_RE.sub('.dist-info', ei)
70 newdn = os.path.join(libdir, di)
71 os.rename(olddn, newdn)
72 files = os.listdir(newdn)
73 for oldfn in files:
74 pn = os.path.join(newdn, oldfn)
75 if oldfn == 'PKG-INFO':
76 md = Metadata(path=pn)
77 mn = os.path.join(newdn, METADATA_FILENAME)
78 md.write(mn)
79 os.remove(pn)
80 manifest = Manifest(os.path.dirname(libdir))
81 manifest.findall()
82 dp = DistributionPath([libdir])
83 dist = next(dp.get_distributions())
84 dist.write_installed_files(manifest.allfiles, prefix)
85
86
87 def install_dist(distname, workdir):
88 pfx = '--install-option='
89 purelib = pfx + '--install-purelib=%s/purelib' % workdir
90 platlib = pfx + '--install-platlib=%s/platlib' % workdir
91 headers = pfx + '--install-headers=%s/headers' % workdir
92 scripts = pfx + '--install-scripts=%s/scripts' % workdir
93 data = pfx + '--install-data=%s/data' % workdir
94 cmd = [
95 'pip', 'install', '--index-url', 'https://pypi.org/simple/', '--timeout', '3', '--default-timeout', '3',
96 purelib, platlib, headers, scripts, data, distname
97 ]
98 result = {
99 'scripts': os.path.join(workdir, 'scripts'),
100 'headers': os.path.join(workdir, 'headers'),
101 'data': os.path.join(workdir, 'data'),
102 }
103 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
104 stdout, _ = p.communicate()
105 if p.returncode:
106 raise ValueError('pip failed to install %s:\n%s' % (distname, stdout))
107 for dn in ('purelib', 'platlib'):
108 libdir = os.path.join(workdir, dn)
109 if os.path.isdir(libdir):
110 result[dn] = libdir
111 break
112 convert_egg_info(libdir, workdir)
113 dp = DistributionPath([libdir])
114 dist = next(dp.get_distributions())
115 md = dist.metadata
116 result['name'] = md.name
117 result['version'] = md.version
118 return result
119
120
121 class WheelTestCase(DistlibTestCase):
122
123 def test_valid_filename(self):
124 attrs = ('name', 'version', 'buildver', 'pyver', 'abi', 'arch')
125 cases = (
126 ('pkg-1.0.0-cp32.cp33-noabi-noarch.whl', ('pkg', '1.0.0', '', ['cp32', 'cp33'], ['noabi'], ['noarch'])),
127 ('package-1.0.0-cp33-noabi-linux_x86_64.whl', ('package', '1.0.0', '', ['cp33'], ['noabi'],
128 ['linux_x86_64'])),
129 ('test-1.0-1st-py2.py3-none-win32.whl', ('test', '1.0', '1st', ['py2', 'py3'], ['none'], ['win32'])),
130 ('Pillow-2.8.1-cp27-none-macosx_10_6_intel.'
131 'macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.'
132 'macosx_10_10_x86_64.whl', ('Pillow', '2.8.1', '', ['cp27'], ['none'], [
133 'macosx_10_6_intel', 'macosx_10_9_intel', 'macosx_10_9_x86_64', 'macosx_10_10_intel',
134 'macosx_10_10_x86_64'
135 ])),
136 )
137
138 for name, values in cases:
139 w = Wheel(name)
140 self.assertEqual(w.wheel_version, (1, 1))
141 self.assertEqual(w.filename, name)
142 for attr, value in zip(attrs, values):
143 self.assertEqual(getattr(w, attr), value)
144
145 def test_invalid_filename(self):
146 names = (
147 '',
148 'package.whl',
149 'package-1.0.0-cp32.cp33.whl',
150 'package-1.0.0-cp32.cp33.whl',
151 'package-1.0.0-cp32.cp33-noabi.whl',
152 'package-1.0.0-cp32.cp33-noabi-noarch.zip',
153 )
154
155 for name in names:
156 self.assertRaises(DistlibException, Wheel, name)
157
158 def test_valid_name(self):
159 attrs = ('name', 'version', 'buildver', 'pyver', 'abi', 'arch')
160 pyver = PYVER
161 cases = (
162 ('pkg-1.0.0', ('pkg', '1.0.0', '', [pyver], ['none'], ['any'])),
163 ('test-1.0-1st', ('test', '1.0', '1st', [pyver], ['none'], ['any'])),
164 (None, ('dummy', '0.1', '', [pyver], ['none'], ['any'])),
165 )
166
167 ENDING = '-%s-none-any.whl' % PYVER
168 for name, values in cases:
169 w = Wheel(name)
170 self.assertEqual(w.wheel_version, (1, 1))
171 self.assertTrue(w.filename.endswith(ENDING))
172 for attr, value in zip(attrs, values):
173 self.assertEqual(getattr(w, attr), value)
174
175 def test_compatible_tags(self):
176 self.assertEqual(PYVER, 'py%d%d' % sys.version_info[:2])
177 tags = COMPATIBLE_TAGS
178 self.assertIn((PYVER, 'none', 'any'), tags)
179 self.assertIn((PYVER[:-1], 'none', 'any'), tags)
180 this_arch = filter(lambda o: o[-1] == ARCH, tags)
181 self.assertTrue(this_arch)
182 if sys.platform.startswith('linux'):
183 arch = ARCH.replace('linux_', '')
184 parts = _get_glibc_version()
185 if len(parts) == 2:
186 self.assertTrue(filter(lambda o: o[-1] == 'manylinux_%s_%s_%s' % (parts[0], parts[1], arch), tags))
187 if parts >= (2, 17):
188 self.assertTrue(filter(lambda o: o[-1] == 'manylinux2014_%s' % arch, tags))
189 if parts >= (2, 12):
190 self.assertTrue(filter(lambda o: o[-1] == 'manylinux2010_%s' % arch, tags))
191 if parts >= (2, 5):
192 self.assertTrue(filter(lambda o: o[-1] == 'manylinux1_%s' % arch, tags))
193
194 def test_is_compatible(self):
195 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
196 if PYVER in ('py27', 'py30', 'py31'):
197 self.assertTrue(is_compatible(fn))
198 self.assertTrue(Wheel(fn).is_compatible())
199 # use actual wheel names from PyPI.
200 wheel_names = [
201 'simplejson-3.17.2-cp27-cp27m-macosx_10_13_x86_64.whl',
202 'simplejson-3.17.2-cp27-cp27m-manylinux1_i686.whl',
203 'simplejson-3.17.2-cp27-cp27m-manylinux1_x86_64.whl',
204 'simplejson-3.17.2-cp27-cp27m-manylinux2010_i686.whl',
205 'simplejson-3.17.2-cp27-cp27m-manylinux2010_x86_64.whl',
206 'simplejson-3.17.2-cp27-cp27mu-manylinux1_i686.whl',
207 'simplejson-3.17.2-cp27-cp27mu-manylinux1_x86_64.whl',
208 'simplejson-3.17.2-cp27-cp27mu-manylinux2010_i686.whl',
209 'simplejson-3.17.2-cp27-cp27mu-manylinux2010_x86_64.whl',
210 'simplejson-3.17.2-cp27-cp27m-win32.whl',
211 'simplejson-3.17.2-cp27-cp27m-win_amd64.whl',
212 'simplejson-3.17.2-cp33-cp33m-win32.whl',
213 'simplejson-3.17.2-cp33-cp33m-win_amd64.whl',
214 'simplejson-3.17.2-cp34-cp34m-win32.whl',
215 'simplejson-3.17.2-cp34-cp34m-win_amd64.whl',
216 'simplejson-3.17.2-cp35-cp35m-manylinux1_i686.whl',
217 'simplejson-3.17.2-cp35-cp35m-manylinux1_x86_64.whl',
218 'simplejson-3.17.2-cp35-cp35m-manylinux2010_i686.whl',
219 'simplejson-3.17.2-cp35-cp35m-manylinux2010_x86_64.whl',
220 'simplejson-3.17.2-cp35-cp35m-manylinux2014_aarch64.whl',
221 'simplejson-3.17.2-cp35-cp35m-win32.whl',
222 'simplejson-3.17.2-cp35-cp35m-win_amd64.whl',
223 'simplejson-3.17.2-cp36-cp36m-macosx_10_13_x86_64.whl',
224 'simplejson-3.17.2-cp36-cp36m-manylinux1_i686.whl',
225 'simplejson-3.17.2-cp36-cp36m-manylinux1_x86_64.whl',
226 'simplejson-3.17.2-cp36-cp36m-manylinux2010_i686.whl',
227 'simplejson-3.17.2-cp36-cp36m-manylinux2010_x86_64.whl',
228 'simplejson-3.17.2-cp36-cp36m-manylinux2014_aarch64.whl',
229 'simplejson-3.17.2-cp36-cp36m-win32.whl',
230 'simplejson-3.17.2-cp36-cp36m-win_amd64.whl',
231 'simplejson-3.17.2-cp37-cp37m-macosx_10_14_x86_64.whl',
232 'simplejson-3.17.2-cp37-cp37m-manylinux1_i686.whl',
233 'simplejson-3.17.2-cp37-cp37m-manylinux1_x86_64.whl',
234 'simplejson-3.17.2-cp37-cp37m-manylinux2010_i686.whl',
235 'simplejson-3.17.2-cp37-cp37m-manylinux2010_x86_64.whl',
236 'simplejson-3.17.2-cp37-cp37m-manylinux2014_aarch64.whl',
237 'simplejson-3.17.2-cp37-cp37m-win32.whl',
238 'simplejson-3.17.2-cp37-cp37m-win_amd64.whl',
239 'simplejson-3.17.2-cp38-cp38-macosx_10_14_x86_64.whl',
240 'simplejson-3.17.2-cp38-cp38-manylinux1_i686.whl',
241 'simplejson-3.17.2-cp38-cp38-manylinux1_x86_64.whl',
242 'simplejson-3.17.2-cp38-cp38-manylinux2010_i686.whl',
243 'simplejson-3.17.2-cp38-cp38-manylinux2010_x86_64.whl',
244 'simplejson-3.17.2-cp38-cp38-manylinux2014_aarch64.whl',
245 'Pillow-7.2.0-cp35-cp35m-macosx_10_10_intel.whl',
246 'Pillow-7.2.0-cp35-cp35m-manylinux1_i686.whl',
247 'Pillow-7.2.0-cp35-cp35m-manylinux1_x86_64.whl',
248 'Pillow-7.2.0-cp35-cp35m-manylinux2014_aarch64.whl',
249 'Pillow-7.2.0-cp35-cp35m-win32.whl',
250 'Pillow-7.2.0-cp35-cp35m-win_amd64.whl',
251 'Pillow-7.2.0-cp36-cp36m-macosx_10_10_x86_64.whl',
252 'Pillow-7.2.0-cp36-cp36m-manylinux1_i686.whl',
253 'Pillow-7.2.0-cp36-cp36m-manylinux1_x86_64.whl',
254 'Pillow-7.2.0-cp36-cp36m-manylinux2014_aarch64.whl',
255 'Pillow-7.2.0-cp36-cp36m-win32.whl',
256 'Pillow-7.2.0-cp36-cp36m-win_amd64.whl',
257 'Pillow-7.2.0-cp37-cp37m-macosx_10_10_x86_64.whl',
258 'Pillow-7.2.0-cp37-cp37m-manylinux1_i686.whl',
259 'Pillow-7.2.0-cp37-cp37m-manylinux1_x86_64.whl',
260 'Pillow-7.2.0-cp37-cp37m-manylinux2014_aarch64.whl',
261 'Pillow-7.2.0-cp37-cp37m-win32.whl',
262 'Pillow-7.2.0-cp37-cp37m-win_amd64.whl',
263 'Pillow-7.2.0-cp38-cp38-macosx_10_10_x86_64.whl',
264 'Pillow-7.2.0-cp38-cp38-manylinux1_i686.whl',
265 'Pillow-7.2.0-cp38-cp38-manylinux1_x86_64.whl',
266 'Pillow-7.2.0-cp38-cp38-manylinux2014_aarch64.whl',
267 'Pillow-7.2.0-cp38-cp38-win32.whl',
268 'Pillow-7.2.0-cp38-cp38-win_amd64.whl',
269 'Pillow-7.2.0-pp36-pypy36_pp73-macosx_10_10_x86_64.whl',
270 'Pillow-7.2.0-pp36-pypy36_pp73-manylinux2010_x86_64.whl',
271 'Pillow-7.2.0-pp36-pypy36_pp73-win32.whl',
272 'reportlab-3.5.47-cp27-cp27m-macosx_10_9_x86_64.whl',
273 'reportlab-3.5.47-cp27-cp27m-manylinux1_i686.whl',
274 'reportlab-3.5.47-cp27-cp27m-manylinux1_x86_64.whl',
275 'reportlab-3.5.47-cp27-cp27m-manylinux2010_i686.whl',
276 'reportlab-3.5.47-cp27-cp27m-manylinux2010_x86_64.whl',
277 'reportlab-3.5.47-cp27-cp27mu-manylinux1_i686.whl',
278 'reportlab-3.5.47-cp27-cp27mu-manylinux1_x86_64.whl',
279 'reportlab-3.5.47-cp27-cp27mu-manylinux2010_i686.whl',
280 'reportlab-3.5.47-cp27-cp27mu-manylinux2010_x86_64.whl',
281 'reportlab-3.5.47-cp27-cp27m-win32.whl',
282 'reportlab-3.5.47-cp27-cp27m-win_amd64.whl',
283 'reportlab-3.5.47-cp35-cp35m-macosx_10_6_intel.whl',
284 'reportlab-3.5.47-cp35-cp35m-manylinux1_i686.whl',
285 'reportlab-3.5.47-cp35-cp35m-manylinux1_x86_64.whl',
286 'reportlab-3.5.47-cp35-cp35m-manylinux2010_i686.whl',
287 'reportlab-3.5.47-cp35-cp35m-manylinux2010_x86_64.whl',
288 'reportlab-3.5.47-cp35-cp35m-win32.whl',
289 'reportlab-3.5.47-cp35-cp35m-win_amd64.whl',
290 'reportlab-3.5.47-cp36-cp36m-macosx_10_9_x86_64.whl',
291 'reportlab-3.5.47-cp36-cp36m-manylinux1_i686.whl',
292 'reportlab-3.5.47-cp36-cp36m-manylinux1_x86_64.whl',
293 'reportlab-3.5.47-cp36-cp36m-manylinux2010_i686.whl',
294 'reportlab-3.5.47-cp36-cp36m-manylinux2010_x86_64.whl',
295 'reportlab-3.5.47-cp36-cp36m-win32.whl',
296 'reportlab-3.5.47-cp36-cp36m-win_amd64.whl',
297 'reportlab-3.5.47-cp37-cp37m-macosx_10_9_x86_64.whl',
298 'reportlab-3.5.47-cp37-cp37m-manylinux1_i686.whl',
299 'reportlab-3.5.47-cp37-cp37m-manylinux1_x86_64.whl',
300 'reportlab-3.5.47-cp37-cp37m-manylinux2010_i686.whl',
301 'reportlab-3.5.47-cp37-cp37m-manylinux2010_x86_64.whl',
302 'reportlab-3.5.47-cp37-cp37m-win32.whl',
303 'reportlab-3.5.47-cp37-cp37m-win_amd64.whl',
304 'reportlab-3.5.47-cp38-cp38-macosx_10_9_x86_64.whl',
305 'reportlab-3.5.47-cp38-cp38-manylinux1_i686.whl',
306 'reportlab-3.5.47-cp38-cp38-manylinux1_x86_64.whl',
307 'reportlab-3.5.47-cp38-cp38-manylinux2010_i686.whl',
308 'reportlab-3.5.47-cp38-cp38-manylinux2010_x86_64.whl',
309 'reportlab-3.5.47-cp38-cp38-win32.whl',
310 'reportlab-3.5.47-cp38-cp38-win_amd64.whl',
311 ]
312 for fn in filter(is_compatible, wheel_names):
313 w = Wheel(fn)
314 our_arch = ARCH.replace('linux_', '')
315 for pyver, abi, arch in w.tags:
316 self.assertEqual(pyver, IMPVER)
317 self.assertEqual(abi, ABI)
318 if sys.platform != 'darwin':
319 self.assertTrue(arch.endswith(our_arch))
320 else:
321 m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', our_arch)
322 self.assertTrue(m)
323 _, major, minor, our_arch_kind = m.groups()
324 our_major = int(major)
325 our_minor = int(minor)
326 m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', arch)
327 self.assertTrue(m)
328 _, major, minor, arch_kind = m.groups()
329 major = int(major)
330 minor = int(minor)
331 self.assertEqual(major, our_major)
332 self.assertLessEqual(minor, our_minor)
333 if arch_kind in ('x86_64', 'i386'):
334 self.assertEqual(arch_kind, our_arch_kind)
335 elif arch_kind == 'fat':
336 self.assertIn(our_arch_kind, ('i386', 'ppc'))
337 elif arch_kind == 'fat3':
338 self.assertIn(our_arch_kind, ('i386', 'ppc', 'x86_x64'))
339 elif arch_kind == 'fat64':
340 self.assertIn(our_arch_kind, ('ppc64', 'x86_x64'))
341 elif arch_kind == 'intel':
342 self.assertIn(our_arch_kind, ('i386', 'x86_x64'))
343 elif arch_kind == 'universal':
344 self.assertIn(our_arch_kind, ('i386', 'ppc', 'ppc64', 'x86_x64', 'intel'))
345 if 'manylinux' in arch:
346 self.assertTrue(sys.platform.startswith('linux'))
347 parts = _get_glibc_version()
348 self.assertEqual(len(parts), 2)
349 if 'manylinux2014_' in arch:
350 self.assertTrue(parts >= (2, 17))
351 if 'manylinux2010_' in arch:
352 self.assertTrue(parts >= (2, 12))
353 if 'manylinux1_' in arch:
354 self.assertTrue(parts >= (2, 5))
355 if 'manylinux_' in arch:
356 s = 'manylinux_%s_%s_' % parts
357 self.assertIn(s, arch)
358
359 def test_is_compatible_limited_abi(self):
360 major_version = sys.version_info.major
361 minor_version = sys.version_info.minor
362 minimum_abi3_version = (3, 2)
363 if not ((major_version, minor_version) >= minimum_abi3_version and IMP_PREFIX == 'cp'):
364 self.skipTest('Python %s does not support the limited API' % VER_SUFFIX)
365
366 compatible_wheel_filenames = [
367 'dummy-0.1-cp%d%d-abi3-%s.whl' % (major_version, current_minor_version, ARCH)
368 for current_minor_version in range(minor_version, -1, -1)
369 if (major_version, current_minor_version) >= minimum_abi3_version
370 ]
371 incompatible_wheel_filenames = [
372 'dummy-0.1-cp%d%d-%s-%s.whl' % (major_version, current_minor_version, ABI, ARCH)
373 for current_minor_version in range(minor_version - 1, -1, -1)
374 ]
375 for wheel_filename in compatible_wheel_filenames:
376 self.assertTrue(is_compatible(wheel_filename), msg=wheel_filename)
377 for wheel_filename in incompatible_wheel_filenames:
378 self.assertFalse(is_compatible(wheel_filename), msg=wheel_filename)
379
380 def test_metadata(self):
381 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
382 w = Wheel(fn)
383 md = w.metadata
384 self.assertEqual(md.name, 'dummy')
385 self.assertEqual(md.version, '0.1')
386
387 def test_invalid(self):
388 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
389 w = Wheel(fn)
390 self.assertRaises(DistlibException, w.get_hash, b'', 'badalgo')
391
392 def check_built_wheel(self, wheel, expected):
393 for key in expected:
394 self.assertEqual(expected[key], getattr(wheel, key))
395 fn = os.path.join(wheel.dirname, wheel.filename)
396 self.assertTrue(os.path.exists(fn))
397 name, version = wheel.name, wheel.version
398 with ZipFile(fn, 'r') as zf:
399 for key in ('scripts', 'headers', 'data'):
400 arcname = '%s-%s.data/%s/%s_file.txt' % (name, version, key, key)
401 with zf.open(arcname) as bf:
402 data = bf.read()
403 expected = ('dummy data - %s' % key).encode('utf-8')
404 if key == 'scripts':
405 expected = b'#!python\n' + expected
406 self.assertTrue(data, expected)
407
408 def check_built_metadata(self, wheel):
409 # Check the metadata of the built wheel (see #238).
410 name, version = wheel.name, wheel.version
411 fn = os.path.join(wheel.dirname, wheel.filename)
412 self.assertTrue(os.path.exists(fn))
413 arcname = '%s-%s.dist-info/WHEEL' % (name, version)
414 with ZipFile(fn, 'r') as zf:
415 with zf.open(arcname) as bf:
416 data = bf.read().decode('utf-8')
417 if wheel.arch[0] == 'any':
418 is_pure = 'true'
419 else:
420 is_pure = 'false'
421 expected = {
422 'Wheel-Version': '%d.%d' % wheel.wheel_version,
423 'Generator': 'distlib %s' % __version__,
424 'Root-Is-Purelib': is_pure,
425 'Build': '1foobar',
426 'Tag': '%s-%s-%s' % (wheel.pyver[0], wheel.abi[0], wheel.arch[0]),
427 }
428 actual = {}
429 for line in data.splitlines():
430 i = line.find(':')
431 key, value = line[:i], line[i + 1:].lstrip()
432 actual[key] = value
433 self.assertEqual(actual, expected)
434
435 def test_build_tags(self):
436 workdir = tempfile.mkdtemp()
437 self.addCleanup(shutil.rmtree, workdir)
438 name = 'dummy'
439 version = '0.1'
440 paths = {'prefix': workdir}
441 for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
442 paths[key] = p = os.path.join(workdir, key)
443 os.makedirs(p)
444 fn = os.path.join(p, '%s_file.txt' % key)
445 with open(fn, 'w') as f:
446 f.write('dummy data - %s' % key)
447 if key in ('purelib', 'platlib'):
448 p = os.path.join(p, '%s-%s.dist-info' % (name, version))
449 os.makedirs(p)
450 fn = os.path.join(p, 'RECORD')
451
452 purelib = paths.pop('purelib')
453 platlib = paths.pop('platlib')
454
455 # Make a pure wheel with default tags
456 paths['purelib'] = purelib
457 wheel = Wheel('%s-%s' % (name, version))
458 wheel.dirname = workdir
459 wheel.build(paths)
460 expected = {
461 'name': name,
462 'version': version,
463 'pyver': [PYVER],
464 'abi': ['none'],
465 'arch': ['any'],
466 'filename': 'dummy-0.1-%s-none-any.whl' % PYVER,
467 }
468 self.check_built_wheel(wheel, expected)
469 # Make a pure wheel with custom tags
470 pyver = [PYVER[:-1], PYVER]
471 wheel.build(paths, {'pyver': pyver})
472 expected = {
473 'name': name,
474 'version': version,
475 'pyver': pyver,
476 'abi': ['none'],
477 'arch': ['any'],
478 'filename': 'dummy-0.1-%s-none-any.whl' % '.'.join(pyver),
479 }
480 self.check_built_wheel(wheel, expected)
481
482 # Make a non-pure wheel with default tags
483 # On this last build in the test, set a buildver and check the metadata
484 paths.pop('purelib')
485 paths['platlib'] = platlib
486 wheel.buildver = '1foobar'
487 wheel.build(paths)
488 expected['pyver'] = [IMPVER]
489 expected['abi'] = [ABI]
490 expected['arch'] = [ARCH]
491 expected['filename'] = 'dummy-0.1-%s-%s-%s-%s.whl' % (wheel.buildver, IMPVER, ABI, ARCH)
492 self.check_built_wheel(wheel, expected)
493 self.check_built_metadata(wheel)
494
495 def do_build_and_install(self, dist):
496 srcdir = tempfile.mkdtemp()
497 self.addCleanup(shutil.rmtree, srcdir)
498 dstdir = tempfile.mkdtemp()
499 self.addCleanup(shutil.rmtree, dstdir)
500
501 paths = install_dist(dist, srcdir)
502 paths['prefix'] = srcdir
503 w = Wheel()
504 w.name = paths.pop('name')
505 w.version = paths.pop('version')
506 w.dirname = srcdir
507 pathname = w.build(paths)
508 self.assertTrue(os.path.exists(pathname))
509
510 paths = {'prefix': dstdir}
511 for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
512 paths[key] = os.path.join(dstdir, key)
513 w = Wheel(pathname)
514 maker = ScriptMaker(None, None, add_launchers=False)
515 maker.executable = os.path.join(paths['scripts'], 'python')
516 dist = w.install(paths, maker)
517 self.assertIsNotNone(dist)
518 self.assertEqual(dist.name, w.name)
519 self.assertEqual(dist.version, w.version)
520 shared = dist.shared_locations
521 self.assertTrue(shared)
522 os.remove(pathname)
523 sm = Manifest(srcdir)
524 sm.findall()
525 sfiles = set([os.path.relpath(p, srcdir) for p in sm.allfiles])
526 dm = Manifest(dstdir)
527 dm.findall()
528 dfiles = set([os.path.relpath(p, dstdir) for p in dm.allfiles])
529 omitted = sfiles - dfiles
530 omitted = omitted.pop()
531 endings = os.path.join('.dist-info', 'WHEEL'), '.pyc', '.pyo'
532 self.assertTrue(omitted.endswith(endings))
533
534 def test_version_incompatibility(self):
535
536 class Warner(object):
537
538 def __call__(self, wheel_version, file_version):
539 self.wheel_version = wheel_version
540 self.file_version = file_version
541
542 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
543 dstdir = tempfile.mkdtemp()
544 self.addCleanup(shutil.rmtree, dstdir)
545 w = Wheel(fn)
546 paths = {'prefix': dstdir}
547 for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
548 paths[key] = os.path.join(dstdir, key)
549 warner = Warner()
550 maker = ScriptMaker(None, None)
551 w.install(paths, maker, warner=warner)
552 self.assertEqual(warner.wheel_version, w.wheel_version)
553 self.assertEqual(warner.file_version, (2, 0))
554 # Now set the wheel's instance to the higher value and ensure
555 # warner isn't called
556 warner = Warner()
557 w.wheel_version = (2, 0)
558 w.install(paths, maker, warner=warner)
559 self.assertFalse(hasattr(warner, 'wheel_version'))
560 self.assertFalse(hasattr(warner, 'file_version'))
561
562 def test_custom_executable(self):
563 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
564 for executable in 'mypython', None:
565 dstdir = tempfile.mkdtemp()
566 self.addCleanup(shutil.rmtree, dstdir)
567 w = Wheel(fn)
568 paths = {'prefix': dstdir}
569 for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
570 paths[key] = os.path.join(dstdir, key)
571 maker = ScriptMaker(None, None)
572 maker.variants = set([''])
573 maker.executable = executable
574 w.install(paths, maker)
575 # On Windows there will be an exe file, and on POSIX a text file.
576 # The test is structured to not care.
577 p = paths['scripts']
578 # there should be just one file in the directory - dummy.py/dummy.exe
579 p = os.path.join(p, os.listdir(p)[0])
580 with open(p, 'rb') as f:
581 data = f.read()
582 if executable is None:
583 expected = fsencode(get_executable())
584 else:
585 expected = executable.encode('utf-8')
586 expected = b'#!' + expected + b' -E'
587 if not sysconfig.is_python_build():
588 self.assertIn(expected, data)
589
590 def test_verify(self):
591 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
592 w = Wheel(fn)
593 w.verify()
594 # see issue 115
595 fn = os.path.join(HERE, 'valid_wheel-0.0.1-py3-none-any.whl')
596 w = Wheel(fn)
597 w.verify()
598 fn = os.path.join(HERE, 'bad_wheels', 'dummy-0.1-py27-none-any.whl')
599 w = Wheel(fn)
600 self.assertRaises(DistlibException, w.verify)
601
602 def wheel_modifier_nop(self, path_map):
603 return False
604
605 def wheel_modifier(self, path_map):
606 mdpath = path_map['dummy-0.1.dist-info/%s' % LEGACY_METADATA_FILENAME]
607 md = Metadata(path=mdpath)
608 md.add_requirements(['numpy'])
609 md.write(path=mdpath, legacy=True)
610 return True
611
612 def wheel_modifier_ver(self, path_map):
613 mdpath = path_map['dummy-0.1.dist-info/%s' % LEGACY_METADATA_FILENAME]
614 md = Metadata(path=mdpath)
615 md.version = '0.1+123'
616 md.write(path=mdpath, legacy=True)
617 return True
618
619 def test_update(self):
620 workdir = tempfile.mkdtemp()
621 self.addCleanup(shutil.rmtree, workdir)
622 fn = 'dummy-0.1-py27-none-any.whl'
623 sfn = os.path.join(HERE, fn)
624 dfn = os.path.join(workdir, fn)
625 shutil.copyfile(sfn, dfn)
626 mtime = os.stat(dfn).st_mtime
627 w = Wheel(dfn)
628 modified = w.update(self.wheel_modifier_nop)
629 self.assertFalse(modified)
630 self.assertEqual(mtime, os.stat(dfn).st_mtime)
631 modified = w.update(self.wheel_modifier)
632 self.assertTrue(modified)
633 self.assertLessEqual(mtime, os.stat(dfn).st_mtime)
634 w = Wheel(dfn)
635 w.verify()
636 md = w.metadata
637 self.assertEqual(md.run_requires, ['numpy'])
638 self.assertEqual(md.version, '0.1+1')
639
640 modified = w.update(self.wheel_modifier_ver)
641 self.assertTrue(modified)
642 self.assertLessEqual(mtime, os.stat(dfn).st_mtime)
643 w = Wheel(dfn)
644 w.verify()
645 md = w.metadata
646 self.assertEqual(md.run_requires, ['numpy'])
647 self.assertEqual(md.version, '0.1+123')
648
649 def test_info(self):
650 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
651 w = Wheel(fn)
652 actual = w.info
653 actual.pop('Generator', None)
654 expected = {'Root-Is-Purelib': 'true', 'Tag': 'py27-none-any', 'Wheel-Version': '2.0'}
655 self.assertEqual(actual, expected)
656
657 @unittest.skipIf(sys.version_info[:2] != (2, 7), 'The test wheel is only '
658 '2.7 mountable')
659 def test_mount(self):
660 fn = os.path.join(HERE, 'dummy-0.1-py27-none-any.whl')
661 w = Wheel(fn)
662 self.assertNotIn(fn, sys.path)
663 w.mount()
664 self.assertIn(fn, sys.path)
665 w.unmount()
666 self.assertNotIn(fn, sys.path)
667
668 def test_mount_extensions(self):
669 if PYVER == 'py27':
670 fn = 'minimext-0.1-cp27-none-linux_x86_64.whl'
671 elif PYVER == 'py32':
672 fn = 'minimext-0.1-cp32-cp32mu-linux_x86_64.whl'
673 elif PYVER == 'py33':
674 fn = 'minimext-0.1-cp33-cp33m-linux_x86_64.whl'
675 else:
676 fn = None
677 if not fn: # pragma: no cover
678 raise unittest.SkipTest('Suitable wheel not found.')
679 fn = os.path.join(HERE, fn)
680 w = Wheel(fn)
681 if not w.is_compatible() or not w.is_mountable(): # pragma: no cover
682 raise unittest.SkipTest('Wheel not suitable for mounting.')
683 self.assertRaises(ImportError, __import__, 'minimext')
684 w.mount()
685 mod = __import__('minimext')
686 self.assertIs(mod, sys.modules['minimext'])
687 self.assertEqual(mod.fib(10), 55)
688 w.unmount()
689 del sys.modules['minimext']
690 self.assertRaises(ImportError, __import__, 'minimext')
691
692 # The EXTENSIONS map in a wheel's .dist-info is attacker-controlled.
693 # install()/update()/verify() already reject archive entries whose
694 # directory portions contain '..', but mount() -> _get_extensions()
695 # did not apply the same check, so a crafted EXTENSIONS entry could
696 # name a cache destination outside the per-wheel dylib cache. mount()
697 # must refuse such a wheel (this mirrors the '..' guard used
698 # elsewhere in this module; the raw extraction is separately
699 # sanitised by the stdlib, so this is a missing-confinement
700 # consistency fix rather than a self-contained RCE).
701 import json
702
703 name, version = 'evilext', '0.1'
704 # Build a filename whose tag is compatible with the running
705 # interpreter, so is_compatible() is True and mount() reaches
706 # _get_extensions().
707 fn = '%s-%s-%s-%s-%s.whl' % (name, version, IMPVER, ABI, ARCH)
708 workdir = tempfile.mkdtemp()
709 try:
710 pathname = os.path.join(workdir, fn)
711 info_dir = '%s-%s.dist-info' % (name, version)
712 extensions = {'evilext._mod': '../../../../tmp/distlib_pwned.so'}
713 with ZipFile(pathname, 'w') as zf:
714 zf.writestr('%s/WHEEL' % info_dir,
715 'Wheel-Version: 1.0\nGenerator: test\n'
716 'Root-Is-Purelib: false\n'
717 'Tag: %s-%s-%s\n' % (IMPVER, ABI, ARCH))
718 zf.writestr('%s/METADATA' % info_dir,
719 'Metadata-Version: 2.1\nName: %s\n'
720 'Version: %s\n' % (name, version))
721 zf.writestr('%s/EXTENSIONS' % info_dir, json.dumps(extensions))
722 zf.writestr('%s/RECORD' % info_dir, '')
723 w = Wheel(pathname)
724 self.assertTrue(w.is_compatible())
725 try:
726 self.assertRaises(DistlibException, w.mount)
727 finally:
728 # mount() inserts the wheel on sys.path before reading
729 # EXTENSIONS; make sure a failed mount leaves no trace.
730 if pathname in sys.path:
731 w.unmount()
732 self.assertNotIn(pathname, sys.path)
733 finally:
734 shutil.rmtree(workdir)
735
736
737 def test_local_version(self):
738 w = Wheel('dummy-0.1_1.2')
739 self.assertEqual(w.filename, 'dummy-0.1_1.2-%s'
740 '-none-any.whl' % PYVER)
741 self.assertEqual(w.name, 'dummy')
742 self.assertEqual(w.version, '0.1-1.2')
743 self.assertFalse(w.exists)
744 w.version = '0.1-1.3'
745 self.assertEqual(w.filename, 'dummy-0.1_1.3-%s'
746 '-none-any.whl' % PYVER)
747
748 def test_abi(self):
749 pyver = sysconfig.get_config_var('py_version_nodot')
750 if not pyver:
751 pyver = '%s%s' % sys.version_info[:2]
752 parts = ['cp', pyver]
753 if sysconfig.get_config_var('Py_DEBUG'):
754 parts.append('d')
755 # Starting with 3.8, the SOABI doesn't append m when WITH_PYMALLOC is
756 # defined (see bpo-36707)
757 vi = sys.version_info[:2]
758 if IMP_PREFIX == 'cp':
759 if vi < (3, 8):
760 wpm = sysconfig.get_config_var('WITH_PYMALLOC')
761 if wpm or wpm is None:
762 parts.append('m')
763 if vi < (3, 3):
764 us = sysconfig.get_config_var('Py_UNICODE_SIZE')
765 if us == 4 or (us is None and sys.maxunicode == 0x10FFFF):
766 parts.append('u')
767 if bool(sysconfig.get_config_var("Py_GIL_DISABLED")):
768 parts.append('t')
769 if vi < (3, 5):
770 abi = ABI
771 else:
772 abi = ABI.split('-')[0]
773 self.assertEqual(''.join(parts), abi)
774
775 @unittest.skipIf('SKIP_ONLINE' in os.environ, 'Skipping online test')
776 @unittest.skipUnless(PIP_AVAILABLE, 'pip is needed for this test')
777 @unittest.skipIf(sys.version_info[:2] >= (3, 7), 'The test distribution is not '
778 '3.7+ compatible')
779 def test_build_and_install_pure(self):
780 if pip_version() >= (20, 2, 0):
781 raise unittest.SkipTest('Test not supported by pip version')
782 self.do_build_and_install('sarge == 0.1')
783
784 @unittest.skipIf('SKIP_ONLINE' in os.environ, 'Skipping online test')
785 @unittest.skipIf(hasattr(sys, 'pypy_version_info'), 'The test distribution'
786 ' does not build on PyPy')
787 @unittest.skipIf(sys.platform != 'linux2', 'The test distribution only '
788 'builds on Linux')
789 @unittest.skipUnless(PIP_AVAILABLE, 'pip is needed for this test')
790 def test_build_and_install_plat(self):
791 if pip_version() >= (20, 2, 0):
792 raise unittest.SkipTest('Test not supported by pip version')
793 self.do_build_and_install('hiredis == 0.1.1')
794
795 @unittest.skipIf('SKIP_ONLINE' in os.environ, 'Skipping online test')
796 @unittest.skipIf(sys.version_info[0] == 3, 'The test distribution is not '
797 '3.x compatible')
798 @unittest.skipUnless(PIP_AVAILABLE, 'pip is needed for this test')
799 def test_build_and_install_data(self):
800 if pip_version() >= (20, 2, 0):
801 raise unittest.SkipTest('Test not supported by pip version')
802 self.do_build_and_install('Werkzeug == 0.5')
803
804 @unittest.skipIf('SKIP_ONLINE' in os.environ, 'Skipping online test')
805 @unittest.skipIf(sys.version_info[0] == 3, 'The test distribution is not '
806 '3.x compatible')
807 @unittest.skipUnless(PIP_AVAILABLE, 'pip is needed for this test')
808 def test_build_and_install_scripts(self):
809 if pip_version() >= (20, 2, 0):
810 raise unittest.SkipTest('Test not supported by pip version')
811 self.do_build_and_install('Babel == 0.9.6')
812
813 def test_path_doesnt_escape(self):
814 workdir = tempfile.mkdtemp(prefix='distlib-test-')
815 self.addCleanup(shutil.rmtree, workdir)
816 maker = ScriptMaker(None, None)
817 root = os.path.join(workdir, "venv_root")
818 purelib = os.path.join(root, "lib", "site-packages")
819 scripts = os.path.join(root, "bin")
820 for d in (purelib, scripts):
821 os.makedirs(d)
822 paths = {
823 "prefix": root,
824 "purelib": purelib,
825 "platlib": purelib,
826 "scripts": scripts,
827 "headers": os.path.join(root, "include"),
828 "data": root,
829 }
830 fn = os.path.join(HERE, 'evilpkg-1.0-py3-none-any.whl')
831 w = Wheel(fn)
832 with self.assertRaises(DistlibException) as ctx:
833 w.install(paths, maker)
834 self.assertIn('Wheel member escapes installation directory', str(ctx.exception))
835
836
837 if __name__ == '__main__': # pragma: no cover
838 import logging
839 logging.basicConfig(level=logging.DEBUG, filename='test_wheel.log', filemode='w', format='%(message)s')
840 unittest.main()