-
-
Notifications
You must be signed in to change notification settings - Fork 31.2k
/
Copy pathtest_tarfile.py
4137 lines (3508 loc) · 158 KB
/
test_tarfile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import errno
import sys
import os
import io
from hashlib import sha256
from contextlib import contextmanager
from random import Random
import pathlib
import shutil
import re
import warnings
import stat
import unittest
import unittest.mock
import tarfile
from test import archiver_tests
from test import support
from test.support import os_helper
from test.support import script_helper
from test.support import warnings_helper
# Check for our compression modules.
try:
import gzip
except ImportError:
gzip = None
try:
import zlib
except ImportError:
zlib = None
try:
import bz2
except ImportError:
bz2 = None
try:
import lzma
except ImportError:
lzma = None
def sha256sum(data):
return sha256(data).hexdigest()
TEMPDIR = os.path.abspath(os_helper.TESTFN) + "-tardir"
tarextdir = TEMPDIR + '-extract-test'
tarname = support.findfile("testtar.tar")
gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
tmpname = os.path.join(TEMPDIR, "tmp.tar")
dotlessname = os.path.join(TEMPDIR, "testtar")
sha256_regtype = (
"e09e4bc8b3c9d9177e77256353b36c159f5f040531bbd4b024a8f9b9196c71ce"
)
sha256_sparse = (
"4f05a776071146756345ceee937b33fc5644f5a96b9780d1c7d6a32cdf164d7b"
)
class TarTest:
tarname = tarname
suffix = ''
open = io.FileIO
taropen = tarfile.TarFile.taropen
@property
def mode(self):
return self.prefix + self.suffix
@support.requires_gzip()
class GzipTest:
tarname = gzipname
suffix = 'gz'
open = gzip.GzipFile if gzip else None
taropen = tarfile.TarFile.gzopen
@support.requires_bz2()
class Bz2Test:
tarname = bz2name
suffix = 'bz2'
open = bz2.BZ2File if bz2 else None
taropen = tarfile.TarFile.bz2open
@support.requires_lzma()
class LzmaTest:
tarname = xzname
suffix = 'xz'
open = lzma.LZMAFile if lzma else None
taropen = tarfile.TarFile.xzopen
class ReadTest(TarTest):
prefix = "r:"
def setUp(self):
self.tar = tarfile.open(self.tarname, mode=self.mode,
encoding="iso8859-1")
def tearDown(self):
self.tar.close()
class UstarReadTest(ReadTest, unittest.TestCase):
def test_fileobj_regular_file(self):
tarinfo = self.tar.getmember("ustar/regtype")
with self.tar.extractfile(tarinfo) as fobj:
data = fobj.read()
self.assertEqual(len(data), tarinfo.size,
"regular file extraction failed")
self.assertEqual(sha256sum(data), sha256_regtype,
"regular file extraction failed")
def test_fileobj_readlines(self):
self.tar.extract("ustar/regtype", TEMPDIR, filter='data')
tarinfo = self.tar.getmember("ustar/regtype")
with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
lines1 = fobj1.readlines()
with self.tar.extractfile(tarinfo) as fobj:
fobj2 = io.TextIOWrapper(fobj)
lines2 = fobj2.readlines()
self.assertEqual(lines1, lines2,
"fileobj.readlines() failed")
self.assertEqual(len(lines2), 114,
"fileobj.readlines() failed")
self.assertEqual(lines2[83],
"I will gladly admit that Python is not the fastest "
"running scripting language.\n",
"fileobj.readlines() failed")
def test_fileobj_iter(self):
self.tar.extract("ustar/regtype", TEMPDIR, filter='data')
tarinfo = self.tar.getmember("ustar/regtype")
with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
lines1 = fobj1.readlines()
with self.tar.extractfile(tarinfo) as fobj2:
lines2 = list(io.TextIOWrapper(fobj2))
self.assertEqual(lines1, lines2,
"fileobj.__iter__() failed")
def test_fileobj_seek(self):
self.tar.extract("ustar/regtype", TEMPDIR,
filter='data')
with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
data = fobj.read()
tarinfo = self.tar.getmember("ustar/regtype")
with self.tar.extractfile(tarinfo) as fobj:
text = fobj.read()
fobj.seek(0)
self.assertEqual(0, fobj.tell(),
"seek() to file's start failed")
fobj.seek(2048, 0)
self.assertEqual(2048, fobj.tell(),
"seek() to absolute position failed")
fobj.seek(-1024, 1)
self.assertEqual(1024, fobj.tell(),
"seek() to negative relative position failed")
fobj.seek(1024, 1)
self.assertEqual(2048, fobj.tell(),
"seek() to positive relative position failed")
s = fobj.read(10)
self.assertEqual(s, data[2048:2058],
"read() after seek failed")
fobj.seek(0, 2)
self.assertEqual(tarinfo.size, fobj.tell(),
"seek() to file's end failed")
self.assertEqual(fobj.read(), b"",
"read() at file's end did not return empty string")
fobj.seek(-tarinfo.size, 2)
self.assertEqual(0, fobj.tell(),
"relative seek() to file's end failed")
fobj.seek(512)
s1 = fobj.readlines()
fobj.seek(512)
s2 = fobj.readlines()
self.assertEqual(s1, s2,
"readlines() after seek failed")
fobj.seek(0)
self.assertEqual(len(fobj.readline()), fobj.tell(),
"tell() after readline() failed")
fobj.seek(512)
self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
"tell() after seek() and readline() failed")
fobj.seek(0)
line = fobj.readline()
self.assertEqual(fobj.read(), data[len(line):],
"read() after readline() failed")
def test_fileobj_text(self):
with self.tar.extractfile("ustar/regtype") as fobj:
fobj = io.TextIOWrapper(fobj)
data = fobj.read().encode("iso8859-1")
self.assertEqual(sha256sum(data), sha256_regtype)
try:
fobj.seek(100)
except AttributeError:
# Issue #13815: seek() complained about a missing
# flush() method.
self.fail("seeking failed in text mode")
# Test if symbolic and hard links are resolved by extractfile(). The
# test link members each point to a regular member whose data is
# supposed to be exported.
def _test_fileobj_link(self, lnktype, regtype):
with self.tar.extractfile(lnktype) as a, \
self.tar.extractfile(regtype) as b:
self.assertEqual(a.name, b.name)
def test_fileobj_link1(self):
self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
def test_fileobj_link2(self):
self._test_fileobj_link("./ustar/linktest2/lnktype",
"ustar/linktest1/regtype")
def test_fileobj_symlink1(self):
self._test_fileobj_link("ustar/symtype", "ustar/regtype")
def test_fileobj_symlink2(self):
self._test_fileobj_link("./ustar/linktest2/symtype",
"ustar/linktest1/regtype")
def test_issue14160(self):
self._test_fileobj_link("symtype2", "ustar/regtype")
def test_add_dir_getmember(self):
# bpo-21987
self.add_dir_and_getmember('bar')
self.add_dir_and_getmember('a'*101)
@unittest.skipUnless(hasattr(os, "getuid") and hasattr(os, "getgid"),
"Missing getuid or getgid implementation")
def add_dir_and_getmember(self, name):
def filter(tarinfo):
tarinfo.uid = tarinfo.gid = 100
return tarinfo
with os_helper.temp_cwd():
with tarfile.open(tmpname, 'w') as tar:
tar.format = tarfile.USTAR_FORMAT
try:
os.mkdir(name)
tar.add(name, filter=filter)
finally:
os.rmdir(name)
with tarfile.open(tmpname) as tar:
self.assertEqual(
tar.getmember(name),
tar.getmember(name + '/')
)
class GzipUstarReadTest(GzipTest, UstarReadTest):
pass
class Bz2UstarReadTest(Bz2Test, UstarReadTest):
pass
class LzmaUstarReadTest(LzmaTest, UstarReadTest):
pass
class ListTest(ReadTest, unittest.TestCase):
# Override setUp to use default encoding (UTF-8)
def setUp(self):
self.tar = tarfile.open(self.tarname, mode=self.mode)
def test_list(self):
tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
with support.swap_attr(sys, 'stdout', tio):
self.tar.list(verbose=False)
out = tio.detach().getvalue()
self.assertIn(b'ustar/conttype', out)
self.assertIn(b'ustar/regtype', out)
self.assertIn(b'ustar/lnktype', out)
self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
self.assertIn(b'./ustar/linktest2/symtype', out)
self.assertIn(b'./ustar/linktest2/lnktype', out)
# Make sure it puts trailing slash for directory
self.assertIn(b'ustar/dirtype/', out)
self.assertIn(b'ustar/dirtype-with-size/', out)
# Make sure it is able to print unencodable characters
def conv(b):
s = b.decode(self.tar.encoding, 'surrogateescape')
return s.encode('ascii', 'backslashreplace')
self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
# Make sure it prints files separated by one newline without any
# 'ls -l'-like accessories if verbose flag is not being used
# ...
# ustar/conttype
# ustar/regtype
# ...
self.assertRegex(out, br'ustar/conttype ?\r?\n'
br'ustar/regtype ?\r?\n')
# Make sure it does not print the source of link without verbose flag
self.assertNotIn(b'link to', out)
self.assertNotIn(b'->', out)
def test_list_verbose(self):
tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
with support.swap_attr(sys, 'stdout', tio):
self.tar.list(verbose=True)
out = tio.detach().getvalue()
# Make sure it prints files separated by one newline with 'ls -l'-like
# accessories if verbose flag is being used
# ...
# ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
# ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
# ...
self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
br'ustar/\w+type ?\r?\n') * 2)
# Make sure it prints the source of link with verbose flag
self.assertIn(b'ustar/symtype -> regtype', out)
self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
self.assertIn(b'./ustar/linktest2/lnktype link to '
b'./ustar/linktest1/regtype', out)
self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
(b'/123' * 125) + b'/longname', out)
self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
(b'/123' * 125) + b'/longname', out)
def test_list_members(self):
tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
def members(tar):
for tarinfo in tar.getmembers():
if 'reg' in tarinfo.name:
yield tarinfo
with support.swap_attr(sys, 'stdout', tio):
self.tar.list(verbose=False, members=members(self.tar))
out = tio.detach().getvalue()
self.assertIn(b'ustar/regtype', out)
self.assertNotIn(b'ustar/conttype', out)
class GzipListTest(GzipTest, ListTest):
pass
class Bz2ListTest(Bz2Test, ListTest):
pass
class LzmaListTest(LzmaTest, ListTest):
pass
class CommonReadTest(ReadTest):
def test_is_tarfile_erroneous(self):
with open(tmpname, "wb"):
pass
# is_tarfile works on filenames
self.assertFalse(tarfile.is_tarfile(tmpname))
# is_tarfile works on path-like objects
self.assertFalse(tarfile.is_tarfile(pathlib.Path(tmpname)))
# is_tarfile works on file objects
with open(tmpname, "rb") as fobj:
self.assertFalse(tarfile.is_tarfile(fobj))
# is_tarfile works on file-like objects
self.assertFalse(tarfile.is_tarfile(io.BytesIO(b"invalid")))
def test_is_tarfile_valid(self):
# is_tarfile works on filenames
self.assertTrue(tarfile.is_tarfile(self.tarname))
# is_tarfile works on path-like objects
self.assertTrue(tarfile.is_tarfile(pathlib.Path(self.tarname)))
# is_tarfile works on file objects
with open(self.tarname, "rb") as fobj:
self.assertTrue(tarfile.is_tarfile(fobj))
# is_tarfile works on file-like objects
with open(self.tarname, "rb") as fobj:
self.assertTrue(tarfile.is_tarfile(io.BytesIO(fobj.read())))
def test_is_tarfile_keeps_position(self):
# Test for issue44289: tarfile.is_tarfile() modifies
# file object's current position
with open(self.tarname, "rb") as fobj:
tarfile.is_tarfile(fobj)
self.assertEqual(fobj.tell(), 0)
with open(self.tarname, "rb") as fobj:
file_like = io.BytesIO(fobj.read())
tarfile.is_tarfile(file_like)
self.assertEqual(file_like.tell(), 0)
def test_empty_tarfile(self):
# Test for issue6123: Allow opening empty archives.
# This test checks if tarfile.open() is able to open an empty tar
# archive successfully. Note that an empty tar archive is not the
# same as an empty file!
with tarfile.open(tmpname, self.mode.replace("r", "w")):
pass
try:
tar = tarfile.open(tmpname, self.mode)
tar.getnames()
except tarfile.ReadError:
self.fail("tarfile.open() failed on empty archive")
else:
self.assertListEqual(tar.getmembers(), [])
finally:
tar.close()
def test_non_existent_tarfile(self):
# Test for issue11513: prevent non-existent gzipped tarfiles raising
# multiple exceptions.
with self.assertRaisesRegex(FileNotFoundError, "xxx"):
tarfile.open("xxx", self.mode)
def test_null_tarfile(self):
# Test for issue6123: Allow opening empty archives.
# This test guarantees that tarfile.open() does not treat an empty
# file as an empty tar archive.
with open(tmpname, "wb"):
pass
self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
def test_ignore_zeros(self):
# Test TarFile's ignore_zeros option.
# generate 512 pseudorandom bytes
data = Random(0).randbytes(512)
for char in (b'\0', b'a'):
# Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
# are ignored correctly.
with self.open(tmpname, "w") as fobj:
fobj.write(char * 1024)
tarinfo = tarfile.TarInfo("foo")
tarinfo.size = len(data)
fobj.write(tarinfo.tobuf())
fobj.write(data)
tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
try:
self.assertListEqual(tar.getnames(), ["foo"],
"ignore_zeros=True should have skipped the %r-blocks" %
char)
finally:
tar.close()
def test_premature_end_of_archive(self):
for size in (512, 600, 1024, 1200):
with tarfile.open(tmpname, "w:") as tar:
t = tarfile.TarInfo("foo")
t.size = 1024
tar.addfile(t, io.BytesIO(b"a" * 1024))
with open(tmpname, "r+b") as fobj:
fobj.truncate(size)
with tarfile.open(tmpname) as tar:
with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
for t in tar:
pass
with tarfile.open(tmpname) as tar:
t = tar.next()
with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
tar.extract(t, TEMPDIR, filter='data')
with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
tar.extractfile(t).read()
def test_length_zero_header(self):
# bpo-39017 (CVE-2019-20907): reading a zero-length header should fail
# with an exception
with self.assertRaisesRegex(tarfile.ReadError, "file could not be opened successfully"):
with tarfile.open(support.findfile('recursion.tar')) as tar:
pass
def test_extractfile_attrs(self):
# gh-74468: TarFile.name must name a file, not a parent archive.
file = self.tar.getmember('ustar/regtype')
with self.tar.extractfile(file) as fobj:
self.assertRaises(AttributeError, fobj.fileno)
self.assertIs(fobj.readable(), True)
self.assertIs(fobj.writable(), False)
if self.is_stream:
self.assertRaises(AttributeError, fobj.seekable)
else:
self.assertIs(fobj.seekable(), True)
self.assertIs(fobj.closed, False)
self.assertIs(fobj.closed, True)
self.assertRaises(AttributeError, fobj.fileno)
self.assertIs(fobj.readable(), True)
self.assertIs(fobj.writable(), False)
if self.is_stream:
self.assertRaises(AttributeError, fobj.seekable)
else:
self.assertIs(fobj.seekable(), True)
class MiscReadTestBase(CommonReadTest):
is_stream = False
def requires_name_attribute(self):
pass
def test_no_name_argument(self):
self.requires_name_attribute()
with open(self.tarname, "rb") as fobj:
self.assertIsInstance(fobj.name, str)
with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
self.assertIsInstance(tar.name, str)
self.assertEqual(tar.name, os.path.abspath(fobj.name))
def test_no_name_attribute(self):
with open(self.tarname, "rb") as fobj:
data = fobj.read()
fobj = io.BytesIO(data)
self.assertRaises(AttributeError, getattr, fobj, "name")
tar = tarfile.open(fileobj=fobj, mode=self.mode)
self.assertIsNone(tar.name)
def test_empty_name_attribute(self):
with open(self.tarname, "rb") as fobj:
data = fobj.read()
fobj = io.BytesIO(data)
fobj.name = ""
with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
self.assertIsNone(tar.name)
def test_int_name_attribute(self):
# Issue 21044: tarfile.open() should handle fileobj with an integer
# 'name' attribute.
fd = os.open(self.tarname, os.O_RDONLY)
with open(fd, 'rb') as fobj:
self.assertIsInstance(fobj.name, int)
with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
self.assertIsNone(tar.name)
def test_bytes_name_attribute(self):
self.requires_name_attribute()
tarname = os.fsencode(self.tarname)
with open(tarname, 'rb') as fobj:
self.assertIsInstance(fobj.name, bytes)
with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
self.assertIsInstance(tar.name, bytes)
self.assertEqual(tar.name, os.path.abspath(fobj.name))
def test_pathlike_name(self):
tarname = pathlib.Path(self.tarname)
with tarfile.open(tarname, mode=self.mode) as tar:
self.assertIsInstance(tar.name, str)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
with self.taropen(tarname) as tar:
self.assertIsInstance(tar.name, str)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
with tarfile.TarFile.open(tarname, mode=self.mode) as tar:
self.assertIsInstance(tar.name, str)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
if self.suffix == '':
with tarfile.TarFile(tarname, mode='r') as tar:
self.assertIsInstance(tar.name, str)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
def test_illegal_mode_arg(self):
with open(tmpname, 'wb'):
pass
with self.assertRaisesRegex(ValueError, 'mode must be '):
tar = self.taropen(tmpname, 'q')
with self.assertRaisesRegex(ValueError, 'mode must be '):
tar = self.taropen(tmpname, 'rw')
with self.assertRaisesRegex(ValueError, 'mode must be '):
tar = self.taropen(tmpname, '')
def test_fileobj_with_offset(self):
# Skip the first member and store values from the second member
# of the testtar.
tar = tarfile.open(self.tarname, mode=self.mode)
try:
tar.next()
t = tar.next()
name = t.name
offset = t.offset
with tar.extractfile(t) as f:
data = f.read()
finally:
tar.close()
# Open the testtar and seek to the offset of the second member.
with self.open(self.tarname) as fobj:
fobj.seek(offset)
# Test if the tarfile starts with the second member.
with tar.open(self.tarname, mode="r:", fileobj=fobj) as tar:
t = tar.next()
self.assertEqual(t.name, name)
# Read to the end of fileobj and test if seeking back to the
# beginning works.
tar.getmembers()
self.assertEqual(tar.extractfile(t).read(), data,
"seek back did not work")
def test_fail_comp(self):
# For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
with open(tarname, "rb") as fobj:
self.assertRaises(tarfile.ReadError, tarfile.open,
fileobj=fobj, mode=self.mode)
def test_v7_dirtype(self):
# Test old style dirtype member (bug #1336623):
# Old V7 tars create directory members using an AREGTYPE
# header with a "/" appended to the filename field.
tarinfo = self.tar.getmember("misc/dirtype-old-v7")
self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
"v7 dirtype failed")
def test_xstar_type(self):
# The xstar format stores extra atime and ctime fields inside the
# space reserved for the prefix field. The prefix field must be
# ignored in this case, otherwise it will mess up the name.
try:
self.tar.getmember("misc/regtype-xstar")
except KeyError:
self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
def test_check_members(self):
for tarinfo in self.tar:
self.assertEqual(int(tarinfo.mtime), 0o7606136617,
"wrong mtime for %s" % tarinfo.name)
if not tarinfo.name.startswith("ustar/"):
continue
self.assertEqual(tarinfo.uname, "tarfile",
"wrong uname for %s" % tarinfo.name)
def test_find_members(self):
self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
"could not find all members")
@unittest.skipUnless(hasattr(os, "link"),
"Missing hardlink implementation")
@os_helper.skip_unless_symlink
def test_extract_hardlink(self):
# Test hardlink extraction (e.g. bug #857297).
with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
tar.extract("ustar/regtype", TEMPDIR, filter='data')
self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
tar.extract("ustar/lnktype", TEMPDIR, filter='data')
self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
data = f.read()
self.assertEqual(sha256sum(data), sha256_regtype)
tar.extract("ustar/symtype", TEMPDIR, filter='data')
self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
data = f.read()
self.assertEqual(sha256sum(data), sha256_regtype)
@os_helper.skip_unless_working_chmod
def test_extractall(self):
# Test if extractall() correctly restores directory permissions
# and times (see issue1735).
tar = tarfile.open(tarname, encoding="iso8859-1")
DIR = os.path.join(TEMPDIR, "extractall")
os.mkdir(DIR)
try:
directories = [t for t in tar if t.isdir()]
tar.extractall(DIR, directories, filter='fully_trusted')
for tarinfo in directories:
path = os.path.join(DIR, tarinfo.name)
if sys.platform != "win32":
# Win32 has no support for fine grained permissions.
self.assertEqual(tarinfo.mode & 0o777,
os.stat(path).st_mode & 0o777,
tarinfo.name)
def format_mtime(mtime):
if isinstance(mtime, float):
return "{} ({})".format(mtime, mtime.hex())
else:
return "{!r} (int)".format(mtime)
file_mtime = os.path.getmtime(path)
errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
format_mtime(tarinfo.mtime),
format_mtime(file_mtime),
path)
self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
finally:
tar.close()
os_helper.rmtree(DIR)
@os_helper.skip_unless_working_chmod
def test_extract_directory(self):
dirtype = "ustar/dirtype"
DIR = os.path.join(TEMPDIR, "extractdir")
os.mkdir(DIR)
try:
with tarfile.open(tarname, encoding="iso8859-1") as tar:
tarinfo = tar.getmember(dirtype)
tar.extract(tarinfo, path=DIR, filter='fully_trusted')
extracted = os.path.join(DIR, dirtype)
self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
if sys.platform != "win32":
self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
finally:
os_helper.rmtree(DIR)
def test_extractall_pathlike_name(self):
DIR = pathlib.Path(TEMPDIR) / "extractall"
with os_helper.temp_dir(DIR), \
tarfile.open(tarname, encoding="iso8859-1") as tar:
directories = [t for t in tar if t.isdir()]
tar.extractall(DIR, directories, filter='fully_trusted')
for tarinfo in directories:
path = DIR / tarinfo.name
self.assertEqual(os.path.getmtime(path), tarinfo.mtime)
def test_extract_pathlike_name(self):
dirtype = "ustar/dirtype"
DIR = pathlib.Path(TEMPDIR) / "extractall"
with os_helper.temp_dir(DIR), \
tarfile.open(tarname, encoding="iso8859-1") as tar:
tarinfo = tar.getmember(dirtype)
tar.extract(tarinfo, path=DIR, filter='fully_trusted')
extracted = DIR / dirtype
self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
def test_init_close_fobj(self):
# Issue #7341: Close the internal file object in the TarFile
# constructor in case of an error. For the test we rely on
# the fact that opening an empty file raises a ReadError.
empty = os.path.join(TEMPDIR, "empty")
with open(empty, "wb") as fobj:
fobj.write(b"")
try:
tar = object.__new__(tarfile.TarFile)
try:
tar.__init__(empty)
except tarfile.ReadError:
self.assertTrue(tar.fileobj.closed)
else:
self.fail("ReadError not raised")
finally:
os_helper.unlink(empty)
def test_parallel_iteration(self):
# Issue #16601: Restarting iteration over tarfile continued
# from where it left off.
with tarfile.open(self.tarname) as tar:
for m1, m2 in zip(tar, tar):
self.assertEqual(m1.offset, m2.offset)
self.assertEqual(m1.get_info(), m2.get_info())
@unittest.skipIf(zlib is None, "requires zlib")
def test_zlib_error_does_not_leak(self):
# bpo-39039: tarfile.open allowed zlib exceptions to bubble up when
# parsing certain types of invalid data
with unittest.mock.patch("tarfile.TarInfo.fromtarfile") as mock:
mock.side_effect = zlib.error
with self.assertRaises(tarfile.ReadError):
tarfile.open(self.tarname)
def test_next_on_empty_tarfile(self):
fd = io.BytesIO()
tf = tarfile.open(fileobj=fd, mode="w")
tf.close()
fd.seek(0)
with tarfile.open(fileobj=fd, mode="r|") as tf:
self.assertEqual(tf.next(), None)
fd.seek(0)
with tarfile.open(fileobj=fd, mode="r") as tf:
self.assertEqual(tf.next(), None)
class MiscReadTest(MiscReadTestBase, unittest.TestCase):
test_fail_comp = None
class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
pass
class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
def requires_name_attribute(self):
self.skipTest("BZ2File have no name attribute")
class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
def requires_name_attribute(self):
self.skipTest("LZMAFile have no name attribute")
class StreamReadTest(CommonReadTest, unittest.TestCase):
prefix="r|"
is_stream = True
def test_read_through(self):
# Issue #11224: A poorly designed _FileInFile.read() method
# caused seeking errors with stream tar files.
for tarinfo in self.tar:
if not tarinfo.isreg():
continue
with self.tar.extractfile(tarinfo) as fobj:
while True:
try:
buf = fobj.read(512)
except tarfile.StreamError:
self.fail("simple read-through using "
"TarFile.extractfile() failed")
if not buf:
break
def test_fileobj_regular_file(self):
tarinfo = self.tar.next() # get "regtype" (can't use getmember)
with self.tar.extractfile(tarinfo) as fobj:
data = fobj.read()
self.assertEqual(len(data), tarinfo.size,
"regular file extraction failed")
self.assertEqual(sha256sum(data), sha256_regtype,
"regular file extraction failed")
def test_provoke_stream_error(self):
tarinfos = self.tar.getmembers()
with self.tar.extractfile(tarinfos[0]) as f: # read the first member
self.assertRaises(tarfile.StreamError, f.read)
def test_compare_members(self):
tar1 = tarfile.open(tarname, encoding="iso8859-1")
try:
tar2 = self.tar
while True:
t1 = tar1.next()
t2 = tar2.next()
if t1 is None:
break
self.assertIsNotNone(t2, "stream.next() failed.")
if t2.islnk() or t2.issym():
with self.assertRaises(tarfile.StreamError):
tar2.extractfile(t2)
continue
v1 = tar1.extractfile(t1)
v2 = tar2.extractfile(t2)
if v1 is None:
continue
self.assertIsNotNone(v2, "stream.extractfile() failed")
self.assertEqual(v1.read(), v2.read(),
"stream extraction failed")
finally:
tar1.close()
class GzipStreamReadTest(GzipTest, StreamReadTest):
pass
class Bz2StreamReadTest(Bz2Test, StreamReadTest):
pass
class LzmaStreamReadTest(LzmaTest, StreamReadTest):
pass
class DetectReadTest(TarTest, unittest.TestCase):
def _testfunc_file(self, name, mode):
try:
tar = tarfile.open(name, mode)
except tarfile.ReadError as e:
self.fail()
else:
tar.close()
def _testfunc_fileobj(self, name, mode):
try:
with open(name, "rb") as f:
tar = tarfile.open(name, mode, fileobj=f)
except tarfile.ReadError as e:
self.fail()
else:
tar.close()
def _test_modes(self, testfunc):
if self.suffix:
with self.assertRaises(tarfile.ReadError):
tarfile.open(tarname, mode="r:" + self.suffix)
with self.assertRaises(tarfile.ReadError):
tarfile.open(tarname, mode="r|" + self.suffix)
with self.assertRaises(tarfile.ReadError):
tarfile.open(self.tarname, mode="r:")
with self.assertRaises(tarfile.ReadError):
tarfile.open(self.tarname, mode="r|")
testfunc(self.tarname, "r")
testfunc(self.tarname, "r:" + self.suffix)
testfunc(self.tarname, "r:*")
testfunc(self.tarname, "r|" + self.suffix)
testfunc(self.tarname, "r|*")
def test_detect_file(self):
self._test_modes(self._testfunc_file)
def test_detect_fileobj(self):
self._test_modes(self._testfunc_fileobj)
class GzipDetectReadTest(GzipTest, DetectReadTest):
pass
class Bz2DetectReadTest(Bz2Test, DetectReadTest):
def test_detect_stream_bz2(self):
# Originally, tarfile's stream detection looked for the string
# "BZh91" at the start of the file. This is incorrect because
# the '9' represents the blocksize (900,000 bytes). If the file was
# compressed using another blocksize autodetection fails.
with open(tarname, "rb") as fobj:
data = fobj.read()
# Compress with blocksize 100,000 bytes, the file starts with "BZh11".
with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
fobj.write(data)
self._testfunc_file(tmpname, "r|*")
class LzmaDetectReadTest(LzmaTest, DetectReadTest):
pass
class GzipBrokenHeaderCorrectException(GzipTest, unittest.TestCase):
"""
See: https://github.com/python/cpython/issues/107396
"""
def runTest(self):
f = io.BytesIO(
b'\x1f\x8b' # header
b'\x08' # compression method
b'\x04' # flags
b'\0\0\0\0\0\0' # timestamp, compression data, OS ID
b'\0\x01' # size
b'\0\0\0\0\0' # corrupt data (zeros)
)
with self.assertRaises(tarfile.ReadError):
tarfile.open(fileobj=f, mode='r|gz')
class MemberReadTest(ReadTest, unittest.TestCase):
def _test_member(self, tarinfo, chksum=None, **kwargs):
if chksum is not None:
with self.tar.extractfile(tarinfo) as f:
self.assertEqual(sha256sum(f.read()), chksum,
"wrong sha256sum for %s" % tarinfo.name)
kwargs["mtime"] = 0o7606136617
kwargs["uid"] = 1000
kwargs["gid"] = 100
if "old-v7" not in tarinfo.name:
# V7 tar can't handle alphabetic owners.
kwargs["uname"] = "tarfile"
kwargs["gname"] = "tarfile"
for k, v in kwargs.items():
self.assertEqual(getattr(tarinfo, k), v,
"wrong value in %s field of %s" % (k, tarinfo.name))
def test_find_regtype(self):
tarinfo = self.tar.getmember("ustar/regtype")
self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
def test_find_conttype(self):
tarinfo = self.tar.getmember("ustar/conttype")
self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
def test_find_dirtype(self):
tarinfo = self.tar.getmember("ustar/dirtype")
self._test_member(tarinfo, size=0)
def test_find_dirtype_with_size(self):
tarinfo = self.tar.getmember("ustar/dirtype-with-size")
self._test_member(tarinfo, size=255)
def test_find_lnktype(self):
tarinfo = self.tar.getmember("ustar/lnktype")
self._test_member(tarinfo, size=0, linkname="ustar/regtype")
def test_find_symtype(self):
tarinfo = self.tar.getmember("ustar/symtype")
self._test_member(tarinfo, size=0, linkname="regtype")
def test_find_blktype(self):
tarinfo = self.tar.getmember("ustar/blktype")
self._test_member(tarinfo, size=0, devmajor=3, devminor=0)