You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

288 lines
9.2 KiB

  1. #!/usr/bin/env python
  2. # coding=utf-8
  3. #
  4. # Copyright (c) 2011, SmartFile <btimby@smartfile.com>
  5. # All rights reserved.
  6. #
  7. # Redistribution and use in source and binary forms, with or without
  8. # modification, are permitted provided that the following conditions are met:
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. # * Neither the name of the organization nor the
  15. # names of its contributors may be used to endorse or promote products
  16. # derived from this software without specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
  22. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. import os, unittest, tempfile, random, string, sys
  29. import zipfile
  30. import io
  31. from libarchive import Archive, is_archive_name, is_archive
  32. from libarchive.zip import is_zipfile, ZipFile, ZipEntry
  33. #PY3 = sys.version_info[0] == 3
  34. PY3 = True
  35. TMPDIR = tempfile.mkdtemp(suffix='.python-libarchive')
  36. ZIPFILE = 'test.zip'
  37. ZIPPATH = os.path.join(TMPDIR, ZIPFILE)
  38. FILENAMES = [
  39. 'test1.txt',
  40. 'foo',
  41. # TODO: test non-ASCII chars.
  42. #'álért.txt',
  43. ]
  44. def make_temp_files():
  45. if not os.path.exists(ZIPPATH):
  46. for name in FILENAMES:
  47. with open(os.path.join(TMPDIR, name), 'w') as f:
  48. f.write(''.join(random.sample(string.ascii_letters, 10)))
  49. def make_temp_archive():
  50. make_temp_files()
  51. with zipfile.ZipFile(ZIPPATH, mode="w") as z:
  52. for name in FILENAMES:
  53. z.write(os.path.join(TMPDIR, name), arcname=name)
  54. class TestIsArchiveName(unittest.TestCase):
  55. def test_formats(self):
  56. self.assertEqual(is_archive_name('foo'), None)
  57. self.assertEqual(is_archive_name('foo.txt'), None)
  58. self.assertEqual(is_archive_name('foo.txt.gz'), None)
  59. self.assertEqual(is_archive_name('foo.tar.gz'), 'tar')
  60. self.assertEqual(is_archive_name('foo.tar.bz2'), 'tar')
  61. self.assertEqual(is_archive_name('foo.zip'), 'zip')
  62. self.assertEqual(is_archive_name('foo.rar'), 'rar')
  63. self.assertEqual(is_archive_name('foo.iso'), 'iso')
  64. self.assertEqual(is_archive_name('foo.rpm'), 'cpio')
  65. class TestIsArchiveZip(unittest.TestCase):
  66. def setUp(self):
  67. make_temp_archive()
  68. def test_zip(self):
  69. self.assertEqual(is_archive(ZIPPATH), True)
  70. self.assertEqual(is_archive(ZIPPATH, formats=('zip', )), True)
  71. self.assertEqual(is_archive(ZIPPATH, formats=('tar', )), False)
  72. class TestIsArchiveTar(unittest.TestCase):
  73. def test_tar(self):
  74. pass
  75. # TODO: incorporate tests from:
  76. # http://hg.python.org/cpython/file/a6e1d926cd98/Lib/test/test_zipfile.py
  77. class TestZipRead(unittest.TestCase):
  78. def setUp(self):
  79. make_temp_archive()
  80. self.f = open(ZIPPATH, mode='r')
  81. def tearDown(self):
  82. self.f.close()
  83. def test_iszipfile(self):
  84. self.assertEqual(is_zipfile('/dev/null'), False)
  85. self.assertEqual(is_zipfile(ZIPPATH), True)
  86. def test_iterate(self):
  87. z = ZipFile(self.f, 'r')
  88. count = 0
  89. for e in z:
  90. count += 1
  91. self.assertEqual(count, len(FILENAMES), 'Did not enumerate correct number of items in archive.')
  92. def test_deferred_close_by_archive(self):
  93. """ Test archive deferred close without a stream. """
  94. z = ZipFile(self.f, 'r')
  95. self.assertIsNotNone(z._a)
  96. self.assertIsNone(z._stream)
  97. z.close()
  98. self.assertIsNone(z._a)
  99. def test_deferred_close_by_stream(self):
  100. """ Ensure archive closes self if stream is closed first. """
  101. z = ZipFile(self.f, 'r')
  102. stream = z.readstream(FILENAMES[0])
  103. stream.close()
  104. # Make sure archive stays open after stream is closed.
  105. self.assertIsNotNone(z._a)
  106. self.assertIsNone(z._stream)
  107. z.close()
  108. self.assertIsNone(z._a)
  109. self.assertTrue(stream.closed)
  110. def test_close_stream_first(self):
  111. """ Ensure that archive stays open after being closed if a stream is
  112. open. Further, ensure closing the stream closes the archive. """
  113. z = ZipFile(self.f, 'r')
  114. stream = z.readstream(FILENAMES[0])
  115. z.close()
  116. try:
  117. stream.read()
  118. except:
  119. self.fail("Reading stream from closed archive failed!")
  120. stream.close()
  121. # Now the archive should close.
  122. self.assertIsNone(z._a)
  123. self.assertTrue(stream.closed)
  124. self.assertIsNone(z._stream)
  125. def test_filenames(self):
  126. z = ZipFile(self.f, 'r')
  127. names = []
  128. for e in z:
  129. names.append(e.filename)
  130. self.assertEqual(names, FILENAMES, 'File names differ in archive.')
  131. #~ def test_non_ascii(self):
  132. #~ pass
  133. def test_extract_str(self):
  134. pass
  135. class TestZipWrite(unittest.TestCase):
  136. def setUp(self):
  137. make_temp_files()
  138. self.f = open(ZIPPATH, mode='w')
  139. def tearDown(self):
  140. self.f.close()
  141. def test_writepath(self):
  142. z = ZipFile(self.f, 'w')
  143. for fname in FILENAMES:
  144. with open(os.path.join(TMPDIR, fname), 'r') as f:
  145. z.writepath(f)
  146. z.close()
  147. def test_writepath_with_password(self):
  148. z = ZipFile(self.f, 'w', password='test')
  149. for fname in FILENAMES:
  150. with open(os.path.join(TMPDIR, fname), 'r') as f:
  151. z.writepath(f)
  152. z.close()
  153. def test_writepath_directory(self):
  154. """ Test writing a directory. """
  155. z = ZipFile(self.f, 'w')
  156. z.writepath(None, pathname='/testdir', folder=True)
  157. z.writepath(None, pathname='/testdir/testinside', folder=True)
  158. z.close()
  159. self.f.close()
  160. f = open(ZIPPATH, mode='r')
  161. z = ZipFile(f, 'r')
  162. entries = z.infolist()
  163. assert len(entries) == 2
  164. assert entries[0].isdir()
  165. z.close()
  166. f.close()
  167. def test_writestream(self):
  168. z = ZipFile(self.f, 'w')
  169. for fname in FILENAMES:
  170. full_path = os.path.join(TMPDIR, fname)
  171. i = open(full_path)
  172. o = z.writestream(fname)
  173. while True:
  174. data = i.read(1)
  175. if not data:
  176. break
  177. if PY3:
  178. o.write(data)
  179. else:
  180. o.write(unicode(data))
  181. o.close()
  182. i.close()
  183. z.close()
  184. def test_writestream_unbuffered(self):
  185. z = ZipFile(self.f, 'w')
  186. for fname in FILENAMES:
  187. full_path = os.path.join(TMPDIR, fname)
  188. i = open(full_path)
  189. o = z.writestream(fname, os.path.getsize(full_path))
  190. while True:
  191. data = i.read(1)
  192. if not data:
  193. break
  194. if PY3:
  195. o.write(data)
  196. else:
  197. o.write(unicode(data))
  198. o.close()
  199. i.close()
  200. z.close()
  201. def test_deferred_close_by_archive(self):
  202. """ Test archive deferred close without a stream. """
  203. z = ZipFile(self.f, 'w')
  204. o = z.writestream(FILENAMES[0])
  205. z.close()
  206. self.assertIsNotNone(z._a)
  207. self.assertIsNotNone(z._stream)
  208. if PY3:
  209. o.write('testdata')
  210. else:
  211. o.write(unicode('testdata'))
  212. o.close()
  213. self.assertIsNone(z._a)
  214. self.assertIsNone(z._stream)
  215. z.close()
  216. class TestHighLevelAPI(unittest.TestCase):
  217. def setUp(self):
  218. make_temp_archive()
  219. def _test_listing_content(self, f):
  220. """ Test helper capturing file paths while iterating the archive. """
  221. found = []
  222. with Archive(f) as a:
  223. for entry in a:
  224. found.append(entry.pathname)
  225. self.assertEqual(set(found), set(FILENAMES))
  226. def test_open_by_name(self):
  227. """ Test an archive opened directly by name. """
  228. self._test_listing_content(ZIPPATH)
  229. def test_open_by_named_fobj(self):
  230. """ Test an archive using a file-like object opened by name. """
  231. with open(ZIPPATH, 'rb') as f:
  232. self._test_listing_content(f)
  233. def test_open_by_unnamed_fobj(self):
  234. """ Test an archive using file-like object opened by fileno(). """
  235. with open(ZIPPATH, 'rb') as zf:
  236. with io.FileIO(zf.fileno(), mode='r', closefd=False) as f:
  237. self._test_listing_content(f)
  238. if __name__ == '__main__':
  239. unittest.main()