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.
 
 
 
 
 

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