PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/distutils/tests/test_archive_util.py

https://gitlab.com/unofficial-mirrors/cpython
Python | 395 lines | 309 code | 55 blank | 31 comment | 49 complexity | e5d64adc2a68492a807416ef261a33f6 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """Tests for distutils.archive_util."""
  3. import unittest
  4. import os
  5. import sys
  6. import tarfile
  7. from os.path import splitdrive
  8. import warnings
  9. from distutils import archive_util
  10. from distutils.archive_util import (check_archive_formats, make_tarball,
  11. make_zipfile, make_archive,
  12. ARCHIVE_FORMATS)
  13. from distutils.spawn import find_executable, spawn
  14. from distutils.tests import support
  15. from test.support import check_warnings, run_unittest, patch, change_cwd
  16. try:
  17. import grp
  18. import pwd
  19. UID_GID_SUPPORT = True
  20. except ImportError:
  21. UID_GID_SUPPORT = False
  22. try:
  23. import zipfile
  24. ZIP_SUPPORT = True
  25. except ImportError:
  26. ZIP_SUPPORT = find_executable('zip')
  27. try:
  28. import zlib
  29. ZLIB_SUPPORT = True
  30. except ImportError:
  31. ZLIB_SUPPORT = False
  32. try:
  33. import bz2
  34. except ImportError:
  35. bz2 = None
  36. try:
  37. import lzma
  38. except ImportError:
  39. lzma = None
  40. def can_fs_encode(filename):
  41. """
  42. Return True if the filename can be saved in the file system.
  43. """
  44. if os.path.supports_unicode_filenames:
  45. return True
  46. try:
  47. filename.encode(sys.getfilesystemencoding())
  48. except UnicodeEncodeError:
  49. return False
  50. return True
  51. class ArchiveUtilTestCase(support.TempdirManager,
  52. support.LoggingSilencer,
  53. unittest.TestCase):
  54. @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
  55. def test_make_tarball(self, name='archive'):
  56. # creating something to tar
  57. tmpdir = self._create_files()
  58. self._make_tarball(tmpdir, name, '.tar.gz')
  59. # trying an uncompressed one
  60. self._make_tarball(tmpdir, name, '.tar', compress=None)
  61. @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
  62. def test_make_tarball_gzip(self):
  63. tmpdir = self._create_files()
  64. self._make_tarball(tmpdir, 'archive', '.tar.gz', compress='gzip')
  65. @unittest.skipUnless(bz2, 'Need bz2 support to run')
  66. def test_make_tarball_bzip2(self):
  67. tmpdir = self._create_files()
  68. self._make_tarball(tmpdir, 'archive', '.tar.bz2', compress='bzip2')
  69. @unittest.skipUnless(lzma, 'Need lzma support to run')
  70. def test_make_tarball_xz(self):
  71. tmpdir = self._create_files()
  72. self._make_tarball(tmpdir, 'archive', '.tar.xz', compress='xz')
  73. @unittest.skipUnless(can_fs_encode('årchiv'),
  74. 'File system cannot handle this filename')
  75. def test_make_tarball_latin1(self):
  76. """
  77. Mirror test_make_tarball, except filename contains latin characters.
  78. """
  79. self.test_make_tarball('årchiv') # note this isn't a real word
  80. @unittest.skipUnless(can_fs_encode('のアーカイブ'),
  81. 'File system cannot handle this filename')
  82. def test_make_tarball_extended(self):
  83. """
  84. Mirror test_make_tarball, except filename contains extended
  85. characters outside the latin charset.
  86. """
  87. self.test_make_tarball('のアーカイブ') # japanese for archive
  88. def _make_tarball(self, tmpdir, target_name, suffix, **kwargs):
  89. tmpdir2 = self.mkdtemp()
  90. unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
  91. "source and target should be on same drive")
  92. base_name = os.path.join(tmpdir2, target_name)
  93. # working with relative paths to avoid tar warnings
  94. with change_cwd(tmpdir):
  95. make_tarball(splitdrive(base_name)[1], 'dist', **kwargs)
  96. # check if the compressed tarball was created
  97. tarball = base_name + suffix
  98. self.assertTrue(os.path.exists(tarball))
  99. self.assertEqual(self._tarinfo(tarball), self._created_files)
  100. def _tarinfo(self, path):
  101. tar = tarfile.open(path)
  102. try:
  103. names = tar.getnames()
  104. names.sort()
  105. return tuple(names)
  106. finally:
  107. tar.close()
  108. _created_files = ('dist', 'dist/file1', 'dist/file2',
  109. 'dist/sub', 'dist/sub/file3', 'dist/sub2')
  110. def _create_files(self):
  111. # creating something to tar
  112. tmpdir = self.mkdtemp()
  113. dist = os.path.join(tmpdir, 'dist')
  114. os.mkdir(dist)
  115. self.write_file([dist, 'file1'], 'xxx')
  116. self.write_file([dist, 'file2'], 'xxx')
  117. os.mkdir(os.path.join(dist, 'sub'))
  118. self.write_file([dist, 'sub', 'file3'], 'xxx')
  119. os.mkdir(os.path.join(dist, 'sub2'))
  120. return tmpdir
  121. @unittest.skipUnless(find_executable('tar') and find_executable('gzip')
  122. and ZLIB_SUPPORT,
  123. 'Need the tar, gzip and zlib command to run')
  124. def test_tarfile_vs_tar(self):
  125. tmpdir = self._create_files()
  126. tmpdir2 = self.mkdtemp()
  127. base_name = os.path.join(tmpdir2, 'archive')
  128. old_dir = os.getcwd()
  129. os.chdir(tmpdir)
  130. try:
  131. make_tarball(base_name, 'dist')
  132. finally:
  133. os.chdir(old_dir)
  134. # check if the compressed tarball was created
  135. tarball = base_name + '.tar.gz'
  136. self.assertTrue(os.path.exists(tarball))
  137. # now create another tarball using `tar`
  138. tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
  139. tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
  140. gzip_cmd = ['gzip', '-f9', 'archive2.tar']
  141. old_dir = os.getcwd()
  142. os.chdir(tmpdir)
  143. try:
  144. spawn(tar_cmd)
  145. spawn(gzip_cmd)
  146. finally:
  147. os.chdir(old_dir)
  148. self.assertTrue(os.path.exists(tarball2))
  149. # let's compare both tarballs
  150. self.assertEqual(self._tarinfo(tarball), self._created_files)
  151. self.assertEqual(self._tarinfo(tarball2), self._created_files)
  152. # trying an uncompressed one
  153. base_name = os.path.join(tmpdir2, 'archive')
  154. old_dir = os.getcwd()
  155. os.chdir(tmpdir)
  156. try:
  157. make_tarball(base_name, 'dist', compress=None)
  158. finally:
  159. os.chdir(old_dir)
  160. tarball = base_name + '.tar'
  161. self.assertTrue(os.path.exists(tarball))
  162. # now for a dry_run
  163. base_name = os.path.join(tmpdir2, 'archive')
  164. old_dir = os.getcwd()
  165. os.chdir(tmpdir)
  166. try:
  167. make_tarball(base_name, 'dist', compress=None, dry_run=True)
  168. finally:
  169. os.chdir(old_dir)
  170. tarball = base_name + '.tar'
  171. self.assertTrue(os.path.exists(tarball))
  172. @unittest.skipUnless(find_executable('compress'),
  173. 'The compress program is required')
  174. def test_compress_deprecated(self):
  175. tmpdir = self._create_files()
  176. base_name = os.path.join(self.mkdtemp(), 'archive')
  177. # using compress and testing the PendingDeprecationWarning
  178. old_dir = os.getcwd()
  179. os.chdir(tmpdir)
  180. try:
  181. with check_warnings() as w:
  182. warnings.simplefilter("always")
  183. make_tarball(base_name, 'dist', compress='compress')
  184. finally:
  185. os.chdir(old_dir)
  186. tarball = base_name + '.tar.Z'
  187. self.assertTrue(os.path.exists(tarball))
  188. self.assertEqual(len(w.warnings), 1)
  189. # same test with dry_run
  190. os.remove(tarball)
  191. old_dir = os.getcwd()
  192. os.chdir(tmpdir)
  193. try:
  194. with check_warnings() as w:
  195. warnings.simplefilter("always")
  196. make_tarball(base_name, 'dist', compress='compress',
  197. dry_run=True)
  198. finally:
  199. os.chdir(old_dir)
  200. self.assertFalse(os.path.exists(tarball))
  201. self.assertEqual(len(w.warnings), 1)
  202. @unittest.skipUnless(ZIP_SUPPORT and ZLIB_SUPPORT,
  203. 'Need zip and zlib support to run')
  204. def test_make_zipfile(self):
  205. # creating something to tar
  206. tmpdir = self._create_files()
  207. base_name = os.path.join(self.mkdtemp(), 'archive')
  208. with change_cwd(tmpdir):
  209. make_zipfile(base_name, 'dist')
  210. # check if the compressed tarball was created
  211. tarball = base_name + '.zip'
  212. self.assertTrue(os.path.exists(tarball))
  213. with zipfile.ZipFile(tarball) as zf:
  214. self.assertEqual(sorted(zf.namelist()),
  215. ['dist/file1', 'dist/file2', 'dist/sub/file3'])
  216. @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
  217. def test_make_zipfile_no_zlib(self):
  218. patch(self, archive_util.zipfile, 'zlib', None) # force zlib ImportError
  219. called = []
  220. zipfile_class = zipfile.ZipFile
  221. def fake_zipfile(*a, **kw):
  222. if kw.get('compression', None) == zipfile.ZIP_STORED:
  223. called.append((a, kw))
  224. return zipfile_class(*a, **kw)
  225. patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile)
  226. # create something to tar and compress
  227. tmpdir = self._create_files()
  228. base_name = os.path.join(self.mkdtemp(), 'archive')
  229. with change_cwd(tmpdir):
  230. make_zipfile(base_name, 'dist')
  231. tarball = base_name + '.zip'
  232. self.assertEqual(called,
  233. [((tarball, "w"), {'compression': zipfile.ZIP_STORED})])
  234. self.assertTrue(os.path.exists(tarball))
  235. with zipfile.ZipFile(tarball) as zf:
  236. self.assertEqual(sorted(zf.namelist()),
  237. ['dist/file1', 'dist/file2', 'dist/sub/file3'])
  238. def test_check_archive_formats(self):
  239. self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']),
  240. 'xxx')
  241. self.assertIsNone(check_archive_formats(['gztar', 'bztar', 'xztar',
  242. 'ztar', 'tar', 'zip']))
  243. def test_make_archive(self):
  244. tmpdir = self.mkdtemp()
  245. base_name = os.path.join(tmpdir, 'archive')
  246. self.assertRaises(ValueError, make_archive, base_name, 'xxx')
  247. def test_make_archive_cwd(self):
  248. current_dir = os.getcwd()
  249. def _breaks(*args, **kw):
  250. raise RuntimeError()
  251. ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file')
  252. try:
  253. try:
  254. make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
  255. except:
  256. pass
  257. self.assertEqual(os.getcwd(), current_dir)
  258. finally:
  259. del ARCHIVE_FORMATS['xxx']
  260. def test_make_archive_tar(self):
  261. base_dir = self._create_files()
  262. base_name = os.path.join(self.mkdtemp() , 'archive')
  263. res = make_archive(base_name, 'tar', base_dir, 'dist')
  264. self.assertTrue(os.path.exists(res))
  265. self.assertEqual(os.path.basename(res), 'archive.tar')
  266. self.assertEqual(self._tarinfo(res), self._created_files)
  267. @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run')
  268. def test_make_archive_gztar(self):
  269. base_dir = self._create_files()
  270. base_name = os.path.join(self.mkdtemp() , 'archive')
  271. res = make_archive(base_name, 'gztar', base_dir, 'dist')
  272. self.assertTrue(os.path.exists(res))
  273. self.assertEqual(os.path.basename(res), 'archive.tar.gz')
  274. self.assertEqual(self._tarinfo(res), self._created_files)
  275. @unittest.skipUnless(bz2, 'Need bz2 support to run')
  276. def test_make_archive_bztar(self):
  277. base_dir = self._create_files()
  278. base_name = os.path.join(self.mkdtemp() , 'archive')
  279. res = make_archive(base_name, 'bztar', base_dir, 'dist')
  280. self.assertTrue(os.path.exists(res))
  281. self.assertEqual(os.path.basename(res), 'archive.tar.bz2')
  282. self.assertEqual(self._tarinfo(res), self._created_files)
  283. @unittest.skipUnless(lzma, 'Need xz support to run')
  284. def test_make_archive_xztar(self):
  285. base_dir = self._create_files()
  286. base_name = os.path.join(self.mkdtemp() , 'archive')
  287. res = make_archive(base_name, 'xztar', base_dir, 'dist')
  288. self.assertTrue(os.path.exists(res))
  289. self.assertEqual(os.path.basename(res), 'archive.tar.xz')
  290. self.assertEqual(self._tarinfo(res), self._created_files)
  291. def test_make_archive_owner_group(self):
  292. # testing make_archive with owner and group, with various combinations
  293. # this works even if there's not gid/uid support
  294. if UID_GID_SUPPORT:
  295. group = grp.getgrgid(0)[0]
  296. owner = pwd.getpwuid(0)[0]
  297. else:
  298. group = owner = 'root'
  299. base_dir = self._create_files()
  300. root_dir = self.mkdtemp()
  301. base_name = os.path.join(self.mkdtemp() , 'archive')
  302. res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
  303. group=group)
  304. self.assertTrue(os.path.exists(res))
  305. res = make_archive(base_name, 'zip', root_dir, base_dir)
  306. self.assertTrue(os.path.exists(res))
  307. res = make_archive(base_name, 'tar', root_dir, base_dir,
  308. owner=owner, group=group)
  309. self.assertTrue(os.path.exists(res))
  310. res = make_archive(base_name, 'tar', root_dir, base_dir,
  311. owner='kjhkjhkjg', group='oihohoh')
  312. self.assertTrue(os.path.exists(res))
  313. @unittest.skipUnless(ZLIB_SUPPORT, "Requires zlib")
  314. @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
  315. def test_tarfile_root_owner(self):
  316. tmpdir = self._create_files()
  317. base_name = os.path.join(self.mkdtemp(), 'archive')
  318. old_dir = os.getcwd()
  319. os.chdir(tmpdir)
  320. group = grp.getgrgid(0)[0]
  321. owner = pwd.getpwuid(0)[0]
  322. try:
  323. archive_name = make_tarball(base_name, 'dist', compress=None,
  324. owner=owner, group=group)
  325. finally:
  326. os.chdir(old_dir)
  327. # check if the compressed tarball was created
  328. self.assertTrue(os.path.exists(archive_name))
  329. # now checks the rights
  330. archive = tarfile.open(archive_name)
  331. try:
  332. for member in archive.getmembers():
  333. self.assertEqual(member.uid, 0)
  334. self.assertEqual(member.gid, 0)
  335. finally:
  336. archive.close()
  337. def test_suite():
  338. return unittest.makeSuite(ArchiveUtilTestCase)
  339. if __name__ == "__main__":
  340. run_unittest(test_suite())