Debian Codegraph @

Lib/test/test_zipapp.py

raw
1 """Test harness for the zipapp module."""
2
3 import io
4 import pathlib
5 import stat
6 import sys
7 import tempfile
8 import unittest
9 import zipapp
10 import zipfile
11 from test.support import requires_zlib
12 from test.support import os_helper
13
14 from unittest.mock import patch
15
16 class ZipAppTest(unittest.TestCase):
17
18 """Test zipapp module functionality."""
19
20 def setUp(self):
21 tmpdir = tempfile.TemporaryDirectory()
22 self.addCleanup(tmpdir.cleanup)
23 self.tmpdir = pathlib.Path(tmpdir.name)
24
25 def test_create_archive(self):
26 # Test packing a directory.
27 source = self.tmpdir / 'source'
28 source.mkdir()
29 (source / '__main__.py').touch()
30 target = self.tmpdir / 'source.pyz'
31 zipapp.create_archive(str(source), str(target))
32 self.assertTrue(target.is_file())
33
34 def test_create_archive_with_pathlib(self):
35 # Test packing a directory using Path objects for source and target.
36 source = self.tmpdir / 'source'
37 source.mkdir()
38 (source / '__main__.py').touch()
39 target = self.tmpdir / 'source.pyz'
40 zipapp.create_archive(source, target)
41 self.assertTrue(target.is_file())
42
43 def test_create_archive_with_subdirs(self):
44 # Test packing a directory includes entries for subdirectories.
45 source = self.tmpdir / 'source'
46 source.mkdir()
47 (source / '__main__.py').touch()
48 (source / 'foo').mkdir()
49 (source / 'bar').mkdir()
50 (source / 'foo' / '__init__.py').touch()
51 target = io.BytesIO()
52 zipapp.create_archive(str(source), target)
53 target.seek(0)
54 with zipfile.ZipFile(target, 'r') as z:
55 self.assertIn('foo/', z.namelist())
56 self.assertIn('bar/', z.namelist())
57
58 def test_create_sorted_archive(self):
59 # Test that zipapps order their files by name
60 source = self.tmpdir / 'source'
61 source.mkdir()
62 (source / 'zed.py').touch()
63 (source / 'bin').mkdir()
64 (source / 'bin' / 'qux').touch()
65 (source / 'bin' / 'baz').touch()
66 (source / '__main__.py').touch()
67 target = io.BytesIO()
68 zipapp.create_archive(str(source), target)
69 target.seek(0)
70 with zipfile.ZipFile(target, 'r') as zf:
71 self.assertEqual(zf.namelist(),
72 ["__main__.py", "bin/", "bin/baz", "bin/qux", "zed.py"])
73
74 def test_create_archive_with_filter(self):
75 # Test packing a directory and using filter to specify
76 # which files to include.
77 def skip_pyc_files(path):
78 return path.suffix != '.pyc'
79 source = self.tmpdir / 'source'
80 source.mkdir()
81 (source / '__main__.py').touch()
82 (source / 'test.py').touch()
83 (source / 'test.pyc').touch()
84 target = self.tmpdir / 'source.pyz'
85
86 zipapp.create_archive(source, target, filter=skip_pyc_files)
87 with zipfile.ZipFile(target, 'r') as z:
88 self.assertIn('__main__.py', z.namelist())
89 self.assertIn('test.py', z.namelist())
90 self.assertNotIn('test.pyc', z.namelist())
91
92 def test_create_archive_self_insertion(self):
93 # When creating an archive, we shouldn't
94 # include the archive in the list of files to add.
95 source = self.tmpdir
96 (source / '__main__.py').touch()
97 (source / 'test.py').touch()
98 target = self.tmpdir / 'target.pyz'
99
100 zipapp.create_archive(source, target)
101 with zipfile.ZipFile(target, 'r') as z:
102 self.assertEqual(len(z.namelist()), 2)
103 self.assertIn('__main__.py', z.namelist())
104 self.assertIn('test.py', z.namelist())
105
106 def test_target_overwrites_source_file(self):
107 # The target cannot be one of the files to add.
108 source = self.tmpdir
109 (source / '__main__.py').touch()
110 target = source / 'target.pyz'
111 target.touch()
112
113 with self.assertRaises(zipapp.ZipAppError):
114 zipapp.create_archive(source, target)
115
116 def test_create_archive_filter_exclude_dir(self):
117 # Test packing a directory and using a filter to exclude a
118 # subdirectory (ensures that the path supplied to include
119 # is relative to the source location, as expected).
120 def skip_dummy_dir(path):
121 return path.parts[0] != 'dummy'
122 source = self.tmpdir / 'source'
123 source.mkdir()
124 (source / '__main__.py').touch()
125 (source / 'test.py').touch()
126 (source / 'dummy').mkdir()
127 (source / 'dummy' / 'test2.py').touch()
128 target = self.tmpdir / 'source.pyz'
129
130 zipapp.create_archive(source, target, filter=skip_dummy_dir)
131 with zipfile.ZipFile(target, 'r') as z:
132 self.assertEqual(len(z.namelist()), 2)
133 self.assertIn('__main__.py', z.namelist())
134 self.assertIn('test.py', z.namelist())
135
136 def test_create_archive_default_target(self):
137 # Test packing a directory to the default name.
138 source = self.tmpdir / 'source'
139 source.mkdir()
140 (source / '__main__.py').touch()
141 zipapp.create_archive(str(source))
142 expected_target = self.tmpdir / 'source.pyz'
143 self.assertTrue(expected_target.is_file())
144
145 @requires_zlib()
146 def test_create_archive_with_compression(self):
147 # Test packing a directory into a compressed archive.
148 source = self.tmpdir / 'source'
149 source.mkdir()
150 (source / '__main__.py').touch()
151 (source / 'test.py').touch()
152 target = self.tmpdir / 'source.pyz'
153
154 zipapp.create_archive(source, target, compressed=True)
155 with zipfile.ZipFile(target, 'r') as z:
156 for name in ('__main__.py', 'test.py'):
157 self.assertEqual(z.getinfo(name).compress_type,
158 zipfile.ZIP_DEFLATED)
159
160 def test_no_main(self):
161 # Test that packing a directory with no __main__.py fails.
162 source = self.tmpdir / 'source'
163 source.mkdir()
164 (source / 'foo.py').touch()
165 target = self.tmpdir / 'source.pyz'
166 with self.assertRaises(zipapp.ZipAppError):
167 zipapp.create_archive(str(source), str(target))
168
169 def test_main_and_main_py(self):
170 # Test that supplying a main argument with __main__.py fails.
171 source = self.tmpdir / 'source'
172 source.mkdir()
173 (source / '__main__.py').touch()
174 target = self.tmpdir / 'source.pyz'
175 with self.assertRaises(zipapp.ZipAppError):
176 zipapp.create_archive(str(source), str(target), main='pkg.mod:fn')
177
178 def test_main_written(self):
179 # Test that the __main__.py is written correctly.
180 source = self.tmpdir / 'source'
181 source.mkdir()
182 (source / 'foo.py').touch()
183 target = self.tmpdir / 'source.pyz'
184 zipapp.create_archive(str(source), str(target), main='pkg.mod:fn')
185 with zipfile.ZipFile(str(target), 'r') as z:
186 self.assertIn('__main__.py', z.namelist())
187 self.assertIn(b'pkg.mod.fn()', z.read('__main__.py'))
188
189 def test_main_only_written_once(self):
190 # Test that we don't write multiple __main__.py files.
191 # The initial implementation had this bug; zip files allow
192 # multiple entries with the same name
193 source = self.tmpdir / 'source'
194 source.mkdir()
195 # Write 2 files, as the original bug wrote __main__.py
196 # once for each file written :-(
197 # See http://bugs.python.org/review/23491/diff/13982/Lib/zipapp.py#newcode67Lib/zipapp.py:67
198 # (line 67)
199 (source / 'foo.py').touch()
200 (source / 'bar.py').touch()
201 target = self.tmpdir / 'source.pyz'
202 zipapp.create_archive(str(source), str(target), main='pkg.mod:fn')
203 with zipfile.ZipFile(str(target), 'r') as z:
204 self.assertEqual(1, z.namelist().count('__main__.py'))
205
206 def test_main_validation(self):
207 # Test that invalid values for main are rejected.
208 source = self.tmpdir / 'source'
209 source.mkdir()
210 target = self.tmpdir / 'source.pyz'
211 problems = [
212 '', 'foo', 'foo:', ':bar', '12:bar', 'a.b.c.:d',
213 '.a:b', 'a:b.', 'a:.b', 'a:silly name'
214 ]
215 for main in problems:
216 with self.subTest(main=main):
217 with self.assertRaises(zipapp.ZipAppError):
218 zipapp.create_archive(str(source), str(target), main=main)
219
220 def test_default_no_shebang(self):
221 # Test that no shebang line is written to the target by default.
222 source = self.tmpdir / 'source'
223 source.mkdir()
224 (source / '__main__.py').touch()
225 target = self.tmpdir / 'source.pyz'
226 zipapp.create_archive(str(source), str(target))
227 with target.open('rb') as f:
228 self.assertNotEqual(f.read(2), b'#!')
229
230 def test_custom_interpreter(self):
231 # Test that a shebang line with a custom interpreter is written
232 # correctly.
233 source = self.tmpdir / 'source'
234 source.mkdir()
235 (source / '__main__.py').touch()
236 target = self.tmpdir / 'source.pyz'
237 zipapp.create_archive(str(source), str(target), interpreter='python')
238 with target.open('rb') as f:
239 self.assertEqual(f.read(2), b'#!')
240 self.assertEqual(b'python\n', f.readline())
241
242 def test_pack_to_fileobj(self):
243 # Test that we can pack to a file object.
244 source = self.tmpdir / 'source'
245 source.mkdir()
246 (source / '__main__.py').touch()
247 target = io.BytesIO()
248 zipapp.create_archive(str(source), target, interpreter='python')
249 self.assertTrue(target.getvalue().startswith(b'#!python\n'))
250
251 def test_read_shebang(self):
252 # Test that we can read the shebang line correctly.
253 source = self.tmpdir / 'source'
254 source.mkdir()
255 (source / '__main__.py').touch()
256 target = self.tmpdir / 'source.pyz'
257 zipapp.create_archive(str(source), str(target), interpreter='python')
258 self.assertEqual(zipapp.get_interpreter(str(target)), 'python')
259
260 def test_read_missing_shebang(self):
261 # Test that reading the shebang line of a file without one returns None.
262 source = self.tmpdir / 'source'
263 source.mkdir()
264 (source / '__main__.py').touch()
265 target = self.tmpdir / 'source.pyz'
266 zipapp.create_archive(str(source), str(target))
267 self.assertEqual(zipapp.get_interpreter(str(target)), None)
268
269 def test_modify_shebang(self):
270 # Test that we can change the shebang of a file.
271 source = self.tmpdir / 'source'
272 source.mkdir()
273 (source / '__main__.py').touch()
274 target = self.tmpdir / 'source.pyz'
275 zipapp.create_archive(str(source), str(target), interpreter='python')
276 new_target = self.tmpdir / 'changed.pyz'
277 zipapp.create_archive(str(target), str(new_target), interpreter='python2.7')
278 self.assertEqual(zipapp.get_interpreter(str(new_target)), 'python2.7')
279
280 def test_write_shebang_to_fileobj(self):
281 # Test that we can change the shebang of a file, writing the result to a
282 # file object.
283 source = self.tmpdir / 'source'
284 source.mkdir()
285 (source / '__main__.py').touch()
286 target = self.tmpdir / 'source.pyz'
287 zipapp.create_archive(str(source), str(target), interpreter='python')
288 new_target = io.BytesIO()
289 zipapp.create_archive(str(target), new_target, interpreter='python2.7')
290 self.assertTrue(new_target.getvalue().startswith(b'#!python2.7\n'))
291
292 def test_read_from_pathlike_obj(self):
293 # Test that we can copy an archive using a path-like object
294 # for the source.
295 source = self.tmpdir / 'source'
296 source.mkdir()
297 (source / '__main__.py').touch()
298 source = os_helper.FakePath(str(source))
299 target1 = os_helper.FakePath(str(self.tmpdir / 'target1.pyz'))
300 target2 = os_helper.FakePath(str(self.tmpdir / 'target2.pyz'))
301 zipapp.create_archive(source, target1, interpreter='python')
302 zipapp.create_archive(target1, target2, interpreter='python2.7')
303 self.assertEqual(zipapp.get_interpreter(target2), 'python2.7')
304
305 def test_read_from_fileobj(self):
306 # Test that we can copy an archive using an open file object.
307 source = self.tmpdir / 'source'
308 source.mkdir()
309 (source / '__main__.py').touch()
310 target = self.tmpdir / 'source.pyz'
311 temp_archive = io.BytesIO()
312 zipapp.create_archive(str(source), temp_archive, interpreter='python')
313 new_target = io.BytesIO()
314 temp_archive.seek(0)
315 zipapp.create_archive(temp_archive, new_target, interpreter='python2.7')
316 self.assertTrue(new_target.getvalue().startswith(b'#!python2.7\n'))
317
318 def test_remove_shebang(self):
319 # Test that we can remove the shebang from a file.
320 source = self.tmpdir / 'source'
321 source.mkdir()
322 (source / '__main__.py').touch()
323 target = self.tmpdir / 'source.pyz'
324 zipapp.create_archive(str(source), str(target), interpreter='python')
325 new_target = self.tmpdir / 'changed.pyz'
326 zipapp.create_archive(str(target), str(new_target), interpreter=None)
327 self.assertEqual(zipapp.get_interpreter(str(new_target)), None)
328
329 def test_content_of_copied_archive(self):
330 # Test that copying an archive doesn't corrupt it.
331 source = self.tmpdir / 'source'
332 source.mkdir()
333 (source / '__main__.py').touch()
334 target = io.BytesIO()
335 zipapp.create_archive(str(source), target, interpreter='python')
336 new_target = io.BytesIO()
337 target.seek(0)
338 zipapp.create_archive(target, new_target, interpreter=None)
339 new_target.seek(0)
340 with zipfile.ZipFile(new_target, 'r') as z:
341 self.assertEqual(set(z.namelist()), {'__main__.py'})
342
343 # (Unix only) tests that archives with shebang lines are made executable
344 @unittest.skipIf(sys.platform == 'win32',
345 'Windows does not support an executable bit')
346 @os_helper.skip_unless_working_chmod
347 def test_shebang_is_executable(self):
348 # Test that an archive with a shebang line is made executable.
349 source = self.tmpdir / 'source'
350 source.mkdir()
351 (source / '__main__.py').touch()
352 target = self.tmpdir / 'source.pyz'
353 zipapp.create_archive(str(source), str(target), interpreter='python')
354 self.assertTrue(target.stat().st_mode & stat.S_IEXEC)
355
356 @unittest.skipIf(sys.platform == 'win32',
357 'Windows does not support an executable bit')
358 def test_no_shebang_is_not_executable(self):
359 # Test that an archive with no shebang line is not made executable.
360 source = self.tmpdir / 'source'
361 source.mkdir()
362 (source / '__main__.py').touch()
363 target = self.tmpdir / 'source.pyz'
364 zipapp.create_archive(str(source), str(target), interpreter=None)
365 self.assertFalse(target.stat().st_mode & stat.S_IEXEC)
366
367
368 class ZipAppCmdlineTest(unittest.TestCase):
369
370 """Test zipapp module command line API."""
371
372 def setUp(self):
373 tmpdir = tempfile.TemporaryDirectory()
374 self.addCleanup(tmpdir.cleanup)
375 self.tmpdir = pathlib.Path(tmpdir.name)
376
377 def make_archive(self):
378 # Test that an archive with no shebang line is not made executable.
379 source = self.tmpdir / 'source'
380 source.mkdir()
381 (source / '__main__.py').touch()
382 target = self.tmpdir / 'source.pyz'
383 zipapp.create_archive(source, target)
384 return target
385
386 def test_cmdline_create(self):
387 # Test the basic command line API.
388 source = self.tmpdir / 'source'
389 source.mkdir()
390 (source / '__main__.py').touch()
391 args = [str(source)]
392 zipapp.main(args)
393 target = source.with_suffix('.pyz')
394 self.assertTrue(target.is_file())
395
396 def test_cmdline_copy(self):
397 # Test copying an archive.
398 original = self.make_archive()
399 target = self.tmpdir / 'target.pyz'
400 args = [str(original), '-o', str(target)]
401 zipapp.main(args)
402 self.assertTrue(target.is_file())
403
404 def test_cmdline_copy_inplace(self):
405 # Test copying an archive in place fails.
406 original = self.make_archive()
407 target = self.tmpdir / 'target.pyz'
408 args = [str(original), '-o', str(original)]
409 with self.assertRaises(SystemExit) as cm:
410 zipapp.main(args)
411 # Program should exit with a non-zero return code.
412 self.assertTrue(cm.exception.code)
413
414 def test_cmdline_copy_change_main(self):
415 # Test copying an archive doesn't allow changing __main__.py.
416 original = self.make_archive()
417 target = self.tmpdir / 'target.pyz'
418 args = [str(original), '-o', str(target), '-m', 'foo:bar']
419 with self.assertRaises(SystemExit) as cm:
420 zipapp.main(args)
421 # Program should exit with a non-zero return code.
422 self.assertTrue(cm.exception.code)
423
424 @patch('sys.stdout', new_callable=io.StringIO)
425 def test_info_command(self, mock_stdout):
426 # Test the output of the info command.
427 target = self.make_archive()
428 args = [str(target), '--info']
429 with self.assertRaises(SystemExit) as cm:
430 zipapp.main(args)
431 # Program should exit with a zero return code.
432 self.assertEqual(cm.exception.code, 0)
433 self.assertEqual(mock_stdout.getvalue(), "Interpreter: <none>\n")
434
435 def test_info_error(self):
436 # Test the info command fails when the archive does not exist.
437 target = self.tmpdir / 'dummy.pyz'
438 args = [str(target), '--info']
439 with self.assertRaises(SystemExit) as cm:
440 zipapp.main(args)
441 # Program should exit with a non-zero return code.
442 self.assertTrue(cm.exception.code)
443
444
445 if __name__ == "__main__":
446 unittest.main()