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.
 
 
 
 
 

281 lines
9.0 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_directory(self):
  148. """ Test writing a directory. """
  149. z = ZipFile(self.f, 'w')
  150. z.writepath(None, pathname='/testdir', folder=True)
  151. z.writepath(None, pathname='/testdir/testinside', folder=True)
  152. z.close()
  153. self.f.close()
  154. f = open(ZIPPATH, mode='r')
  155. z = ZipFile(f, 'r')
  156. entries = z.infolist()
  157. assert len(entries) == 2
  158. assert entries[0].isdir()
  159. z.close()
  160. f.close()
  161. def test_writestream(self):
  162. z = ZipFile(self.f, 'w')
  163. for fname in FILENAMES:
  164. full_path = os.path.join(TMPDIR, fname)
  165. i = open(full_path)
  166. o = z.writestream(fname)
  167. while True:
  168. data = i.read(1)
  169. if not data:
  170. break
  171. if PY3:
  172. o.write(data)
  173. else:
  174. o.write(unicode(data))
  175. o.close()
  176. i.close()
  177. z.close()
  178. def test_writestream_unbuffered(self):
  179. z = ZipFile(self.f, 'w')
  180. for fname in FILENAMES:
  181. full_path = os.path.join(TMPDIR, fname)
  182. i = open(full_path)
  183. o = z.writestream(fname, os.path.getsize(full_path))
  184. while True:
  185. data = i.read(1)
  186. if not data:
  187. break
  188. if PY3:
  189. o.write(data)
  190. else:
  191. o.write(unicode(data))
  192. o.close()
  193. i.close()
  194. z.close()
  195. def test_deferred_close_by_archive(self):
  196. """ Test archive deferred close without a stream. """
  197. z = ZipFile(self.f, 'w')
  198. o = z.writestream(FILENAMES[0])
  199. z.close()
  200. self.assertIsNotNone(z._a)
  201. self.assertIsNotNone(z._stream)
  202. if PY3:
  203. o.write('testdata')
  204. else:
  205. o.write(unicode('testdata'))
  206. o.close()
  207. self.assertIsNone(z._a)
  208. self.assertIsNone(z._stream)
  209. z.close()
  210. class TestHighLevelAPI(unittest.TestCase):
  211. def setUp(self):
  212. make_temp_archive()
  213. def _test_listing_content(self, f):
  214. """ Test helper capturing file paths while iterating the archive. """
  215. found = []
  216. with Archive(f) as a:
  217. for entry in a:
  218. found.append(entry.pathname)
  219. self.assertEqual(set(found), set(FILENAMES))
  220. def test_open_by_name(self):
  221. """ Test an archive opened directly by name. """
  222. self._test_listing_content(ZIPPATH)
  223. def test_open_by_named_fobj(self):
  224. """ Test an archive using a file-like object opened by name. """
  225. with open(ZIPPATH, 'rb') as f:
  226. self._test_listing_content(f)
  227. def test_open_by_unnamed_fobj(self):
  228. """ Test an archive using file-like object opened by fileno(). """
  229. with open(ZIPPATH, 'rb') as zf:
  230. with io.FileIO(zf.fileno(), mode='r', closefd=False) as f:
  231. self._test_listing_content(f)
  232. if __name__ == '__main__':
  233. unittest.main()