test_gzip.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. """Test script for the gzip module.
  2. """
  3. import array
  4. import functools
  5. import io
  6. import os
  7. import pathlib
  8. import struct
  9. import sys
  10. import unittest
  11. from subprocess import PIPE, Popen
  12. from test.support import import_helper
  13. from test.support import os_helper
  14. from test.support import _4G, bigmemtest, requires_subprocess
  15. from test.support.script_helper import assert_python_ok, assert_python_failure
  16. gzip = import_helper.import_module('gzip')
  17. data1 = b""" int length=DEFAULTALLOC, err = Z_OK;
  18. PyObject *RetVal;
  19. int flushmode = Z_FINISH;
  20. unsigned long start_total_out;
  21. """
  22. data2 = b"""/* zlibmodule.c -- gzip-compatible data compression */
  23. /* See http://www.gzip.org/zlib/
  24. /* See http://www.winimage.com/zLibDll for Windows */
  25. """
  26. TEMPDIR = os.path.abspath(os_helper.TESTFN) + '-gzdir'
  27. class UnseekableIO(io.BytesIO):
  28. def seekable(self):
  29. return False
  30. def tell(self):
  31. raise io.UnsupportedOperation
  32. def seek(self, *args):
  33. raise io.UnsupportedOperation
  34. class BaseTest(unittest.TestCase):
  35. filename = os_helper.TESTFN
  36. def setUp(self):
  37. os_helper.unlink(self.filename)
  38. def tearDown(self):
  39. os_helper.unlink(self.filename)
  40. class TestGzip(BaseTest):
  41. def write_and_read_back(self, data, mode='b'):
  42. b_data = bytes(data)
  43. with gzip.GzipFile(self.filename, 'w'+mode) as f:
  44. l = f.write(data)
  45. self.assertEqual(l, len(b_data))
  46. with gzip.GzipFile(self.filename, 'r'+mode) as f:
  47. self.assertEqual(f.read(), b_data)
  48. def test_write(self):
  49. with gzip.GzipFile(self.filename, 'wb') as f:
  50. f.write(data1 * 50)
  51. # Try flush and fileno.
  52. f.flush()
  53. f.fileno()
  54. if hasattr(os, 'fsync'):
  55. os.fsync(f.fileno())
  56. f.close()
  57. # Test multiple close() calls.
  58. f.close()
  59. def test_write_read_with_pathlike_file(self):
  60. filename = pathlib.Path(self.filename)
  61. with gzip.GzipFile(filename, 'w') as f:
  62. f.write(data1 * 50)
  63. self.assertIsInstance(f.name, str)
  64. with gzip.GzipFile(filename, 'a') as f:
  65. f.write(data1)
  66. with gzip.GzipFile(filename) as f:
  67. d = f.read()
  68. self.assertEqual(d, data1 * 51)
  69. self.assertIsInstance(f.name, str)
  70. # The following test_write_xy methods test that write accepts
  71. # the corresponding bytes-like object type as input
  72. # and that the data written equals bytes(xy) in all cases.
  73. def test_write_memoryview(self):
  74. self.write_and_read_back(memoryview(data1 * 50))
  75. m = memoryview(bytes(range(256)))
  76. data = m.cast('B', shape=[8,8,4])
  77. self.write_and_read_back(data)
  78. def test_write_bytearray(self):
  79. self.write_and_read_back(bytearray(data1 * 50))
  80. def test_write_array(self):
  81. self.write_and_read_back(array.array('I', data1 * 40))
  82. def test_write_incompatible_type(self):
  83. # Test that non-bytes-like types raise TypeError.
  84. # Issue #21560: attempts to write incompatible types
  85. # should not affect the state of the fileobject
  86. with gzip.GzipFile(self.filename, 'wb') as f:
  87. with self.assertRaises(TypeError):
  88. f.write('')
  89. with self.assertRaises(TypeError):
  90. f.write([])
  91. f.write(data1)
  92. with gzip.GzipFile(self.filename, 'rb') as f:
  93. self.assertEqual(f.read(), data1)
  94. def test_read(self):
  95. self.test_write()
  96. # Try reading.
  97. with gzip.GzipFile(self.filename, 'r') as f:
  98. d = f.read()
  99. self.assertEqual(d, data1*50)
  100. def test_read1(self):
  101. self.test_write()
  102. blocks = []
  103. nread = 0
  104. with gzip.GzipFile(self.filename, 'r') as f:
  105. while True:
  106. d = f.read1()
  107. if not d:
  108. break
  109. blocks.append(d)
  110. nread += len(d)
  111. # Check that position was updated correctly (see issue10791).
  112. self.assertEqual(f.tell(), nread)
  113. self.assertEqual(b''.join(blocks), data1 * 50)
  114. @bigmemtest(size=_4G, memuse=1)
  115. def test_read_large(self, size):
  116. # Read chunk size over UINT_MAX should be supported, despite zlib's
  117. # limitation per low-level call
  118. compressed = gzip.compress(data1, compresslevel=1)
  119. f = gzip.GzipFile(fileobj=io.BytesIO(compressed), mode='rb')
  120. self.assertEqual(f.read(size), data1)
  121. def test_io_on_closed_object(self):
  122. # Test that I/O operations on closed GzipFile objects raise a
  123. # ValueError, just like the corresponding functions on file objects.
  124. # Write to a file, open it for reading, then close it.
  125. self.test_write()
  126. f = gzip.GzipFile(self.filename, 'r')
  127. fileobj = f.fileobj
  128. self.assertFalse(fileobj.closed)
  129. f.close()
  130. self.assertTrue(fileobj.closed)
  131. with self.assertRaises(ValueError):
  132. f.read(1)
  133. with self.assertRaises(ValueError):
  134. f.seek(0)
  135. with self.assertRaises(ValueError):
  136. f.tell()
  137. # Open the file for writing, then close it.
  138. f = gzip.GzipFile(self.filename, 'w')
  139. fileobj = f.fileobj
  140. self.assertFalse(fileobj.closed)
  141. f.close()
  142. self.assertTrue(fileobj.closed)
  143. with self.assertRaises(ValueError):
  144. f.write(b'')
  145. with self.assertRaises(ValueError):
  146. f.flush()
  147. def test_append(self):
  148. self.test_write()
  149. # Append to the previous file
  150. with gzip.GzipFile(self.filename, 'ab') as f:
  151. f.write(data2 * 15)
  152. with gzip.GzipFile(self.filename, 'rb') as f:
  153. d = f.read()
  154. self.assertEqual(d, (data1*50) + (data2*15))
  155. def test_many_append(self):
  156. # Bug #1074261 was triggered when reading a file that contained
  157. # many, many members. Create such a file and verify that reading it
  158. # works.
  159. with gzip.GzipFile(self.filename, 'wb', 9) as f:
  160. f.write(b'a')
  161. for i in range(0, 200):
  162. with gzip.GzipFile(self.filename, "ab", 9) as f: # append
  163. f.write(b'a')
  164. # Try reading the file
  165. with gzip.GzipFile(self.filename, "rb") as zgfile:
  166. contents = b""
  167. while 1:
  168. ztxt = zgfile.read(8192)
  169. contents += ztxt
  170. if not ztxt: break
  171. self.assertEqual(contents, b'a'*201)
  172. def test_exclusive_write(self):
  173. with gzip.GzipFile(self.filename, 'xb') as f:
  174. f.write(data1 * 50)
  175. with gzip.GzipFile(self.filename, 'rb') as f:
  176. self.assertEqual(f.read(), data1 * 50)
  177. with self.assertRaises(FileExistsError):
  178. gzip.GzipFile(self.filename, 'xb')
  179. def test_buffered_reader(self):
  180. # Issue #7471: a GzipFile can be wrapped in a BufferedReader for
  181. # performance.
  182. self.test_write()
  183. with gzip.GzipFile(self.filename, 'rb') as f:
  184. with io.BufferedReader(f) as r:
  185. lines = [line for line in r]
  186. self.assertEqual(lines, 50 * data1.splitlines(keepends=True))
  187. def test_readline(self):
  188. self.test_write()
  189. # Try .readline() with varying line lengths
  190. with gzip.GzipFile(self.filename, 'rb') as f:
  191. line_length = 0
  192. while 1:
  193. L = f.readline(line_length)
  194. if not L and line_length != 0: break
  195. self.assertTrue(len(L) <= line_length)
  196. line_length = (line_length + 1) % 50
  197. def test_readlines(self):
  198. self.test_write()
  199. # Try .readlines()
  200. with gzip.GzipFile(self.filename, 'rb') as f:
  201. L = f.readlines()
  202. with gzip.GzipFile(self.filename, 'rb') as f:
  203. while 1:
  204. L = f.readlines(150)
  205. if L == []: break
  206. def test_seek_read(self):
  207. self.test_write()
  208. # Try seek, read test
  209. with gzip.GzipFile(self.filename) as f:
  210. while 1:
  211. oldpos = f.tell()
  212. line1 = f.readline()
  213. if not line1: break
  214. newpos = f.tell()
  215. f.seek(oldpos) # negative seek
  216. if len(line1)>10:
  217. amount = 10
  218. else:
  219. amount = len(line1)
  220. line2 = f.read(amount)
  221. self.assertEqual(line1[:amount], line2)
  222. f.seek(newpos) # positive seek
  223. def test_seek_whence(self):
  224. self.test_write()
  225. # Try seek(whence=1), read test
  226. with gzip.GzipFile(self.filename) as f:
  227. f.read(10)
  228. f.seek(10, whence=1)
  229. y = f.read(10)
  230. self.assertEqual(y, data1[20:30])
  231. def test_seek_write(self):
  232. # Try seek, write test
  233. with gzip.GzipFile(self.filename, 'w') as f:
  234. for pos in range(0, 256, 16):
  235. f.seek(pos)
  236. f.write(b'GZ\n')
  237. def test_mode(self):
  238. self.test_write()
  239. with gzip.GzipFile(self.filename, 'r') as f:
  240. self.assertEqual(f.myfileobj.mode, 'rb')
  241. os_helper.unlink(self.filename)
  242. with gzip.GzipFile(self.filename, 'x') as f:
  243. self.assertEqual(f.myfileobj.mode, 'xb')
  244. def test_1647484(self):
  245. for mode in ('wb', 'rb'):
  246. with gzip.GzipFile(self.filename, mode) as f:
  247. self.assertTrue(hasattr(f, "name"))
  248. self.assertEqual(f.name, self.filename)
  249. def test_paddedfile_getattr(self):
  250. self.test_write()
  251. with gzip.GzipFile(self.filename, 'rb') as f:
  252. self.assertTrue(hasattr(f.fileobj, "name"))
  253. self.assertEqual(f.fileobj.name, self.filename)
  254. def test_mtime(self):
  255. mtime = 123456789
  256. with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
  257. fWrite.write(data1)
  258. with gzip.GzipFile(self.filename) as fRead:
  259. self.assertTrue(hasattr(fRead, 'mtime'))
  260. self.assertIsNone(fRead.mtime)
  261. dataRead = fRead.read()
  262. self.assertEqual(dataRead, data1)
  263. self.assertEqual(fRead.mtime, mtime)
  264. def test_metadata(self):
  265. mtime = 123456789
  266. with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
  267. fWrite.write(data1)
  268. with open(self.filename, 'rb') as fRead:
  269. # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
  270. idBytes = fRead.read(2)
  271. self.assertEqual(idBytes, b'\x1f\x8b') # gzip ID
  272. cmByte = fRead.read(1)
  273. self.assertEqual(cmByte, b'\x08') # deflate
  274. try:
  275. expectedname = self.filename.encode('Latin-1') + b'\x00'
  276. expectedflags = b'\x08' # only the FNAME flag is set
  277. except UnicodeEncodeError:
  278. expectedname = b''
  279. expectedflags = b'\x00'
  280. flagsByte = fRead.read(1)
  281. self.assertEqual(flagsByte, expectedflags)
  282. mtimeBytes = fRead.read(4)
  283. self.assertEqual(mtimeBytes, struct.pack('<i', mtime)) # little-endian
  284. xflByte = fRead.read(1)
  285. self.assertEqual(xflByte, b'\x02') # maximum compression
  286. osByte = fRead.read(1)
  287. self.assertEqual(osByte, b'\xff') # OS "unknown" (OS-independent)
  288. # Since the FNAME flag is set, the zero-terminated filename follows.
  289. # RFC 1952 specifies that this is the name of the input file, if any.
  290. # However, the gzip module defaults to storing the name of the output
  291. # file in this field.
  292. nameBytes = fRead.read(len(expectedname))
  293. self.assertEqual(nameBytes, expectedname)
  294. # Since no other flags were set, the header ends here.
  295. # Rather than process the compressed data, let's seek to the trailer.
  296. fRead.seek(os.stat(self.filename).st_size - 8)
  297. crc32Bytes = fRead.read(4) # CRC32 of uncompressed data [data1]
  298. self.assertEqual(crc32Bytes, b'\xaf\xd7d\x83')
  299. isizeBytes = fRead.read(4)
  300. self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
  301. def test_metadata_ascii_name(self):
  302. self.filename = os_helper.TESTFN_ASCII
  303. self.test_metadata()
  304. def test_compresslevel_metadata(self):
  305. # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
  306. # specifically, discussion of XFL in section 2.3.1
  307. cases = [
  308. ('fast', 1, b'\x04'),
  309. ('best', 9, b'\x02'),
  310. ('tradeoff', 6, b'\x00'),
  311. ]
  312. xflOffset = 8
  313. for (name, level, expectedXflByte) in cases:
  314. with self.subTest(name):
  315. fWrite = gzip.GzipFile(self.filename, 'w', compresslevel=level)
  316. with fWrite:
  317. fWrite.write(data1)
  318. with open(self.filename, 'rb') as fRead:
  319. fRead.seek(xflOffset)
  320. xflByte = fRead.read(1)
  321. self.assertEqual(xflByte, expectedXflByte)
  322. def test_with_open(self):
  323. # GzipFile supports the context management protocol
  324. with gzip.GzipFile(self.filename, "wb") as f:
  325. f.write(b"xxx")
  326. f = gzip.GzipFile(self.filename, "rb")
  327. f.close()
  328. try:
  329. with f:
  330. pass
  331. except ValueError:
  332. pass
  333. else:
  334. self.fail("__enter__ on a closed file didn't raise an exception")
  335. try:
  336. with gzip.GzipFile(self.filename, "wb") as f:
  337. 1/0
  338. except ZeroDivisionError:
  339. pass
  340. else:
  341. self.fail("1/0 didn't raise an exception")
  342. def test_zero_padded_file(self):
  343. with gzip.GzipFile(self.filename, "wb") as f:
  344. f.write(data1 * 50)
  345. # Pad the file with zeroes
  346. with open(self.filename, "ab") as f:
  347. f.write(b"\x00" * 50)
  348. with gzip.GzipFile(self.filename, "rb") as f:
  349. d = f.read()
  350. self.assertEqual(d, data1 * 50, "Incorrect data in file")
  351. def test_gzip_BadGzipFile_exception(self):
  352. self.assertTrue(issubclass(gzip.BadGzipFile, OSError))
  353. def test_bad_gzip_file(self):
  354. with open(self.filename, 'wb') as file:
  355. file.write(data1 * 50)
  356. with gzip.GzipFile(self.filename, 'r') as file:
  357. self.assertRaises(gzip.BadGzipFile, file.readlines)
  358. def test_non_seekable_file(self):
  359. uncompressed = data1 * 50
  360. buf = UnseekableIO()
  361. with gzip.GzipFile(fileobj=buf, mode="wb") as f:
  362. f.write(uncompressed)
  363. compressed = buf.getvalue()
  364. buf = UnseekableIO(compressed)
  365. with gzip.GzipFile(fileobj=buf, mode="rb") as f:
  366. self.assertEqual(f.read(), uncompressed)
  367. def test_peek(self):
  368. uncompressed = data1 * 200
  369. with gzip.GzipFile(self.filename, "wb") as f:
  370. f.write(uncompressed)
  371. def sizes():
  372. while True:
  373. for n in range(5, 50, 10):
  374. yield n
  375. with gzip.GzipFile(self.filename, "rb") as f:
  376. f.max_read_chunk = 33
  377. nread = 0
  378. for n in sizes():
  379. s = f.peek(n)
  380. if s == b'':
  381. break
  382. self.assertEqual(f.read(len(s)), s)
  383. nread += len(s)
  384. self.assertEqual(f.read(100), b'')
  385. self.assertEqual(nread, len(uncompressed))
  386. def test_textio_readlines(self):
  387. # Issue #10791: TextIOWrapper.readlines() fails when wrapping GzipFile.
  388. lines = (data1 * 50).decode("ascii").splitlines(keepends=True)
  389. self.test_write()
  390. with gzip.GzipFile(self.filename, 'r') as f:
  391. with io.TextIOWrapper(f, encoding="ascii") as t:
  392. self.assertEqual(t.readlines(), lines)
  393. def test_fileobj_from_fdopen(self):
  394. # Issue #13781: Opening a GzipFile for writing fails when using a
  395. # fileobj created with os.fdopen().
  396. fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
  397. with os.fdopen(fd, "wb") as f:
  398. with gzip.GzipFile(fileobj=f, mode="w") as g:
  399. pass
  400. def test_fileobj_mode(self):
  401. gzip.GzipFile(self.filename, "wb").close()
  402. with open(self.filename, "r+b") as f:
  403. with gzip.GzipFile(fileobj=f, mode='r') as g:
  404. self.assertEqual(g.mode, gzip.READ)
  405. with gzip.GzipFile(fileobj=f, mode='w') as g:
  406. self.assertEqual(g.mode, gzip.WRITE)
  407. with gzip.GzipFile(fileobj=f, mode='a') as g:
  408. self.assertEqual(g.mode, gzip.WRITE)
  409. with gzip.GzipFile(fileobj=f, mode='x') as g:
  410. self.assertEqual(g.mode, gzip.WRITE)
  411. with self.assertRaises(ValueError):
  412. gzip.GzipFile(fileobj=f, mode='z')
  413. for mode in "rb", "r+b":
  414. with open(self.filename, mode) as f:
  415. with gzip.GzipFile(fileobj=f) as g:
  416. self.assertEqual(g.mode, gzip.READ)
  417. for mode in "wb", "ab", "xb":
  418. if "x" in mode:
  419. os_helper.unlink(self.filename)
  420. with open(self.filename, mode) as f:
  421. with self.assertWarns(FutureWarning):
  422. g = gzip.GzipFile(fileobj=f)
  423. with g:
  424. self.assertEqual(g.mode, gzip.WRITE)
  425. def test_bytes_filename(self):
  426. str_filename = self.filename
  427. try:
  428. bytes_filename = str_filename.encode("ascii")
  429. except UnicodeEncodeError:
  430. self.skipTest("Temporary file name needs to be ASCII")
  431. with gzip.GzipFile(bytes_filename, "wb") as f:
  432. f.write(data1 * 50)
  433. with gzip.GzipFile(bytes_filename, "rb") as f:
  434. self.assertEqual(f.read(), data1 * 50)
  435. # Sanity check that we are actually operating on the right file.
  436. with gzip.GzipFile(str_filename, "rb") as f:
  437. self.assertEqual(f.read(), data1 * 50)
  438. def test_decompress_limited(self):
  439. """Decompressed data buffering should be limited"""
  440. bomb = gzip.compress(b'\0' * int(2e6), compresslevel=9)
  441. self.assertLess(len(bomb), io.DEFAULT_BUFFER_SIZE)
  442. bomb = io.BytesIO(bomb)
  443. decomp = gzip.GzipFile(fileobj=bomb)
  444. self.assertEqual(decomp.read(1), b'\0')
  445. max_decomp = 1 + io.DEFAULT_BUFFER_SIZE
  446. self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp,
  447. "Excessive amount of data was decompressed")
  448. # Testing compress/decompress shortcut functions
  449. def test_compress(self):
  450. for data in [data1, data2]:
  451. for args in [(), (1,), (6,), (9,)]:
  452. datac = gzip.compress(data, *args)
  453. self.assertEqual(type(datac), bytes)
  454. with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
  455. self.assertEqual(f.read(), data)
  456. def test_compress_mtime(self):
  457. mtime = 123456789
  458. for data in [data1, data2]:
  459. for args in [(), (1,), (6,), (9,)]:
  460. with self.subTest(data=data, args=args):
  461. datac = gzip.compress(data, *args, mtime=mtime)
  462. self.assertEqual(type(datac), bytes)
  463. with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
  464. f.read(1) # to set mtime attribute
  465. self.assertEqual(f.mtime, mtime)
  466. def test_compress_correct_level(self):
  467. # gzip.compress calls with mtime == 0 take a different code path.
  468. for mtime in (0, 42):
  469. with self.subTest(mtime=mtime):
  470. nocompress = gzip.compress(data1, compresslevel=0, mtime=mtime)
  471. yescompress = gzip.compress(data1, compresslevel=1, mtime=mtime)
  472. self.assertIn(data1, nocompress)
  473. self.assertNotIn(data1, yescompress)
  474. def test_decompress(self):
  475. for data in (data1, data2):
  476. buf = io.BytesIO()
  477. with gzip.GzipFile(fileobj=buf, mode="wb") as f:
  478. f.write(data)
  479. self.assertEqual(gzip.decompress(buf.getvalue()), data)
  480. # Roundtrip with compress
  481. datac = gzip.compress(data)
  482. self.assertEqual(gzip.decompress(datac), data)
  483. def test_decompress_truncated_trailer(self):
  484. compressed_data = gzip.compress(data1)
  485. self.assertRaises(EOFError, gzip.decompress, compressed_data[:-4])
  486. def test_decompress_missing_trailer(self):
  487. compressed_data = gzip.compress(data1)
  488. self.assertRaises(EOFError, gzip.decompress, compressed_data[:-8])
  489. def test_read_truncated(self):
  490. data = data1*50
  491. # Drop the CRC (4 bytes) and file size (4 bytes).
  492. truncated = gzip.compress(data)[:-8]
  493. with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
  494. self.assertRaises(EOFError, f.read)
  495. with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
  496. self.assertEqual(f.read(len(data)), data)
  497. self.assertRaises(EOFError, f.read, 1)
  498. # Incomplete 10-byte header.
  499. for i in range(2, 10):
  500. with gzip.GzipFile(fileobj=io.BytesIO(truncated[:i])) as f:
  501. self.assertRaises(EOFError, f.read, 1)
  502. def test_read_with_extra(self):
  503. # Gzip data with an extra field
  504. gzdata = (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'
  505. b'\x05\x00Extra'
  506. b'\x0bI-.\x01\x002\xd1Mx\x04\x00\x00\x00')
  507. with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
  508. self.assertEqual(f.read(), b'Test')
  509. def test_prepend_error(self):
  510. # See issue #20875
  511. with gzip.open(self.filename, "wb") as f:
  512. f.write(data1)
  513. with gzip.open(self.filename, "rb") as f:
  514. f._buffer.raw._fp.prepend()
  515. def test_issue44439(self):
  516. q = array.array('Q', [1, 2, 3, 4, 5])
  517. LENGTH = len(q) * q.itemsize
  518. with gzip.GzipFile(fileobj=io.BytesIO(), mode='w') as f:
  519. self.assertEqual(f.write(q), LENGTH)
  520. self.assertEqual(f.tell(), LENGTH)
  521. class TestOpen(BaseTest):
  522. def test_binary_modes(self):
  523. uncompressed = data1 * 50
  524. with gzip.open(self.filename, "wb") as f:
  525. f.write(uncompressed)
  526. with open(self.filename, "rb") as f:
  527. file_data = gzip.decompress(f.read())
  528. self.assertEqual(file_data, uncompressed)
  529. with gzip.open(self.filename, "rb") as f:
  530. self.assertEqual(f.read(), uncompressed)
  531. with gzip.open(self.filename, "ab") as f:
  532. f.write(uncompressed)
  533. with open(self.filename, "rb") as f:
  534. file_data = gzip.decompress(f.read())
  535. self.assertEqual(file_data, uncompressed * 2)
  536. with self.assertRaises(FileExistsError):
  537. gzip.open(self.filename, "xb")
  538. os_helper.unlink(self.filename)
  539. with gzip.open(self.filename, "xb") as f:
  540. f.write(uncompressed)
  541. with open(self.filename, "rb") as f:
  542. file_data = gzip.decompress(f.read())
  543. self.assertEqual(file_data, uncompressed)
  544. def test_pathlike_file(self):
  545. filename = pathlib.Path(self.filename)
  546. with gzip.open(filename, "wb") as f:
  547. f.write(data1 * 50)
  548. with gzip.open(filename, "ab") as f:
  549. f.write(data1)
  550. with gzip.open(filename) as f:
  551. self.assertEqual(f.read(), data1 * 51)
  552. def test_implicit_binary_modes(self):
  553. # Test implicit binary modes (no "b" or "t" in mode string).
  554. uncompressed = data1 * 50
  555. with gzip.open(self.filename, "w") as f:
  556. f.write(uncompressed)
  557. with open(self.filename, "rb") as f:
  558. file_data = gzip.decompress(f.read())
  559. self.assertEqual(file_data, uncompressed)
  560. with gzip.open(self.filename, "r") as f:
  561. self.assertEqual(f.read(), uncompressed)
  562. with gzip.open(self.filename, "a") as f:
  563. f.write(uncompressed)
  564. with open(self.filename, "rb") as f:
  565. file_data = gzip.decompress(f.read())
  566. self.assertEqual(file_data, uncompressed * 2)
  567. with self.assertRaises(FileExistsError):
  568. gzip.open(self.filename, "x")
  569. os_helper.unlink(self.filename)
  570. with gzip.open(self.filename, "x") as f:
  571. f.write(uncompressed)
  572. with open(self.filename, "rb") as f:
  573. file_data = gzip.decompress(f.read())
  574. self.assertEqual(file_data, uncompressed)
  575. def test_text_modes(self):
  576. uncompressed = data1.decode("ascii") * 50
  577. uncompressed_raw = uncompressed.replace("\n", os.linesep)
  578. with gzip.open(self.filename, "wt", encoding="ascii") as f:
  579. f.write(uncompressed)
  580. with open(self.filename, "rb") as f:
  581. file_data = gzip.decompress(f.read()).decode("ascii")
  582. self.assertEqual(file_data, uncompressed_raw)
  583. with gzip.open(self.filename, "rt", encoding="ascii") as f:
  584. self.assertEqual(f.read(), uncompressed)
  585. with gzip.open(self.filename, "at", encoding="ascii") as f:
  586. f.write(uncompressed)
  587. with open(self.filename, "rb") as f:
  588. file_data = gzip.decompress(f.read()).decode("ascii")
  589. self.assertEqual(file_data, uncompressed_raw * 2)
  590. def test_fileobj(self):
  591. uncompressed_bytes = data1 * 50
  592. uncompressed_str = uncompressed_bytes.decode("ascii")
  593. compressed = gzip.compress(uncompressed_bytes)
  594. with gzip.open(io.BytesIO(compressed), "r") as f:
  595. self.assertEqual(f.read(), uncompressed_bytes)
  596. with gzip.open(io.BytesIO(compressed), "rb") as f:
  597. self.assertEqual(f.read(), uncompressed_bytes)
  598. with gzip.open(io.BytesIO(compressed), "rt", encoding="ascii") as f:
  599. self.assertEqual(f.read(), uncompressed_str)
  600. def test_bad_params(self):
  601. # Test invalid parameter combinations.
  602. with self.assertRaises(TypeError):
  603. gzip.open(123.456)
  604. with self.assertRaises(ValueError):
  605. gzip.open(self.filename, "wbt")
  606. with self.assertRaises(ValueError):
  607. gzip.open(self.filename, "xbt")
  608. with self.assertRaises(ValueError):
  609. gzip.open(self.filename, "rb", encoding="utf-8")
  610. with self.assertRaises(ValueError):
  611. gzip.open(self.filename, "rb", errors="ignore")
  612. with self.assertRaises(ValueError):
  613. gzip.open(self.filename, "rb", newline="\n")
  614. def test_encoding(self):
  615. # Test non-default encoding.
  616. uncompressed = data1.decode("ascii") * 50
  617. uncompressed_raw = uncompressed.replace("\n", os.linesep)
  618. with gzip.open(self.filename, "wt", encoding="utf-16") as f:
  619. f.write(uncompressed)
  620. with open(self.filename, "rb") as f:
  621. file_data = gzip.decompress(f.read()).decode("utf-16")
  622. self.assertEqual(file_data, uncompressed_raw)
  623. with gzip.open(self.filename, "rt", encoding="utf-16") as f:
  624. self.assertEqual(f.read(), uncompressed)
  625. def test_encoding_error_handler(self):
  626. # Test with non-default encoding error handler.
  627. with gzip.open(self.filename, "wb") as f:
  628. f.write(b"foo\xffbar")
  629. with gzip.open(self.filename, "rt", encoding="ascii", errors="ignore") \
  630. as f:
  631. self.assertEqual(f.read(), "foobar")
  632. def test_newline(self):
  633. # Test with explicit newline (universal newline mode disabled).
  634. uncompressed = data1.decode("ascii") * 50
  635. with gzip.open(self.filename, "wt", encoding="ascii", newline="\n") as f:
  636. f.write(uncompressed)
  637. with gzip.open(self.filename, "rt", encoding="ascii", newline="\r") as f:
  638. self.assertEqual(f.readlines(), [uncompressed])
  639. def create_and_remove_directory(directory):
  640. def decorator(function):
  641. @functools.wraps(function)
  642. def wrapper(*args, **kwargs):
  643. os.makedirs(directory)
  644. try:
  645. return function(*args, **kwargs)
  646. finally:
  647. os_helper.rmtree(directory)
  648. return wrapper
  649. return decorator
  650. class TestCommandLine(unittest.TestCase):
  651. data = b'This is a simple test with gzip'
  652. @requires_subprocess()
  653. def test_decompress_stdin_stdout(self):
  654. with io.BytesIO() as bytes_io:
  655. with gzip.GzipFile(fileobj=bytes_io, mode='wb') as gzip_file:
  656. gzip_file.write(self.data)
  657. args = sys.executable, '-m', 'gzip', '-d'
  658. with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
  659. out, err = proc.communicate(bytes_io.getvalue())
  660. self.assertEqual(err, b'')
  661. self.assertEqual(out, self.data)
  662. @create_and_remove_directory(TEMPDIR)
  663. def test_decompress_infile_outfile(self):
  664. gzipname = os.path.join(TEMPDIR, 'testgzip.gz')
  665. self.assertFalse(os.path.exists(gzipname))
  666. with gzip.open(gzipname, mode='wb') as fp:
  667. fp.write(self.data)
  668. rc, out, err = assert_python_ok('-m', 'gzip', '-d', gzipname)
  669. with open(os.path.join(TEMPDIR, "testgzip"), "rb") as gunziped:
  670. self.assertEqual(gunziped.read(), self.data)
  671. self.assertTrue(os.path.exists(gzipname))
  672. self.assertEqual(rc, 0)
  673. self.assertEqual(out, b'')
  674. self.assertEqual(err, b'')
  675. def test_decompress_infile_outfile_error(self):
  676. rc, out, err = assert_python_failure('-m', 'gzip', '-d', 'thisisatest.out')
  677. self.assertEqual(b"filename doesn't end in .gz: 'thisisatest.out'", err.strip())
  678. self.assertEqual(rc, 1)
  679. self.assertEqual(out, b'')
  680. @requires_subprocess()
  681. @create_and_remove_directory(TEMPDIR)
  682. def test_compress_stdin_outfile(self):
  683. args = sys.executable, '-m', 'gzip'
  684. with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
  685. out, err = proc.communicate(self.data)
  686. self.assertEqual(err, b'')
  687. self.assertEqual(out[:2], b"\x1f\x8b")
  688. @create_and_remove_directory(TEMPDIR)
  689. def test_compress_infile_outfile_default(self):
  690. local_testgzip = os.path.join(TEMPDIR, 'testgzip')
  691. gzipname = local_testgzip + '.gz'
  692. self.assertFalse(os.path.exists(gzipname))
  693. with open(local_testgzip, 'wb') as fp:
  694. fp.write(self.data)
  695. rc, out, err = assert_python_ok('-m', 'gzip', local_testgzip)
  696. self.assertTrue(os.path.exists(gzipname))
  697. self.assertEqual(out, b'')
  698. self.assertEqual(err, b'')
  699. @create_and_remove_directory(TEMPDIR)
  700. def test_compress_infile_outfile(self):
  701. for compress_level in ('--fast', '--best'):
  702. with self.subTest(compress_level=compress_level):
  703. local_testgzip = os.path.join(TEMPDIR, 'testgzip')
  704. gzipname = local_testgzip + '.gz'
  705. self.assertFalse(os.path.exists(gzipname))
  706. with open(local_testgzip, 'wb') as fp:
  707. fp.write(self.data)
  708. rc, out, err = assert_python_ok('-m', 'gzip', compress_level, local_testgzip)
  709. self.assertTrue(os.path.exists(gzipname))
  710. self.assertEqual(out, b'')
  711. self.assertEqual(err, b'')
  712. os.remove(gzipname)
  713. self.assertFalse(os.path.exists(gzipname))
  714. def test_compress_fast_best_are_exclusive(self):
  715. rc, out, err = assert_python_failure('-m', 'gzip', '--fast', '--best')
  716. self.assertIn(b"error: argument --best: not allowed with argument --fast", err)
  717. self.assertEqual(out, b'')
  718. def test_decompress_cannot_have_flags_compression(self):
  719. rc, out, err = assert_python_failure('-m', 'gzip', '--fast', '-d')
  720. self.assertIn(b'error: argument -d/--decompress: not allowed with argument --fast', err)
  721. self.assertEqual(out, b'')
  722. if __name__ == "__main__":
  723. unittest.main()