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.
 
 
 
 
 

280 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. TMPDIR = tempfile.mkdtemp(suffix='.python-libarchive')
  35. ZIPFILE = 'test.zip'
  36. ZIPPATH = os.path.join(TMPDIR, ZIPFILE)
  37. FILENAMES = [
  38. 'test1.txt',
  39. 'foo',
  40. # TODO: test non-ASCII chars.
  41. #'álért.txt',
  42. ]
  43. def make_temp_files():
  44. if not os.path.exists(ZIPPATH):
  45. for name in FILENAMES:
  46. with open(os.path.join(TMPDIR, name), 'w') as f:
  47. f.write(''.join(random.sample(string.ascii_letters, 10)))
  48. def make_temp_archive():
  49. make_temp_files()
  50. with zipfile.ZipFile(ZIPPATH, mode="w") as z:
  51. for name in FILENAMES:
  52. z.write(os.path.join(TMPDIR, name), arcname=name)
  53. class TestIsArchiveName(unittest.TestCase):
  54. def test_formats(self):
  55. self.assertEqual(is_archive_name('foo'), None)
  56. self.assertEqual(is_archive_name('foo.txt'), None)
  57. self.assertEqual(is_archive_name('foo.txt.gz'), None)
  58. self.assertEqual(is_archive_name('foo.tar.gz'), 'tar')
  59. self.assertEqual(is_archive_name('foo.tar.bz2'), 'tar')
  60. self.assertEqual(is_archive_name('foo.zip'), 'zip')
  61. self.assertEqual(is_archive_name('foo.rar'), 'rar')
  62. self.assertEqual(is_archive_name('foo.iso'), 'iso')
  63. self.assertEqual(is_archive_name('foo.rpm'), 'cpio')
  64. class TestIsArchiveZip(unittest.TestCase):
  65. def setUp(self):
  66. make_temp_archive()
  67. def test_zip(self):
  68. self.assertEqual(is_archive(ZIPPATH), True)
  69. self.assertEqual(is_archive(ZIPPATH, formats=('zip', )), True)
  70. self.assertEqual(is_archive(ZIPPATH, formats=('tar', )), False)
  71. class TestIsArchiveTar(unittest.TestCase):
  72. def test_tar(self):
  73. pass
  74. # TODO: incorporate tests from:
  75. # http://hg.python.org/cpython/file/a6e1d926cd98/Lib/test/test_zipfile.py
  76. class TestZipRead(unittest.TestCase):
  77. def setUp(self):
  78. make_temp_archive()
  79. self.f = open(ZIPPATH, mode='r')
  80. def tearDown(self):
  81. self.f.close()
  82. def test_iszipfile(self):
  83. self.assertEqual(is_zipfile('/dev/null'), False)
  84. self.assertEqual(is_zipfile(ZIPPATH), True)
  85. def test_iterate(self):
  86. z = ZipFile(self.f, 'r')
  87. count = 0
  88. for e in z:
  89. count += 1
  90. self.assertEqual(count, len(FILENAMES), 'Did not enumerate correct number of items in archive.')
  91. def test_deferred_close_by_archive(self):
  92. """ Test archive deferred close without a stream. """
  93. z = ZipFile(self.f, 'r')
  94. self.assertIsNotNone(z._a)
  95. self.assertIsNone(z._stream)
  96. z.close()
  97. self.assertIsNone(z._a)
  98. def test_deferred_close_by_stream(self):
  99. """ Ensure archive closes self if stream is closed first. """
  100. z = ZipFile(self.f, 'r')
  101. stream = z.readstream(FILENAMES[0])
  102. stream.close()
  103. # Make sure archive stays open after stream is closed.
  104. self.assertIsNotNone(z._a)
  105. self.assertIsNone(z._stream)
  106. z.close()
  107. self.assertIsNone(z._a)
  108. self.assertTrue(stream.closed)
  109. def test_close_stream_first(self):
  110. """ Ensure that archive stays open after being closed if a stream is
  111. open. Further, ensure closing the stream closes the archive. """
  112. z = ZipFile(self.f, 'r')
  113. stream = z.readstream(FILENAMES[0])
  114. z.close()
  115. try:
  116. stream.read()
  117. except:
  118. self.fail("Reading stream from closed archive failed!")
  119. stream.close()
  120. # Now the archive should close.
  121. self.assertIsNone(z._a)
  122. self.assertTrue(stream.closed)
  123. self.assertIsNone(z._stream)
  124. def test_filenames(self):
  125. z = ZipFile(self.f, 'r')
  126. names = []
  127. for e in z:
  128. names.append(e.filename)
  129. self.assertEqual(names, FILENAMES, 'File names differ in archive.')
  130. #~ def test_non_ascii(self):
  131. #~ pass
  132. def test_extract_str(self):
  133. pass
  134. class TestZipWrite(unittest.TestCase):
  135. def setUp(self):
  136. make_temp_files()
  137. self.f = open(ZIPPATH, mode='w')
  138. def tearDown(self):
  139. self.f.close()
  140. def test_writepath(self):
  141. z = ZipFile(self.f, 'w')
  142. for fname in FILENAMES:
  143. with open(os.path.join(TMPDIR, fname), 'r') as f:
  144. z.writepath(f)
  145. z.close()
  146. def test_writepath_directory(self):
  147. """ Test writing a directory. """
  148. z = ZipFile(self.f, 'w')
  149. z.writepath(None, pathname='/testdir', folder=True)
  150. z.writepath(None, pathname='/testdir/testinside', folder=True)
  151. z.close()
  152. self.f.close()
  153. f = open(ZIPPATH, mode='r')
  154. z = ZipFile(f, 'r')
  155. entries = z.infolist()
  156. assert len(entries) == 2
  157. assert entries[0].isdir()
  158. z.close()
  159. f.close()
  160. def test_writestream(self):
  161. z = ZipFile(self.f, 'w')
  162. for fname in FILENAMES:
  163. full_path = os.path.join(TMPDIR, fname)
  164. i = open(full_path)
  165. o = z.writestream(fname)
  166. while True:
  167. data = i.read(1)
  168. if not data:
  169. break
  170. if PY3:
  171. o.write(data)
  172. else:
  173. o.write(unicode(data))
  174. o.close()
  175. i.close()
  176. z.close()
  177. def test_writestream_unbuffered(self):
  178. z = ZipFile(self.f, 'w')
  179. for fname in FILENAMES:
  180. full_path = os.path.join(TMPDIR, fname)
  181. i = open(full_path)
  182. o = z.writestream(fname, os.path.getsize(full_path))
  183. while True:
  184. data = i.read(1)
  185. if not data:
  186. break
  187. if PY3:
  188. o.write(data)
  189. else:
  190. o.write(unicode(data))
  191. o.close()
  192. i.close()
  193. z.close()
  194. def test_deferred_close_by_archive(self):
  195. """ Test archive deferred close without a stream. """
  196. z = ZipFile(self.f, 'w')
  197. o = z.writestream(FILENAMES[0])
  198. z.close()
  199. self.assertIsNotNone(z._a)
  200. self.assertIsNotNone(z._stream)
  201. if PY3:
  202. o.write('testdata')
  203. else:
  204. o.write(unicode('testdata'))
  205. o.close()
  206. self.assertIsNone(z._a)
  207. self.assertIsNone(z._stream)
  208. z.close()
  209. class TestHighLevelAPI(unittest.TestCase):
  210. def setUp(self):
  211. make_temp_archive()
  212. def _test_listing_content(self, f):
  213. """ Test helper capturing file paths while iterating the archive. """
  214. found = []
  215. with Archive(f) as a:
  216. for entry in a:
  217. found.append(entry.pathname)
  218. self.assertEqual(set(found), set(FILENAMES))
  219. def test_open_by_name(self):
  220. """ Test an archive opened directly by name. """
  221. self._test_listing_content(ZIPPATH)
  222. def test_open_by_named_fobj(self):
  223. """ Test an archive using a file-like object opened by name. """
  224. with open(ZIPPATH, 'rb') as f:
  225. self._test_listing_content(f)
  226. def test_open_by_unnamed_fobj(self):
  227. """ Test an archive using file-like object opened by fileno(). """
  228. with open(ZIPPATH, 'rb') as zf:
  229. with io.FileIO(zf.fileno(), mode='r', closefd=False) as f:
  230. self._test_listing_content(f)
  231. if __name__ == '__main__':
  232. unittest.main()