Debian Codegraph @

tests/test_util.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2012-2026 Vinay Sajip.
4 # Licensed to the Python Software Foundation under a contributor agreement.
5 # See LICENSE.txt and CONTRIBUTORS.txt.
6 #
7 from io import BytesIO
8 from itertools import islice
9 import os
10 import re
11 import shutil
12 try:
13 import ssl
14 except ImportError:
15 ssl = None
16 import sys
17 import tempfile
18 import textwrap
19 import time
20
21 from compat import unittest
22 from support import TempdirManager, DistlibTestCase, in_github_workflow
23
24 from distlib import DistlibException
25 from distlib.compat import cache_from_source
26 from distlib.util import (get_export_entry, ExportEntry, resolve, get_cache_base, path_to_cache_dir, zip_dir,
27 parse_credentials, ensure_slash, split_filename, EventMixin, Sequencer, unarchive, Progress,
28 iglob, RICH_GLOB, parse_requirement, get_extras, Configurator, read_exports, write_exports,
29 FileOperator, is_string_sequence, get_package_data, convert_path)
30
31 HERE = os.path.dirname(os.path.abspath(__file__))
32 IN_GITHUB_WORKFLOW = in_github_workflow()
33
34
35 class TestContainer(object):
36
37 def __init__(self, *args, **kwargs):
38 self.args = args
39 self.kwargs = kwargs
40
41
42 class UtilTestCase(DistlibTestCase):
43
44 def check_entry(self, entry, name, prefix, suffix, flags):
45 self.assertEqual(entry.name, name)
46 self.assertEqual(entry.prefix, prefix)
47 self.assertEqual(entry.suffix, suffix)
48 self.assertEqual(entry.flags, flags)
49
50 def test_export_entry(self):
51 self.assertIsNone(get_export_entry('foo.py'))
52 self.assertIsNone(get_export_entry('foo.py='))
53 for spec in ('foo=foo:main', 'foo =foo:main', 'foo= foo:main', 'foo = foo:main'):
54 self.check_entry(get_export_entry(spec), 'foo', 'foo', 'main', [])
55 self.check_entry(get_export_entry('foo=foo.bar:main'), 'foo', 'foo.bar', 'main', [])
56 self.check_entry(get_export_entry('foo=foo.bar:main [a]'), 'foo', 'foo.bar', 'main', ['a'])
57 # See issue #127 - allow hyphens
58 self.check_entry(get_export_entry('foo=foo.bar:main [with-foo]'), 'foo', 'foo.bar', 'main', ['with-foo'])
59 self.check_entry(get_export_entry('foo=foo.bar:main [ a ]'), 'foo', 'foo.bar', 'main', ['a'])
60 self.check_entry(get_export_entry('foo=foo.bar:main [a=b, c=d,e, f=g]'), 'foo', 'foo.bar', 'main',
61 ['a=b', 'c=d', 'e', 'f=g'])
62 self.check_entry(get_export_entry('foo=foo.bar:main [a=9, 9=8,e, f9=g8]'), 'foo', 'foo.bar', 'main',
63 ['a=9', '9=8', 'e', 'f9=g8'])
64 self.check_entry(get_export_entry('foo=foo.bar:main[x]'), 'foo', 'foo.bar', 'main', ['x'])
65 self.check_entry(get_export_entry('foo=abc'), 'foo', 'abc', None, [])
66 self.check_entry(get_export_entry('smc++ = smcpp.frontend:console'), 'smc++', 'smcpp.frontend', 'console', [])
67 # See issue #203 - correct name parsing to allow non-name-like names like ","
68 self.check_entry(get_export_entry(', = comma:main'), ',', 'comma', 'main', [])
69 self.check_entry(get_export_entry(',comma = comma:main'), ',comma', 'comma', 'main', [])
70
71 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x:y')
72 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x [')
73 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x ]')
74 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x []')
75 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x [\\]')
76 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x [a=]')
77 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x [a,]')
78 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x [a,,b]')
79 self.assertRaises(DistlibException, get_export_entry, 'foo=foo.bar:x [a b]')
80
81 def test_resolve(self):
82 import logging
83 import logging.handlers
84 self.assertIs(resolve('logging', None), logging)
85 self.assertIs(resolve('logging.handlers', None), logging.handlers)
86 self.assertIs(resolve('logging', 'root'), logging.root)
87 self.assertEqual(resolve('logging', 'root.debug'), logging.root.debug)
88
89 def test_cache_base(self):
90 actual = get_cache_base()
91 if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
92 expected = os.path.expandvars('$localappdata')
93 else:
94 expected = os.path.expanduser('~')
95 expected = os.path.join(expected, '.distlib')
96 self.assertEqual(expected, actual)
97 self.assertTrue(os.path.isdir(expected))
98
99 @unittest.skipIf(os.name != 'posix', 'Test is only valid for POSIX')
100 def test_path_to_cache_dir_posix(self):
101 self.assertEqual(path_to_cache_dir('/home/user/some-file.zip'), '--home--user--some-file.zip.cache')
102 self.assertEqual(
103 path_to_cache_dir('path/to/some-file.zip'),
104 os.path.splitext(path_to_cache_dir(os.path.dirname(HERE)))[0] + '--path--to--some-file.zip.cache')
105 self.assertEqual(path_to_cache_dir('path/to/some-file.zip', use_abspath=False), 'path--to--some-file.zip.cache')
106
107 @unittest.skipIf(os.name != 'nt', 'Test is only valid for Windows')
108 def test_path_to_cache_dir_nt(self):
109 self.assertEqual(path_to_cache_dir(r'c:\Users\User\Some-File.zip'), 'c-----Users--User--Some-File.zip.cache')
110
111 def test_parse_credentials(self):
112 cases = (
113 ('example.com', (None, None, 'example.com')),
114 ('[email protected]', ('user', None, 'example.com')),
115 ('user:[email protected]', ('user', 'pwd', 'example.com')),
116 ('user:@example.com', ('user', '', 'example.com')),
117 ('user:pass@[email protected]', ('user', 'pass@word', 'example.com')),
118 ('user:pass:[email protected]', ('user', 'pass:word', 'example.com')),
119 ('user%3Aname:%23%5E%[email protected]', ('user:name', '#^@', 'example.com')),
120 )
121
122 for s, expected in cases:
123 self.assertEqual(parse_credentials(s), expected)
124
125 def test_ensure_slash(self):
126 self.assertEqual(ensure_slash(''), '/')
127 self.assertEqual(ensure_slash('/'), '/')
128 self.assertEqual(ensure_slash('abc'), 'abc/')
129 self.assertEqual(ensure_slash('def/'), 'def/')
130
131 def test_split_filename(self):
132 self.assertIsNone(split_filename('abl.jquery'))
133 self.assertEqual(split_filename('abl.jquery-1.4.2-2'), ('abl.jquery', '1.4.2-2', None))
134 self.assertEqual(split_filename('python-gnupg-0.1'), ('python-gnupg', '0.1', None))
135 self.assertEqual(split_filename('baklabel-1.0.3-2729-py3.2'), ('baklabel', '1.0.3-2729', '3.2'))
136 self.assertEqual(split_filename('baklabel-1.0.3-2729-py27'), ('baklabel', '1.0.3-2729', '27'))
137 self.assertEqual(split_filename('advpy-0.99b'), ('advpy', '0.99b', None))
138 self.assertEqual(split_filename('asv_files-dev-20120501-01', 'asv_files'),
139 ('asv_files', 'dev-20120501-01', None))
140 self.assertEqual(split_filename('greenlet-0.4.0-py27-win32'), ('greenlet', '0.4.0', '27'))
141 self.assertEqual(split_filename('greenlet-0.4.0-py27-linux_x86_64'), ('greenlet', '0.4.0', '27'))
142 self.assertEqual(split_filename('django-altuser-v0.6.8'), ('django-altuser', 'v0.6.8', None))
143 self.assertEqual(split_filename('youtube_dl_server-alpha.1'), ('youtube_dl_server', 'alpha.1', None))
144 self.assertEqual(split_filename('pytest-xdist-dev'), ('pytest-xdist', 'dev', None))
145 self.assertEqual(split_filename('pytest_xdist-0.1_myfork', None), ('pytest_xdist', '0.1_myfork', None))
146 self.assertEqual(split_filename('pytest_xdist-0.1_myfork', 'pytest-xdist'),
147 ('pytest_xdist', '0.1_myfork', None))
148 self.assertEqual(split_filename('pytest_xdist-0.1_myfork', 'pytest_dist'), ('pytest_xdist', '0.1_myfork', None))
149
150 def test_convert_path(self):
151 CP = convert_path
152 if os.sep == '/':
153 d = os.path.dirname(__file__)
154 self.assertEqual(CP(d), d)
155 else:
156 self.assertEqual(CP(''), '')
157 self.assertRaises(ValueError, CP, '/foo')
158 self.assertRaises(ValueError, CP, 'foo/')
159
160 def test_events(self):
161 collected = []
162
163 def handler1(e, *args, **kwargs):
164 collected.append((1, e, args, kwargs))
165
166 def handler2(e, *args, **kwargs):
167 collected.append((2, e, args, kwargs))
168
169 def handler3(e, *args, **kwargs):
170 if not args:
171 raise NotImplementedError('surprise!')
172 collected.append((3, e, args, kwargs))
173 return (args, kwargs)
174
175 e = EventMixin()
176 e.add('A', handler1)
177 self.assertRaises(ValueError, e.remove, 'B', handler1)
178
179 cases = (
180 ((1, 2), {
181 'buckle': 'my shoe'
182 }),
183 ((3, 4), {
184 'shut': 'the door'
185 }),
186 )
187
188 for case in cases:
189 e.publish('A', *case[0], **case[1])
190 e.publish('B', *case[0], **case[1])
191
192 for actual, source in zip(collected, cases):
193 self.assertEqual(actual, (1, 'A') + source[:1] + source[1:])
194
195 collected = []
196 e.add('B', handler2)
197
198 self.assertEqual(tuple(e.get_subscribers('A')), (handler1, ))
199 self.assertEqual(tuple(e.get_subscribers('B')), (handler2, ))
200 self.assertEqual(tuple(e.get_subscribers('C')), ())
201
202 for case in cases:
203 e.publish('A', *case[0], **case[1])
204 e.publish('B', *case[0], **case[1])
205
206 actuals = islice(collected, 0, None, 2)
207 for actual, source in zip(actuals, cases):
208 self.assertEqual(actual, (1, 'A') + source[:1] + source[1:])
209
210 actuals = islice(collected, 1, None, 2)
211 for actual, source in zip(actuals, cases):
212 self.assertEqual(actual, (2, 'B') + source[:1] + source[1:])
213
214 e.remove('B', handler2)
215
216 collected = []
217
218 for case in cases:
219 e.publish('A', *case[0], **case[1])
220 e.publish('B', *case[0], **case[1])
221
222 for actual, source in zip(collected, cases):
223 self.assertEqual(actual, (1, 'A') + source[:1] + source[1:])
224
225 e.add('C', handler3)
226
227 collected = []
228 returned = []
229
230 for case in cases:
231 returned.extend(e.publish('C', *case[0], **case[1]))
232 returned.extend(e.publish('C'))
233
234 for actual, source in zip(collected, cases):
235 self.assertEqual(actual, (3, 'C') + source[:1] + source[1:])
236
237 self.assertEqual(tuple(islice(returned, 1, None, 2)), (None, None))
238 actuals = islice(returned, 0, None, 2)
239 for actual, expected in zip(actuals, cases):
240 self.assertEqual(actual, expected)
241
242 def test_sequencer_basic(self):
243 seq = Sequencer()
244
245 steps = (('check', 'sdist'), ('check', 'register'), ('check', 'sdist'), ('check', 'register'),
246 ('register', 'upload_sdist'), ('sdist', 'upload_sdist'), ('check', 'build_clibs'),
247 ('build_clibs', 'build_ext'), ('build_ext', 'build_py'), ('build_py', 'build_scripts'),
248 ('build_scripts', 'build'), ('build', 'test'), ('register', 'upload_bdist'), ('build', 'upload_bdist'),
249 ('build', 'install_headers'), ('install_headers', 'install_lib'), ('install_lib', 'install_scripts'),
250 ('install_scripts', 'install_data'), ('install_data', 'install_distinfo'), ('install_distinfo',
251 'install'))
252
253 for pred, succ in steps:
254 seq.add(pred, succ)
255
256 # Note: these tests are sensitive to dictionary ordering
257 # but work under Python 2.6, 2.7, 3.2, 3.3, 3.4 and PyPy 2.5
258 cases = (
259 ('check', ['check']),
260 ('register', ['check', 'register']),
261 ('sdist', ['check', 'sdist']),
262 ('build_clibs', ['check', 'build_clibs']),
263 ('build_ext', ['check', 'build_clibs', 'build_ext']),
264 ('build_py', ['check', 'build_clibs', 'build_ext', 'build_py']),
265 ('build_scripts', ['check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts']),
266 ('build', ['check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build']),
267 ('test', ['check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'test']),
268 ('install_headers',
269 ['check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'install_headers']),
270 ('install_lib', [
271 'check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'install_headers',
272 'install_lib'
273 ]),
274 ('install_scripts', [
275 'check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'install_headers',
276 'install_lib', 'install_scripts'
277 ]),
278 ('install_data', [
279 'check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'install_headers',
280 'install_lib', 'install_scripts', 'install_data'
281 ]),
282 ('install_distinfo', [
283 'check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'install_headers',
284 'install_lib', 'install_scripts', 'install_data', 'install_distinfo'
285 ]),
286 ('install', [
287 'check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'install_headers',
288 'install_lib', 'install_scripts', 'install_data', 'install_distinfo', 'install'
289 ]),
290 ('upload_sdist', (['check', 'register', 'sdist',
291 'upload_sdist'], ['check', 'sdist', 'register', 'upload_sdist'])),
292 ('upload_bdist',
293 (['check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'build', 'register', 'upload_bdist'],
294 ['check', 'build_clibs', 'build_ext', 'build_py', 'build_scripts', 'register', 'build', 'upload_bdist'])),
295 )
296
297 for final, expected in cases:
298 actual = list(seq.get_steps(final))
299 if isinstance(expected, tuple):
300 self.assertIn(actual, expected)
301 else:
302 self.assertEqual(actual, expected)
303
304 dot = seq.dot
305 expected = '''
306 digraph G {
307 check -> build_clibs;
308 install_lib -> install_scripts;
309 register -> upload_bdist;
310 build -> upload_bdist;
311 build_ext -> build_py;
312 install_scripts -> install_data;
313 check -> sdist;
314 check -> register;
315 build -> install_headers;
316 install_data -> install_distinfo;
317 sdist -> upload_sdist;
318 register -> upload_sdist;
319 install_distinfo -> install;
320 build -> test;
321 install_headers -> install_lib;
322 build_py -> build_scripts;
323 build_clibs -> build_ext;
324 build_scripts -> build;
325 }
326 '''
327 expected = textwrap.dedent(expected).strip().splitlines()
328 actual = dot.splitlines()
329 self.assertEqual(expected[0], actual[0])
330 self.assertEqual(expected[-1], actual[-1])
331 self.assertEqual(set(expected[1:-1]), set(actual[1:-1]))
332 actual = seq.strong_connections
333 expected = (
334 [('test', ), ('upload_bdist', ), ('install', ), ('install_distinfo', ), ('install_data', ),
335 ('install_scripts', ), ('install_lib', ), ('install_headers', ), ('build', ), ('build_scripts', ),
336 ('build_py', ), ('build_ext', ), ('build_clibs', ), ('upload_sdist', ), ('sdist', ), ('register', ),
337 ('check', )],
338 [('install', ), ('install_distinfo', ), ('install_data', ), ('install_scripts', ), ('install_lib', ),
339 ('install_headers', ), ('test', ), ('upload_bdist', ), ('build', ), ('build_scripts', ), ('build_py', ),
340 ('build_ext', ), ('build_clibs', ), ('upload_sdist', ), ('sdist', ), ('register', ), ('check', )],
341 [('upload_sdist', ), ('sdist', ), ('install', ), ('install_distinfo', ), ('install_data', ),
342 ('upload_bdist', ), ('register', ), ('install_scripts', ), ('install_lib', ), ('install_headers', ),
343 ('test', ), ('build', ), ('build_scripts', ), ('build_py', ), ('build_ext', ), ('build_clibs', ),
344 ('check', )],
345 # Next case added for PyPy
346 [('upload_sdist', ), ('sdist', ), ('upload_bdist', ), ('register', ), ('test', ), ('install', ),
347 ('install_distinfo', ), ('install_data', ),
348 ('install_scripts', ), ('install_lib', ), ('install_headers', ), ('build', ), ('build_scripts', ),
349 ('build_py', ), ('build_ext', ), ('build_clibs', ), ('check', )],
350 # Next case added for Python 3.6
351 [('upload_sdist', ), ('sdist', ), ('upload_bdist', ), ('register', ), ('install', ), ('install_distinfo', ),
352 ('install_data', ), ('install_scripts', ), ('install_lib', ), ('install_headers', ), ('test', ),
353 ('build', ), ('build_scripts', ), ('build_py', ), ('build_ext', ), ('build_clibs', ), ('check', )],
354 # Next case added for Python 3.11
355 [('upload_sdist', ), ('sdist', ), ('install', ), ('install_distinfo', ), ('install_data', ),
356 ('install_scripts', ), ('install_lib', ), ('install_headers', ), ('test', ), ('upload_bdist', ),
357 ('build', ), ('build_scripts', ), ('build_py', ), ('build_ext', ), ('build_clibs', ), ('register', ),
358 ('check', )])
359 self.assertIn(actual, expected)
360
361 def test_sequencer_cycle(self):
362 seq = Sequencer()
363 seq.add('A', 'B')
364 seq.add('B', 'C')
365 seq.add('C', 'D')
366 self.assertEqual(list(seq.get_steps('D')), ['A', 'B', 'C', 'D'])
367 seq.add('C', 'A')
368 self.assertEqual(list(seq.get_steps('D')), ['C', 'A', 'B', 'D'])
369 self.assertFalse(seq.is_step('E'))
370 self.assertRaises(ValueError, seq.get_steps, 'E')
371 seq.add_node('E')
372 self.assertTrue(seq.is_step('E'))
373 self.assertEqual(list(seq.get_steps('E')), ['E'])
374 seq.remove_node('E')
375 self.assertFalse(seq.is_step('E'))
376 self.assertRaises(ValueError, seq.get_steps, 'E')
377 seq.remove('C', 'A')
378 self.assertEqual(list(seq.get_steps('D')), ['A', 'B', 'C', 'D'])
379
380 def test_sequencer_removal(self):
381 seq = Sequencer()
382 seq.add('A', 'B')
383 seq.add('B', 'C')
384 seq.add('C', 'D')
385 preds = {'B': set(['A']), 'C': set(['B']), 'D': set(['C'])}
386 succs = {'A': set(['B']), 'B': set(['C']), 'C': set(['D'])}
387 self.assertEqual(seq._preds, preds)
388 self.assertEqual(seq._succs, succs)
389 seq.remove_node('C')
390 self.assertEqual(seq._preds, preds)
391 self.assertEqual(seq._succs, succs)
392 seq.remove_node('C', True)
393 self.assertEqual(seq._preds, {'B': set(['A'])})
394 self.assertEqual(seq._succs, {'A': set(['B'])})
395
396 def test_unarchive(self):
397 import io, zipfile, tarfile
398
399 good_archives = (
400 ('good.zip', zipfile.ZipFile, 'r', 'namelist'),
401 ('good.tar', tarfile.open, 'r', 'getnames'),
402 ('good.tar.gz', tarfile.open, 'r:gz', 'getnames'),
403 ('good.tar.bz2', tarfile.open, 'r:bz2', 'getnames'),
404 )
405 bad_archives = ('bad.zip', 'bad.tar', 'bad.tar.gz', 'bad.tar.bz2')
406
407 # Test "evil" tarball on 3.12 *or* on Python with PEP-706 backported
408 if sys.version_info > (3, 12) or hasattr(tarfile, 'data_filter'):
409 bad_archives += ('evil.tar.gz', )
410
411 for name, cls, mode, lister in good_archives:
412 td = tempfile.mkdtemp()
413 archive = None
414 try:
415 name = os.path.join(HERE, name)
416 unarchive(name, td)
417 archive = cls(name, mode)
418 names = getattr(archive, lister)()
419 for name in names:
420 p = os.path.join(td, name)
421 self.assertTrue(os.path.exists(p))
422 finally:
423 shutil.rmtree(td)
424 if archive:
425 archive.close()
426
427 for name in bad_archives:
428 name = os.path.join(HERE, name)
429 td = tempfile.mkdtemp()
430 try:
431 # OSError is raised on Windows on CPython 3.13, pypy-3.11
432 self.assertRaises((OSError, ValueError), unarchive, name, td)
433 finally:
434 shutil.rmtree(td)
435
436 # A tar member name being inside dest_dir says nothing about where a
437 # symlink/hardlink member *points*. A link whose target escapes
438 # dest_dir is the dangerous primitive: a subsequent member written
439 # *through* that link (or the link itself being followed later) drops
440 # data outside the destination. unarchive(check=True) must reject any
441 # archive that contains such a link, and must not create an escaping
442 # link or file on disk.
443 #
444 # Note on Python versions: unarchive() installs tarfile.tar_filter
445 # as its extraction filter on Pythons that support PEP-706 (3.12+,
446 # or backports). tar_filter permits symlinks/hardlinks whose *target*
447 # escapes the destination (only the stricter data_filter rejects
448 # those), so the escaping link is created even there. On 3.8 - 3.11
449 # there are no extraction filters at all. In every case unarchive's
450 # own link check is the guard this test relies on, so the test holds
451 # across all supported Pythons.
452
453 def make_link_tar(path, linktype, linkname, with_payload):
454 with tarfile.open(path, 'w:gz') as tf:
455 ti = tarfile.TarInfo('link')
456 ti.type = linktype
457 ti.linkname = linkname
458 tf.addfile(ti)
459 if with_payload:
460 data = b'PWNED'
461 fi = tarfile.TarInfo('link/escaped.txt')
462 fi.size = len(data)
463 tf.addfile(fi, io.BytesIO(data))
464
465 abs_target = os.path.join(tempfile.gettempdir(), 'distlib_unarchive_escape_target')
466 cases = (
467 ('relative symlink', tarfile.SYMTYPE, '../../../../distlib_unarchive_escape_target', True),
468 ('absolute symlink', tarfile.SYMTYPE, abs_target, False),
469 ('relative hardlink', tarfile.LNKTYPE, '../../../../distlib_unarchive_escape_target', False),
470 )
471 for label, linktype, linkname, with_payload in cases:
472 work = tempfile.mkdtemp()
473 try:
474 arc = os.path.join(work, 'evil.tar.gz')
475 make_link_tar(arc, linktype, linkname, with_payload)
476 dest = os.path.join(work, 'dest')
477 os.mkdir(dest)
478 # unarchive must refuse the archive ...
479 self.assertRaises((OSError, ValueError, DistlibException), unarchive, arc, dest, check=True)
480 # ... and must not have planted an escaping link inside dest.
481 linkpath = os.path.join(dest, 'link')
482 if os.path.islink(linkpath):
483 self.fail('%s: escaping link was created: %r -> %r' % (label, linkpath, os.readlink(linkpath)))
484 # ... and no payload may have escaped outside dest.
485 escaped = os.path.normpath(os.path.join(dest, linkname, 'escaped.txt'))
486 self.assertFalse(os.path.exists(escaped), '%s: file escaped to %r' % (label, escaped))
487 finally:
488 shutil.rmtree(work)
489
490 def test_string_sequence(self):
491 self.assertTrue(is_string_sequence(['a']))
492 self.assertTrue(is_string_sequence(['a', 'b']))
493 self.assertFalse(is_string_sequence(['a', 'b', None]))
494 self.assertRaises(AssertionError, is_string_sequence, [])
495
496 @unittest.skipIf('SKIP_ONLINE' in os.environ, 'Skipping online test')
497 @unittest.skipIf('SKIP_EXT_PACKAGE_DATA' in os.environ, 'Skipping test requiring external package data')
498 @unittest.skipUnless(ssl, 'SSL required for this test.')
499 def test_package_data(self):
500 data = get_package_data(name='config', version='0.3.6')
501 self.assertTrue(data)
502 self.assertTrue('index-metadata' in data)
503 metadata = data['index-metadata']
504 self.assertEqual(metadata['name'], 'config')
505 self.assertEqual(metadata['version'], '0.3.6')
506 data = get_package_data(name='config', version='0.3.5')
507 self.assertFalse(data)
508
509 def test_zip_dir(self):
510 d = os.path.join(HERE, 'foofoo')
511 data = zip_dir(d)
512 self.assertIsInstance(data, BytesIO)
513
514 def test_configurator(self):
515 d = {
516 'a': 1,
517 'b': 2.0,
518 'c': 'xyz',
519 'd': 'inc://' + os.path.join(HERE, 'included.json'),
520 'e': 'inc://' + 'included.json',
521 'stderr': 'ext://sys.stderr',
522 'list_o_stuff': [
523 'cfg://stderr',
524 'ext://sys.stdout',
525 'ext://logging.NOTSET',
526 ],
527 'dict_o_stuff': {
528 'k1': 'cfg://list_o_stuff[1]',
529 'k2': 'abc',
530 'k3': 'cfg://list_o_stuff',
531 },
532 'another_dict_o_stuff': {
533 'k1': 'cfg://dict_o_stuff[k2]',
534 'k2': 'ext://re.I',
535 'k3': 'cfg://dict_o_stuff[k3][0]',
536 },
537 'custom': {
538 '()': __name__ + '.TestContainer',
539 '[]': [1, 'a', 2.0, ('b', 'c', 'd')],
540 '.': {
541 'p1': 'a',
542 'p2': 'b',
543 'p3': {
544 '()': __name__ + '.TestContainer',
545 '[]': [1, 2],
546 '.': {
547 'p1': 'c',
548 },
549 },
550 },
551 'k1': 'v1',
552 'k2': 'v2',
553 }
554 }
555
556 cfg = Configurator(d, HERE)
557 self.assertEqual(cfg['a'], 1)
558 self.assertEqual(cfg['b'], 2.0)
559 self.assertEqual(cfg['c'], 'xyz')
560 self.assertIs(cfg['stderr'], sys.stderr)
561 self.assertIs(cfg['list_o_stuff'][0], sys.stderr)
562 self.assertIs(cfg['list_o_stuff'][1], sys.stdout)
563 self.assertIs(cfg['list_o_stuff'][-1], 0) # logging.NOTSET == 0
564 self.assertIs(cfg['dict_o_stuff']['k1'], sys.stdout)
565 self.assertIs(cfg['another_dict_o_stuff']['k1'], 'abc')
566 self.assertIs(cfg['another_dict_o_stuff']['k2'], re.I)
567 self.assertIs(cfg['another_dict_o_stuff']['k3'], sys.stderr)
568 custom = cfg['custom']
569 self.assertIsInstance(custom, TestContainer)
570 self.assertEqual(custom.args, (1, 'a', 2.0, ('b', 'c', 'd')))
571 self.assertEqual(custom.kwargs, {'k1': 'v1', 'k2': 'v2'})
572 self.assertEqual(custom.p1, 'a')
573 self.assertEqual(custom.p2, 'b')
574 self.assertIsInstance(custom.p3, TestContainer)
575 self.assertEqual(custom.p3.args, (1, 2))
576 self.assertEqual(custom.p3.kwargs, {})
577 self.assertEqual(custom.p3.p1, 'c')
578 self.assertEqual(cfg['d'], {'foo': 'bar', 'bar': 'baz'})
579 self.assertEqual(cfg['e'], {'foo': 'bar', 'bar': 'baz'})
580
581
582 def _speed_range(min_speed, max_speed):
583 return tuple(['%d KB/s' % v for v in range(min_speed, max_speed + 1)])
584
585
586 def _eta_range(min_eta, max_eta, prefix='ETA '):
587 msg = prefix + ': 00:00:%02d'
588 return tuple([msg % v for v in range(min_eta, max_eta + 1)])
589
590
591 class ProgressTestCase(DistlibTestCase):
592 # Of late, the speed tests keep failing on Windows
593 @unittest.skipIf(IN_GITHUB_WORKFLOW, 'Test disabled on some environments due to performance')
594 def test_basic(self):
595
596 # These ranges may need tweaking to cater for especially slow
597 # machines
598 if os.name == 'nt':
599 speed1 = _speed_range(18, 20)
600 speed2 = _speed_range(20, 22)
601 else:
602 speed1 = _speed_range(16, 19)
603 speed2 = _speed_range(20, 22)
604 expected = (
605 (' 10 %', _eta_range(4, 7), speed1),
606 (' 20 %', _eta_range(4, 7), speed1),
607 (' 30 %', _eta_range(3, 4), speed1),
608 (' 40 %', _eta_range(3, 3), speed1),
609 (' 50 %', _eta_range(2, 2), speed1),
610 (' 60 %', _eta_range(2, 2), speed1),
611 (' 70 %', _eta_range(1, 1), speed1),
612 (' 80 %', _eta_range(1, 1), speed1),
613 (' 90 %', _eta_range(0, 0), speed1),
614 ('100 %', _eta_range(4, 5, 'Done'), speed2),
615 )
616 bar = Progress(maxval=100000).start()
617 for i, v in enumerate(range(10000, 100000, 10000)):
618 time.sleep(0.5)
619 bar.update(v)
620 p, e, s = expected[i]
621 self.assertEqual(bar.percentage, p)
622 self.assertIn(bar.ETA, e, p)
623 self.assertIn(bar.speed, s)
624 bar.stop()
625 p, e, s = expected[i + 1]
626 self.assertEqual(bar.percentage, p)
627 self.assertIn(bar.ETA, e, p)
628 self.assertIn(bar.speed, s)
629
630 # Of late, the speed tests keep failing on Windows
631 @unittest.skipIf(IN_GITHUB_WORKFLOW, 'Test disabled on some environments due to performance')
632 def test_unknown(self):
633 if os.name == 'nt':
634 speed = _speed_range(17, 20)
635 else:
636 speed = _speed_range(17, 19)
637 expected = (
638 (' ?? %', 'ETA : ??:??:??', speed),
639 (' ?? %', 'ETA : ??:??:??', speed),
640 (' ?? %', 'ETA : ??:??:??', speed),
641 (' ?? %', 'ETA : ??:??:??', speed),
642 (' ?? %', 'ETA : ??:??:??', speed),
643 (' ?? %', 'ETA : ??:??:??', speed),
644 (' ?? %', 'ETA : ??:??:??', speed),
645 (' ?? %', 'ETA : ??:??:??', speed),
646 (' ?? %', 'ETA : ??:??:??', speed),
647 ('100 %', 'Done: 00:00:04', speed),
648 )
649 bar = Progress(maxval=None).start()
650 for i, v in enumerate(range(10000, 100000, 10000)):
651 time.sleep(0.5)
652 bar.update(v)
653 p, e, s = expected[i]
654 self.assertEqual(bar.percentage, p)
655 self.assertEqual(bar.ETA, e)
656 self.assertIn(bar.speed, s)
657 bar.stop()
658 p, e, s = expected[i + 1]
659 self.assertEqual(bar.percentage, p)
660 self.assertEqual(bar.ETA, e)
661 self.assertIn(bar.speed, s)
662
663
664 class FileOpsTestCase(DistlibTestCase):
665
666 def setUp(self):
667 self.fileop = FileOperator()
668 self.workdir = tempfile.mkdtemp()
669
670 def tearDown(self):
671 if os.path.isdir(self.workdir):
672 shutil.rmtree(self.workdir)
673
674 def test_ensure_dir(self):
675 td = self.workdir
676 os.rmdir(td)
677 self.fileop.ensure_dir(td)
678 self.assertTrue(os.path.exists(td))
679 self.fileop.dry_run = True
680 os.rmdir(td)
681 self.fileop.ensure_dir(td)
682 self.assertFalse(os.path.exists(td))
683
684 def test_ensure_removed(self):
685 td = self.workdir
686 self.assertTrue(os.path.exists(td))
687 self.fileop.dry_run = True
688 self.fileop.ensure_removed(td)
689 self.assertTrue(os.path.exists(td))
690 self.fileop.dry_run = False
691 self.fileop.ensure_removed(td)
692 self.assertFalse(os.path.exists(td))
693
694 def test_is_writable(self):
695 sd = 'subdir'
696 ssd = 'subsubdir'
697 path = os.path.join(self.workdir, sd, ssd)
698 os.makedirs(path)
699 path = os.path.join(path, 'test')
700 self.assertTrue(self.fileop.is_writable(path))
701 if os.name == 'posix':
702 self.assertFalse(self.fileop.is_writable('/etc'))
703
704 def test_byte_compile(self):
705 path = os.path.join(self.workdir, 'hello.py')
706 if sys.version_info[:2] >= (3, 15):
707 dpath = cache_from_source(path, optimization='')
708 else:
709 dpath = cache_from_source(path, True)
710 self.fileop.write_text_file(path, 'print("Hello, world!")', 'utf-8')
711 self.fileop.byte_compile(path, optimize=False)
712 self.assertTrue(os.path.exists(dpath))
713
714 def write_some_files(self):
715 path = os.path.join(self.workdir, 'file1')
716 written = []
717 self.fileop.write_text_file(path, 'test', 'utf-8')
718 written.append(path)
719 path = os.path.join(self.workdir, 'file2')
720 self.fileop.copy_file(written[0], path)
721 written.append(path)
722 path = os.path.join(self.workdir, 'dir1')
723 self.fileop.ensure_dir(path)
724 return set(written), set([path])
725
726 def test_copy_check(self):
727 srcpath = os.path.join(self.workdir, 'file1')
728 self.fileop.write_text_file(srcpath, 'test', 'utf-8')
729 dstpath = os.path.join(self.workdir, 'file2')
730 os.mkdir(dstpath)
731 self.assertRaises(ValueError, self.fileop.copy_file, srcpath, dstpath)
732 os.rmdir(dstpath)
733 if os.name == 'posix': # symlinks available
734 linkpath = os.path.join(self.workdir, 'file3')
735 self.fileop.write_text_file(linkpath, 'linkdest', 'utf-8')
736 os.symlink(linkpath, dstpath)
737 self.assertRaises(ValueError, self.fileop.copy_file, srcpath, dstpath)
738
739 def test_commit(self):
740 # will assert if record isn't set
741 self.assertRaises(AssertionError, self.fileop.commit)
742 self.fileop.record = True
743 expected = self.write_some_files()
744 actual = self.fileop.commit()
745 self.assertEqual(actual, expected)
746 self.assertFalse(self.fileop.record)
747
748 def test_rollback(self):
749 # will assert if record isn't set
750 self.assertRaises(AssertionError, self.fileop.commit)
751 self.fileop.record = True
752 self.write_some_files()
753 self.fileop.rollback()
754 self.assertEqual(os.listdir(self.workdir), [])
755 self.assertFalse(self.fileop.record)
756
757
758 class GlobTestCaseBase(TempdirManager, DistlibTestCase):
759
760 def build_files_tree(self, files):
761 tempdir = self.mkdtemp()
762 for filepath in files:
763 is_dir = filepath.endswith('/')
764 filepath = os.path.join(tempdir, *filepath.split('/'))
765 if is_dir:
766 dirname = filepath
767 else:
768 dirname = os.path.dirname(filepath)
769 if dirname and not os.path.exists(dirname):
770 os.makedirs(dirname)
771 if not is_dir:
772 self.write_file(filepath, 'babar')
773 return tempdir
774
775 @staticmethod
776 def os_dependent_path(path):
777 path = path.rstrip('/').split('/')
778 return os.path.join(*path)
779
780 def clean_tree(self, spec):
781 files = []
782 for path, includes in spec.items():
783 if includes:
784 files.append(self.os_dependent_path(path))
785 return sorted(files)
786
787
788 class GlobTestCase(GlobTestCaseBase):
789
790 def assertGlobMatch(self, glob, spec):
791 tempdir = self.build_files_tree(spec)
792 expected = self.clean_tree(spec)
793 os.chdir(tempdir)
794 result = sorted(iglob(glob))
795 self.assertEqual(expected, result)
796
797 def test_regex_rich_glob(self):
798 matches = RICH_GLOB.findall(r"babar aime les {fraises} est les {huitres}")
799 self.assertEqual(["fraises", "huitres"], matches)
800
801 def test_simple_glob(self):
802 glob = '*.tp?'
803 spec = {'coucou.tpl': True, 'coucou.tpj': True, 'Donotwant': False}
804 self.assertGlobMatch(glob, spec)
805
806 def test_simple_glob_in_dir(self):
807 glob = os.path.join('babar', '*.tp?')
808 spec = {'babar/coucou.tpl': True, 'babar/coucou.tpj': True, 'babar/toto.bin': False, 'Donotwant': False}
809 self.assertGlobMatch(glob, spec)
810
811 def test_recursive_glob_head(self):
812 glob = os.path.join('**', 'tip', '*.t?l')
813 spec = {
814 'babar/zaza/zuzu/tip/coucou.tpl': True,
815 'babar/z/tip/coucou.tpl': True,
816 'babar/tip/coucou.tpl': True,
817 'babar/zeop/tip/babar/babar.tpl': False,
818 'babar/z/tip/coucou.bin': False,
819 'babar/toto.bin': False,
820 'zozo/zuzu/tip/babar.tpl': True,
821 'zozo/tip/babar.tpl': True,
822 'Donotwant': False
823 }
824 self.assertGlobMatch(glob, spec)
825
826 def test_recursive_glob_tail(self):
827 glob = os.path.join('babar', '**')
828 spec = {
829 'babar/zaza/': True,
830 'babar/zaza/zuzu/': True,
831 'babar/zaza/zuzu/babar.xml': True,
832 'babar/zaza/zuzu/toto.xml': True,
833 'babar/zaza/zuzu/toto.csv': True,
834 'babar/zaza/coucou.tpl': True,
835 'babar/bubu.tpl': True,
836 'zozo/zuzu/tip/babar.tpl': False,
837 'zozo/tip/babar.tpl': False,
838 'Donotwant': False
839 }
840 self.assertGlobMatch(glob, spec)
841
842 def test_recursive_glob_middle(self):
843 glob = os.path.join('babar', '**', 'tip', '*.t?l')
844 spec = {
845 'babar/zaza/zuzu/tip/coucou.tpl': True,
846 'babar/z/tip/coucou.tpl': True,
847 'babar/tip/coucou.tpl': True,
848 'babar/zeop/tip/babar/babar.tpl': False,
849 'babar/z/tip/coucou.bin': False,
850 'babar/toto.bin': False,
851 'zozo/zuzu/tip/babar.tpl': False,
852 'zozo/tip/babar.tpl': False,
853 'Donotwant': False
854 }
855 self.assertGlobMatch(glob, spec)
856
857 def test_glob_set_tail(self):
858 glob = os.path.join('bin', '*.{bin,sh,exe}')
859 spec = {
860 'bin/babar.bin': True,
861 'bin/zephir.sh': True,
862 'bin/celestine.exe': True,
863 'bin/cornelius.bat': False,
864 'bin/cornelius.xml': False,
865 'toto/yurg': False,
866 'Donotwant': False
867 }
868 self.assertGlobMatch(glob, spec)
869
870 def test_glob_set_middle(self):
871 glob = os.path.join('xml', '{babar,toto}.xml')
872 spec = {
873 'xml/babar.xml': True,
874 'xml/toto.xml': True,
875 'xml/babar.xslt': False,
876 'xml/cornelius.sgml': False,
877 'xml/zephir.xml': False,
878 'toto/yurg.xml': False,
879 'Donotwant': False
880 }
881 self.assertGlobMatch(glob, spec)
882
883 def test_glob_set_head(self):
884 glob = os.path.join('{xml,xslt}', 'babar.*')
885 spec = {
886 'xml/babar.xml': True,
887 'xml/toto.xml': False,
888 'xslt/babar.xslt': True,
889 'xslt/toto.xslt': False,
890 'toto/yurg.xml': False,
891 'Donotwant': False
892 }
893 self.assertGlobMatch(glob, spec)
894
895 def test_glob_all(self):
896 dirs = '{%s,%s}' % (os.path.join('xml', '*'), os.path.join('xslt', '**'))
897 glob = os.path.join(dirs, 'babar.xml')
898 spec = {
899 'xml/a/babar.xml': True,
900 'xml/b/babar.xml': True,
901 'xml/a/c/babar.xml': False,
902 'xslt/a/babar.xml': True,
903 'xslt/b/babar.xml': True,
904 'xslt/a/c/babar.xml': True,
905 'toto/yurg.xml': False,
906 'Donotwant': False
907 }
908 self.assertGlobMatch(glob, spec)
909
910 def test_invalid_glob_pattern(self):
911 invalids = [
912 'ppooa**',
913 'azzaeaz4**/',
914 '/**ddsfs',
915 '**##1e"&e',
916 'DSFb**c009',
917 '{',
918 '{aaQSDFa',
919 '}',
920 'aQSDFSaa}',
921 '{**a,',
922 ',**a}',
923 '{a**,',
924 ',b**}',
925 '{a**a,babar}',
926 '{bob,b**z}',
927 ]
928 for pattern in invalids:
929 self.assertRaises(ValueError, iglob, pattern)
930
931 def test_parse_requirement(self):
932 # Empty requirements
933 for empty in ('', '#this should be ignored'):
934 self.assertIsNone(parse_requirement(empty))
935
936 # Invalid requirements
937 for invalid in ('a (', 'a/', 'a$', 'a [', 'a () [],', 'a 1.2'):
938 self.assertRaises(SyntaxError, parse_requirement, invalid)
939
940 # Valid requirements
941 def validate(r, values):
942 self.assertEqual(r.name, values[0])
943 self.assertEqual(r.constraints, values[1])
944 self.assertEqual(r.extras, values[2])
945 self.assertEqual(r.requirement, values[3])
946 self.assertEqual(r.url, values[4])
947
948 r = parse_requirement('a')
949 validate(r, ('a', None, None, 'a', None))
950 r = parse_requirement('a >= 1.2, <2.0,!=1.7')
951 validate(r, ('a', [('>=', '1.2'), ('<', '2.0'), ('!=', '1.7')], None, 'a >= 1.2, < 2.0, != 1.7', None))
952 r = parse_requirement('a [ab,cd , ef] >= 1.2, <2.0')
953 validate(r, ('a', [('>=', '1.2'), ('<', '2.0')], ['ab', 'cd', 'ef'], 'a >= 1.2, < 2.0', None))
954 r = parse_requirement('a[]')
955 validate(r, ('a', None, None, 'a', None))
956 r = parse_requirement('a (== 1.2.*, != 1.2.1.*)')
957 validate(r, ('a', [('==', '1.2.*'), ('!=', '1.2.1.*')], None, 'a == 1.2.*, != 1.2.1.*', None))
958 r = parse_requirement('a @ http://domain.com/path#abc=def')
959 validate(r, ('a', None, None, 'a', 'http://domain.com/path#abc=def'))
960 # See issue #148
961 r = parse_requirement('a >=3.6')
962 validate(r, ('a', [('>=', '3.6')], None, 'a >= 3.6', None))
963 r = parse_requirement('a >=3.6,')
964 validate(r, ('a', [('>=', '3.6')], None, 'a >= 3.6', None))
965
966 if False: # TODO re-enable
967 for e in ('*', ':*:', ':meta:', '-', '-abc'):
968 r = parse_requirement('a [%s]' % e)
969 validate(r, ('a', None, [e], 'a', None))
970
971 def test_write_exports(self):
972 exports = {
973 'foo': {
974 'v1': ExportEntry('v1', 'p1', 's1', []),
975 'v2': ExportEntry('v2', 'p2', 's2', ['f2=a', 'g2']),
976 },
977 'bar': {
978 'v3': ExportEntry('v3', 'p3', 's3', ['f3', 'g3=h']),
979 'v4': ExportEntry('v4', 'p4', 's4', ['f4', 'g4']),
980 },
981 }
982
983 fd, fn = tempfile.mkstemp()
984 try:
985 os.close(fd)
986 with open(fn, 'wb') as f:
987 write_exports(exports, f)
988 with open(fn, 'rb') as f:
989 actual = read_exports(f)
990 self.assertEqual(actual, exports)
991 finally:
992 os.remove(fn)
993
994 def test_get_extras(self):
995 cases = (
996 (['*'], ['i18n'], set(['i18n'])),
997 (['*', '-bar'], ['foo', 'bar'], set(['foo'])),
998 )
999 for requested, available, expected in cases:
1000 actual = get_extras(requested, available)
1001 self.assertEqual(actual, expected)
1002
1003
1004 if __name__ == '__main__': # pragma: no cover
1005 unittest.main()