Debian Codegraph @

tests/test_scripts.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 __future__ import unicode_literals
8
9 import os
10 import shutil
11 import subprocess
12 import sys
13 import tempfile
14 import textwrap
15 try:
16 import venv
17 except ImportError:
18 venv = None
19
20 from compat import unittest
21 from support import DistlibTestCase
22
23 from distlib import DistlibException
24 from distlib.compat import fsencode, sysconfig
25 from distlib.scripts import ScriptMaker, enquote_executable
26 from distlib.util import get_executable
27
28 HERE = os.path.abspath(os.path.dirname(__file__))
29
30 COPIED_SCRIPT = '''#!python
31 # This is a copied script
32 '''
33
34 MADE_SCRIPT = 'made = dummy.module:main'
35
36
37 class ScriptTestCase(DistlibTestCase):
38
39 def setUp(self):
40 source_dir = os.path.join(HERE, 'scripts')
41 target_dir = tempfile.mkdtemp(prefix='distlib-test-')
42 self.maker = ScriptMaker(source_dir, target_dir, add_launchers=False)
43
44 def tearDown(self):
45 shutil.rmtree(self.maker.target_dir)
46
47 @unittest.skipIf(sysconfig.is_python_build(), 'Test not appropriate for '
48 'Python source builds')
49 def test_shebangs(self):
50 executable = fsencode(get_executable())
51 for fn in ('foo.py', 'script1.py', 'script2.py', 'script3.py', 'shell.sh'):
52 files = self.maker.make(fn)
53 self.assertEqual(len(files), 1)
54 d, f = os.path.split(files[0])
55 self.assertEqual(f, fn)
56 self.assertEqual(d, self.maker.target_dir)
57 if fn.endswith('.py') and fn != 'foo.py': # no shebang in foo.py
58 with open(files[0], 'rb') as f:
59 first_line = f.readline()
60 self.assertIn(executable, first_line)
61
62 def test_shebangs_custom_executable(self):
63 srcdir = tempfile.mkdtemp(prefix='distlib-test-')
64 self.addCleanup(shutil.rmtree, srcdir)
65 dstdir = tempfile.mkdtemp(prefix='distlib-test-')
66 self.addCleanup(shutil.rmtree, dstdir)
67 maker = ScriptMaker(srcdir, dstdir, add_launchers=False)
68 maker.executable = 'this_should_appear_in_the_shebang_line(中文)'
69 # let's create the script to be copied. It has a vanilla shebang line,
70 # with some Unicode in it.
71 fn = os.path.join(srcdir, 'copied')
72 with open(fn, 'w') as f:
73 f.write(COPIED_SCRIPT)
74 # Let's ask the maker to copy the script, and see what the shebang is
75 # in the copy.
76 filenames = maker.make('copied')
77 with open(filenames[0], 'rb') as f:
78 actual = f.readline().decode('utf-8')
79 self.assertIn(maker.executable, actual)
80 # Now let's make a script from a callable
81 filenames = maker.make(MADE_SCRIPT)
82 with open(filenames[0], 'rb') as f:
83 actual = f.readline().decode('utf-8')
84 self.assertIn(maker.executable, actual)
85
86 @unittest.skipIf(os.name != 'posix', 'Test only appropriate for '
87 'POSIX systems')
88 def test_custom_shebang(self):
89 # Construct an executable with a space in it
90 self.maker.executable = 'an executable with spaces'
91 filenames = self.maker.make('script1.py')
92 with open(filenames[0], 'rb') as f:
93 first_line = f.readline()
94 second_line = f.readline()
95 third_line = f.readline()
96 self.assertEqual(first_line, b'#!/bin/sh\n')
97 self.assertEqual(second_line, b"'''exec' an executable with "
98 b'spaces "$0" "$@"\n')
99 self.assertEqual(third_line, b"' '''\n")
100 # Python 3.3 cannot create a venv in an existing directory
101 if venv and sys.version_info[:2] >= (3, 4):
102 if sys.platform == 'darwin':
103 # Supposedly 512, but various symlinks mean that temp folder
104 # names get larger than you'd expect ... might vary on different
105 # OS versions, too
106 dlen = 220
107 else:
108 dlen = 127
109 dstdir = tempfile.mkdtemp(suffix='cataaaaaa' + 'a' * dlen)
110 self.addCleanup(shutil.rmtree, dstdir)
111 bindir = os.path.join(dstdir, 'bin')
112 maker = ScriptMaker(self.maker.source_dir, bindir, add_launchers=False)
113 # See issue #204. Changed to use symlinks on POSIX
114 venv.create(dstdir, symlinks=(os.name != 'nt'))
115 maker.executable = os.path.join(bindir, 'python')
116 filenames = maker.make('script8.py')
117 p = subprocess.Popen(filenames[0], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
118 stdout, stderr = p.communicate()
119 self.assertEqual(p.returncode, 0)
120 self.assertEqual(stderr, b'')
121 expected = os.path.realpath(maker.executable) # symlinks on OS X
122 actual = os.path.realpath(stdout.strip())
123 self.assertEqual(actual, expected.encode('utf-8'))
124
125 @unittest.skipIf(os.name != 'posix', 'Test only appropriate for '
126 'POSIX systems')
127 def test_cross_env_shebang(self):
128 # Construct an executable with a path that wouldn't ordinarily be a problem
129 self.maker.executable = '/path/to/python3'
130
131 # Set the cross-compiling marker attribute, then clean up.
132 try:
133 sys.cross_compiling = True
134 filenames = self.maker.make('script1.py')
135 finally:
136 delattr(sys, "cross_compiling")
137
138 with open(filenames[0], 'rb') as f:
139 first_line = f.readline()
140 second_line = f.readline()
141 third_line = f.readline()
142 self.assertEqual(first_line, b'#!/bin/sh\n')
143 self.assertEqual(second_line, b"'''exec' /path/to/python3 "
144 b'"$0" "$@"\n')
145 self.assertEqual(third_line, b"' '''\n")
146
147 def test_multiple(self):
148 specs = ('foo.py', 'script1.py', 'script2.py', 'script3.py', 'shell.sh', 'uwsgi_part')
149 files = self.maker.make_multiple(specs)
150 self.assertEqual(len(specs), len(files))
151 expected = set(specs)
152 self.assertEqual(expected, set([os.path.basename(f) for f in files]))
153 ofiles = os.listdir(self.maker.target_dir)
154 self.assertEqual(expected, set(ofiles))
155
156 def test_generation(self):
157 self.maker.clobber = True
158
159 def do_test(maker, version_info):
160 for name in ('main', 'other_main'):
161 for options in (None, {}, {'gui': False}, {'gui': True}):
162 gui = options and options.get('gui', False)
163 spec = 'foo = foo:' + name
164 files = maker.make(spec, options)
165 self.assertEqual(len(files), 2)
166 actual = set()
167 for f in files:
168 d, f = os.path.split(f)
169 actual.add(f)
170 if os.name == 'nt': # pragma: no cover
171 if gui:
172 ext = 'pyw'
173 else:
174 ext = 'py'
175 expected = set(['foo.%s' % ext, 'foo-%s.%s.%s' % (version_info[0], version_info[1], ext)])
176 else:
177 expected = set(['foo', 'foo-%s.%s' % (version_info[0], version_info[1])])
178 self.assertEqual(actual, expected)
179 self.assertEqual(d, maker.target_dir)
180 for fn in files:
181 with open(fn, 'r') as f:
182 text = f.read()
183 # self.assertIn("_resolve('foo', '%s')" % name, text)
184 if options and options['gui'] and os.name == 'nt': # pragma: no cover
185 first_line, rest = text.split('\n', 1)
186 self.assertIn('pythonw', first_line)
187
188 do_test(self.maker, sys.version_info)
189 # See issue 134. Test for specifying the target Python version
190 self.maker.version_info = version_info = (4, 4) # just any other Python version
191 do_test(self.maker, version_info)
192
193 def test_clobber(self):
194 files = self.maker.make('foo = foo:main')
195 saved_files = files
196 self.assertGreaterEqual(len(files), 2) # foo, foo-X.Y
197 files = self.maker.make('foo = foo:main')
198 self.assertFalse(files)
199 self.maker.clobber = True
200 files = self.maker.make('foo = foo:main')
201 self.assertEqual(files, saved_files)
202
203 @unittest.skipIf(os.name != 'nt', 'Test is Windows-specific')
204 def test_launchers(self): # pragma: no cover
205 tlauncher = self.maker._get_launcher('t')
206 self.maker.add_launchers = True
207 specs = ('foo.py', 'script1.py', 'script2.py', 'script3.py', 'shell.sh')
208 files = self.maker.make_multiple(specs)
209 self.assertEqual(len(specs), len(files))
210 filenames = set([os.path.basename(f) for f in files])
211 self.assertEqual(filenames, set(('foo.py', 'script1.exe', 'script2.exe', 'script3.exe', 'shell.sh')))
212 for fn in files:
213 if not fn.endswith('.exe'):
214 continue
215 with open(fn, 'rb') as f:
216 data = f.read()
217 self.assertTrue(data.startswith(tlauncher))
218
219 @unittest.skipIf(os.name != 'nt', 'Test is Windows-specific')
220 def test_launcher_run(self):
221 self.maker.add_launchers = True
222 files = self.maker.make('script6.py')
223 self.assertEqual(len(files), 1)
224 p = subprocess.Popen([files[0], 'Test Argument'],
225 stdout=subprocess.PIPE,
226 stdin=subprocess.PIPE,
227 stderr=subprocess.STDOUT)
228 stdout, stderr = p.communicate('input'.encode('ascii'))
229 actual = stdout.decode('ascii').replace('\r\n', '\n')
230 expected = textwrap.dedent("""
231 script6.exe
232 ['Test Argument']
233 'input'
234 non-optimized
235 """).lstrip()
236 self.assertEqual(actual, expected)
237
238 @unittest.skipIf(os.name != 'nt', 'Test is Windows-specific')
239 def test_launcher_run_with_interpreter_args(self):
240 srcdir = tempfile.mkdtemp(prefix='distlib-test-')
241 self.addCleanup(shutil.rmtree, srcdir)
242 dstdir = tempfile.mkdtemp(prefix='distlib-test-')
243 self.addCleanup(shutil.rmtree, dstdir)
244 maker = ScriptMaker(srcdir, dstdir, add_launchers=True)
245
246 # add '-O' option to shebang to run in optimized mode
247 with open(os.path.join(HERE, 'scripts', 'script6.py'), 'r') as src:
248 with open(os.path.join(srcdir, 'script6-optimized.py'), 'w') as dst:
249 shebang = src.readline().rstrip()
250 dst.write(shebang + " -O\n")
251 dst.write(src.read())
252
253 files = maker.make('script6-optimized.py')
254 self.assertEqual(len(files), 1)
255 p = subprocess.Popen([files[0], 'Test Argument'],
256 stdout=subprocess.PIPE,
257 stdin=subprocess.PIPE,
258 stderr=subprocess.STDOUT)
259 stdout, stderr = p.communicate('input'.encode('ascii'))
260 actual = stdout.decode('ascii').replace('\r\n', '\n')
261 expected = textwrap.dedent("""
262 script6-optimized.exe
263 ['Test Argument']
264 'input'
265 """).lstrip() # 'non-optimized' is not printed this time
266 self.assertEqual(actual, expected)
267
268 @unittest.skipIf(os.name != 'nt', 'Test is Windows-specific')
269 def test_windows(self): # pragma: no cover
270 wlauncher = self.maker._get_launcher('w')
271 tlauncher = self.maker._get_launcher('t')
272 self.maker.add_launchers = True
273 # executable = os.path.normcase(sys.executable).encode('utf-8')
274 executable = sys.executable.encode('utf-8')
275 if b'python3.' in executable:
276 wexecutable = executable.replace(b'python3.', b'pythonw3.')
277 else:
278 wexecutable = executable.replace(b'python.', b'pythonw.')
279 files = self.maker.make('script4.py')
280 self.assertEqual(len(files), 1)
281 filenames = set([os.path.basename(f) for f in files])
282 self.assertEqual(filenames, set(['script4.exe']))
283 for fn in files:
284 with open(fn, 'rb') as f:
285 data = f.read()
286 self.assertTrue(data.startswith(wlauncher))
287 self.assertIn(executable, data)
288 # Now test making scripts gui and console
289 files = self.maker.make('foo = foo:main', {'gui': True})
290 self.assertEqual(len(files), 2)
291 filenames = set([os.path.basename(f) for f in files])
292 specific = '%s.%s' % sys.version_info[:2]
293 self.assertEqual(filenames, set(('foo.exe', 'foo-%s.exe' % specific)))
294 for fn in files:
295 with open(fn, 'rb') as f:
296 data = f.read()
297 self.assertTrue(data.startswith(wlauncher))
298 self.assertIn(wexecutable, data)
299
300 files = self.maker.make('foo = foo:main')
301 self.assertEqual(len(files), 2)
302 filenames = set([os.path.basename(f) for f in files])
303 self.assertEqual(filenames, set(('foo.exe', 'foo-%s.exe' % specific)))
304 for fn in files:
305 with open(fn, 'rb') as f:
306 data = f.read()
307 self.assertTrue(data.startswith(tlauncher))
308 self.assertIn(executable, data)
309
310 @unittest.skipIf(os.name != 'nt', 'Test is Windows-specific')
311 def test_windows_run(self):
312 self.maker.add_launchers = True
313 files = self.maker.make('script7.pyw')
314 self.assertEqual(len(files), 1)
315
316 test_output = os.path.join(self.maker.target_dir, 'test_output.txt')
317 p = subprocess.Popen([files[0], test_output, 'Test Argument'],
318 stdout=subprocess.PIPE,
319 stdin=subprocess.PIPE,
320 stderr=subprocess.STDOUT)
321 stdout, stderr = p.communicate()
322 self.assertFalse(stdout)
323 self.assertFalse(stderr)
324 with open(test_output, 'rb') as f:
325 actual = f.read().decode('ascii')
326 self.assertEqual(actual, 'Test Argument')
327
328 def test_dry_run(self):
329 self.maker.dry_run = True
330 self.maker.variants = set([''])
331 specs = ('foo.py', 'bar = foo:main')
332 files = self.maker.make_multiple(specs)
333 self.assertEqual(len(specs), len(files))
334 if os.name == 'nt': # pragma: no cover
335 bar = 'bar.py'
336 else:
337 bar = 'bar'
338 self.assertEqual(set(('foo.py', bar)), set([os.path.basename(f) for f in files]))
339 ofiles = os.listdir(self.maker.target_dir)
340 self.assertFalse(ofiles)
341
342 def test_script_run(self):
343 if sys.version_info[:2] < (3, 13):
344 target = 'cgi:print_directory'
345 else:
346 target = 'logging:getHandlerNames'
347 files = self.maker.make('test = %s' % target)
348 self.assertEqual(len(files), 2)
349 p = subprocess.Popen([sys.executable, files[0]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
350 stdout, stderr = p.communicate()
351 if sys.version_info[:2] < (3, 13):
352 self.assertIn(b'<H3>Current Working Directory:</H3>', stdout)
353 self.assertIn(os.getcwd().encode('utf-8'), stdout)
354 else:
355 self.assertIn(b'frozenset(', stderr)
356 self.assertEqual(p.returncode, 1)
357
358 @unittest.skipUnless(os.name == 'posix', 'Test only valid for POSIX')
359 def test_mode(self):
360 # save test runner's original umask and ensure default 022
361 saved_umask = os.umask(0o022)
362 try:
363 self.maker.set_mode = False
364 files = self.maker.make('foo = foo:main')
365 self.assertEqual(len(files), 2)
366 for f in files:
367 self.assertIn(os.stat(f).st_mode & 0o7777, (0o644, 0o664))
368 self.maker.set_mode = True
369 files = self.maker.make('bar = bar:main')
370 self.assertEqual(len(files), 2)
371 for f in files:
372 self.assertIn(os.stat(f).st_mode & 0o7777, (0o755, 0o775))
373 finally:
374 # restore the test runner's original umask
375 os.umask(saved_umask)
376
377 def test_interpreter_args(self):
378 executable = fsencode(get_executable())
379 options = {'interpreter_args': ['-E', '"foo bar"', 'baz frobozz']}
380 self.maker.variants = set([''])
381 files = self.maker.make('foo = bar:baz', options=options)
382 self.assertEqual(len(files), 1)
383 with open(files[0], 'rb') as f:
384 shebang_line = f.readline()
385 if not sysconfig.is_python_build():
386 self.assertIn(executable, shebang_line)
387 self.assertIn(b' -E "foo bar" baz frobozz', shebang_line)
388
389 def test_args_on_copy(self):
390 self.maker.variants = set([''])
391 self.maker.executable = 'mypython'
392 files = self.maker.make('script5.py')
393 with open(files[0]) as f:
394 actual = f.readline().strip()
395 self.assertEqual(actual, '#!mypython -mzippy.activate')
396 if not sysconfig.is_python_build():
397 self.maker.executable = None
398 os.remove(files[0])
399 files = self.maker.make('script5.py')
400 with open(files[0]) as f:
401 actual = f.readline().strip()
402 expected = '#!%s -mzippy.activate' % get_executable()
403 self.assertEqual(actual, expected)
404
405 def test_enquote_executable(self):
406 for executable, expected in (('/no/spaces', '/no/spaces'), ('/i have/space', '"/i have/space"'),
407 ('"/space prequoted"', '"/space prequoted"'),
408 ('/usr/bin/env nospaces', '/usr/bin/env nospaces'), ('/usr/bin/env with spaces',
409 '/usr/bin/env "with spaces"'),
410 ('/usr/bin/env "pre spaced"', '/usr/bin/env "pre spaced"')):
411 self.assertEqual(enquote_executable(executable), expected)
412
413 def test_variant_configuration(self):
414 spec = 'foo = foo:main'
415 files = self.maker.make(spec)
416 if os.name == 'nt':
417 ext = '.py'
418 else:
419 ext = ''
420 basenames = ('foo%s' % ext, 'foo-%s.%s%s' % (self.maker.version_info[:2] + (ext, )))
421 expected = set([os.path.join(self.maker.target_dir, s) for s in basenames])
422 self.assertEqual(expected, set(files))
423 self.maker.variant_separator = ''
424 self.maker.clobber = True
425 files = self.maker.make(spec)
426 basenames = ('foo%s' % ext, 'foo%s.%s%s' % (self.maker.version_info[:2] + (ext, )))
427 expected = set([os.path.join(self.maker.target_dir, s) for s in basenames])
428 self.assertEqual(expected, set(files))
429
430 class CustomMaker(ScriptMaker):
431
432 def get_script_filenames(self, name):
433 result = super(CustomMaker, self).get_script_filenames(name)
434 if 'X.Y' in self.variants:
435 result.add('%s%s.%s' % ((name, ) + self.version_info[:2]))
436 return result
437
438 maker = CustomMaker(self.maker.source_dir, self.maker.target_dir, add_launchers=False)
439 maker.clobber = True
440 files = maker.make(spec)
441 basenames = ('foo%s' % ext, 'foo%s.%s%s' % (self.maker.version_info[:2] + (ext, )),
442 'foo-%s.%s%s' % (self.maker.version_info[:2] + (ext, )))
443 expected = set([os.path.join(self.maker.target_dir, s) for s in basenames])
444 self.assertEqual(expected, set(files))
445 if os.name == 'nt':
446 maker.add_launchers = True
447 files = maker.make(spec)
448 expected = set([e.replace('.py', '.exe') for e in expected])
449 self.assertEqual(expected, set(files))
450
451 def test_path_doesnt_escape_script_dir(self):
452 """
453 Check that a crafted entry point name doesn't escape the scripts directory.
454 """
455 # First, create a directory unconnected to any script being installed and put
456 # a known good script in it. Then make a script from an entry point crafted to overwrite it
457 # and see if it's caught.
458 known_good_dir = tempfile.mkdtemp(prefix='distlib-test-')
459 self.addCleanup(shutil.rmtree, known_good_dir)
460 fn = os.path.join(known_good_dir, 'known_good')
461 with open(fn, 'w') as f:
462 f.write('KNOWN GOOD')
463 self.maker.clobber = True
464 self.maker.variants = set(('',))
465 specs = (
466 os.path.join('..', os.path.basename(known_good_dir), 'known_good') + '=foo:bar',
467 os.path.join('..', '..', os.path.basename(known_good_dir), 'known_good') + '=foo:bar',
468 )
469 for spec in specs:
470 with self.assertRaises(DistlibException) as ctx:
471 self.maker.make(spec)
472 self.assertEqual(str(ctx.exception), 'Attempt to escape script directory')
473
474 if __name__ == '__main__': # pragma: no cover
475 unittest.main()