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.
 
 
 
 
 

242 lines
7.8 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
  29. from libarchive import is_archive_name, is_archive
  30. from libarchive.zip import is_zipfile, ZipFile, ZipEntry
  31. TMPDIR = tempfile.mkdtemp()
  32. ZIPCMD = '/usr/bin/zip'
  33. ZIPFILE = 'test.zip'
  34. ZIPPATH = os.path.join(TMPDIR, ZIPFILE)
  35. FILENAMES = [
  36. 'test1.txt',
  37. 'foo',
  38. # TODO: test non-ASCII chars.
  39. #'álért.txt',
  40. ]
  41. def make_temp_files():
  42. if not os.path.exists(ZIPPATH):
  43. for name in FILENAMES:
  44. file(os.path.join(TMPDIR, name), 'w').write(''.join(random.sample(string.printable, 10)))
  45. def make_temp_archive():
  46. if not os.access(ZIPCMD, os.X_OK):
  47. raise AssertionError('Cannot execute %s.' % ZIPCMD)
  48. cmd = [ZIPCMD, ZIPFILE]
  49. make_temp_files()
  50. cmd.extend(FILENAMES)
  51. os.chdir(TMPDIR)
  52. subprocess.call(cmd, stdout=subprocess.PIPE)
  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. def test_iszipfile(self):
  80. self.assertEqual(is_zipfile('/dev/null'), False)
  81. self.assertEqual(is_zipfile(ZIPPATH), True)
  82. def test_iterate(self):
  83. f = file(ZIPPATH, mode='r')
  84. z = ZipFile(f, 'r')
  85. count = 0
  86. for e in z:
  87. count += 1
  88. self.assertEqual(count, len(FILENAMES), 'Did not enumerate correct number of items in archive.')
  89. def test_deferred_close_by_archive(self):
  90. """ Test archive deferred close without a stream. """
  91. f = file(ZIPPATH, mode='r')
  92. z = ZipFile(f, 'r')
  93. self.assertIsNotNone(z._a)
  94. self.assertIsNone(z._stream)
  95. z.close()
  96. self.assertIsNone(z._a)
  97. def test_deferred_close_by_stream(self):
  98. """ Ensure archive closes self if stream is closed first. """
  99. f = file(ZIPPATH, mode='r')
  100. z = ZipFile(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. f = file(ZIPPATH, mode='r')
  113. z = ZipFile(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. f = file(ZIPPATH, mode='r')
  127. z = ZipFile(f, 'r')
  128. names = []
  129. for e in z:
  130. names.append(e.filename)
  131. self.assertEqual(names, FILENAMES, 'File names differ in archive.')
  132. #~ def test_non_ascii(self):
  133. #~ pass
  134. def test_extract_str(self):
  135. pass
  136. class TestZipWrite(unittest.TestCase):
  137. def setUp(self):
  138. make_temp_files()
  139. def test_writepath(self):
  140. f = file(ZIPPATH, mode='w')
  141. z = ZipFile(f, 'w')
  142. for fname in FILENAMES:
  143. z.writepath(file(os.path.join(TMPDIR, fname), 'r'))
  144. z.close()
  145. def test_writepath_directory(self):
  146. """ Test writing a directory. """
  147. f = file(ZIPPATH, mode='w')
  148. z = ZipFile(f, 'w')
  149. z.writepath(None, pathname='/testdir', folder=True)
  150. z.writepath(None, pathname='/testdir/testinside', folder=True)
  151. z.close()
  152. f.close()
  153. f = file(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. f = file(ZIPPATH, mode='w')
  162. z = ZipFile(f, 'w')
  163. for fname in FILENAMES:
  164. full_path = os.path.join(TMPDIR, fname)
  165. i = file(full_path)
  166. o = z.writestream(fname)
  167. while True:
  168. data = i.read(1)
  169. if not data:
  170. break
  171. o.write(data)
  172. o.close()
  173. i.close()
  174. z.close()
  175. def test_writestream_unbuffered(self):
  176. f = file(ZIPPATH, mode='w')
  177. z = ZipFile(f, 'w')
  178. for fname in FILENAMES:
  179. full_path = os.path.join(TMPDIR, fname)
  180. i = file(full_path)
  181. o = z.writestream(fname, os.path.getsize(full_path))
  182. while True:
  183. data = i.read(1)
  184. if not data:
  185. break
  186. o.write(data)
  187. o.close()
  188. i.close()
  189. z.close()
  190. def test_deferred_close_by_archive(self):
  191. """ Test archive deferred close without a stream. """
  192. f = file(ZIPPATH, mode='w')
  193. z = ZipFile(f, 'w')
  194. o = z.writestream(FILENAMES[0])
  195. z.close()
  196. self.assertIsNotNone(z._a)
  197. self.assertIsNotNone(z._stream)
  198. o.write('testdata')
  199. o.close()
  200. self.assertIsNone(z._a)
  201. self.assertIsNone(z._stream)
  202. z.close()
  203. if __name__ == '__main__':
  204. unittest.main()