Debian Codegraph @

tests/test_extract.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import io
2 import os
3 import stat
4 import tarfile
5 from errno import ELOOP
6 from pathlib import Path
7
8 import pytest
9
10 from conda_package_streaming import exceptions, extract, package_streaming
11
12 HAS_TAR_FILTER = hasattr(tarfile, "tar_filter")
13 MAX_CONDAS = 8
14
15
16 def test_extract_stream(conda_paths, tmp_path):
17 for i, package in enumerate(conda_paths):
18 print(package)
19 with open(package, "rb") as fileobj:
20 stream = package_streaming.stream_conda_component(
21 package, fileobj, component=package_streaming.CondaComponent.pkg
22 )
23 dest_dir = tmp_path / package.name
24 extract.extract_stream(stream, dest_dir)
25
26 if i >= MAX_CONDAS:
27 break
28
29
30 def test_extract_all(conda_paths, tmp_path):
31 for i, package in enumerate(conda_paths):
32 print(package)
33 dest_dir = tmp_path / package.name
34 extract.extract(package, dest_dir=dest_dir)
35
36 if i >= MAX_CONDAS:
37 break
38
39
40 def empty_tarfile(name, mode=0o644, tar_mode="w", create_subdir=False):
41 """
42 Return BytesIO containing a tarfile with one empty file named :name
43 """
44 tar = io.BytesIO()
45 t = tarfile.open(mode=tar_mode, fileobj=tar)
46 if create_subdir:
47 tarinfo = tarfile.TarInfo(name=name)
48 # Add execute bit for directory
49 tarinfo.mode = mode | 0o111
50 tarinfo.type = tarfile.DIRTYPE
51 t.addfile(tarinfo, io.BytesIO())
52 tarinfo = tarfile.TarInfo(name=str(Path(name, name)))
53 tarinfo.mode = mode
54 t.addfile(tarinfo, io.BytesIO())
55 else:
56 tarinfo = tarfile.TarInfo(name=name)
57 tarinfo.mode = mode
58 t.addfile(tarinfo, io.BytesIO())
59 t.close()
60 tar.seek(0)
61 return tar
62
63
64 def not_unicode_tarbz2(
65 name=b"\x80\x81".decode("utf-8", errors="surrogateescape"), mode=0o644
66 ):
67 """
68 Return BytesIO containing a tarfile with one empty file named :name
69 """
70 return empty_tarfile(name=name, tar_mode="w:bz2")
71
72
73 def test_oserror(tmp_path):
74 """
75 Fail if tarfile raises OSError (formerly known as IOError)
76 """
77 tar = empty_tarfile("empty-test")
78
79 class TarELOOP(tarfile.TarFile):
80 def extractall(self, path=None, members=None, filter=None):
81 raise OSError(ELOOP, "case sensitivity")
82
83 class TarOSError(tarfile.TarFile):
84 def extractall(self, path=None, members=None, filter=None):
85 raise OSError("not eloop")
86
87 def stream(cls):
88 yield (cls(fileobj=tar), tarfile.TarInfo())
89
90 with pytest.raises(exceptions.CaseInsensitiveFileSystemError):
91 extract.extract_stream(stream(TarELOOP), tmp_path)
92
93 with pytest.raises(OSError):
94 extract.extract_stream(stream(TarOSError), tmp_path)
95
96
97 def stream(fileobj):
98 """
99 Like the tuples produced by part of conda-package-streaming.
100 """
101 yield (package_streaming.TarfileNoSameOwner(fileobj=fileobj), tarfile.TarInfo())
102
103
104 def stream_stdlib(fileobj):
105 """
106 Like the tuples produced by part of conda-package-streaming.
107 """
108 yield (tarfile.TarFile(fileobj=fileobj), tarfile.TarInfo())
109
110
111 def test_slip(tmp_path):
112 """
113 Fail if tarfile tries to put files outside its dest_dir (tmp_path)
114 """
115
116 tar = empty_tarfile(name="../slip")
117
118 with pytest.raises(exceptions.SafetyError):
119 extract.extract_stream(stream(tar), tmp_path)
120
121 # If we are using tarfile.filter, the leading / will be stripped instead.
122 tar2 = empty_tarfile(name="/absolute")
123
124 with pytest.raises(exceptions.SafetyError):
125 extract.extract_stream(stream(tar2), tmp_path)
126
127
128 def test_chown(conda_paths, tmp_path):
129 for package in conda_paths[:2]:
130 print(package)
131 with open(package, "rb") as fileobj:
132 stream = package_streaming.stream_conda_component(
133 package, fileobj, component=package_streaming.CondaComponent.pkg
134 )
135
136 for tar, member in stream:
137 assert isinstance(tar, package_streaming.TarfileNoSameOwner), tar
138 break
139
140
141 @pytest.mark.parametrize(
142 "tar_filter",
143 (pytest.param(None, id="no tar filter"), pytest.param("data", id="data_filter")),
144 )
145 def test_umask(tmp_path, monkeypatch, tar_filter):
146 """
147 Demonstrate that umask-respecting tar implementation works.
148
149 Mock umask in case it is different on your system.
150 """
151 if tar_filter is not None and not HAS_TAR_FILTER:
152 pytest.skip("Requires tar_filter")
153 try:
154 MOCK_UMASK = 0o022
155 current_umask = os.umask(MOCK_UMASK)
156 monkeypatch.setattr(
157 "conda_package_streaming.package_streaming.UMASK", MOCK_UMASK
158 )
159
160 assert (
161 package_streaming.TarfileNoSameOwner(
162 fileobj=empty_tarfile("file.txt")
163 ).umask
164 == MOCK_UMASK
165 )
166
167 # [
168 # ('S_IFREG', 32768),
169 # ('UF_HIDDEN', 32768),
170 # ('FILE_ATTRIBUTE_INTEGRITY_STREAM', 32768)
171 # ]
172
173 # Of the high bits 100755 highest bit 1 can mean just "is regular file"
174
175 name = "naughty_umask"
176 tar3 = empty_tarfile(name=name, mode=0o777, create_subdir=True)
177
178 stat_check = stat.S_IRGRP
179 stat_name = "S_IRGRP"
180
181 root_path = tmp_path / "stdlib"
182 root_path.mkdir()
183 files_to_check = [root_path / name, root_path / name / name]
184
185 extract.extract_stream(stream_stdlib(tar3), root_path, tar_filter=tar_filter)
186 for file in files_to_check:
187 mode = file.stat().st_mode
188 # is the new .extractall(filter=) erasing "stat_name"?
189 assert mode & stat_check, f"{file} has {stat_name}? %o != %o" % (
190 mode,
191 mode & stat_check,
192 )
193
194 # specifically forbid that stat bit
195 MOCK_UMASK |= stat_check
196 monkeypatch.setattr(
197 "conda_package_streaming.package_streaming.UMASK", MOCK_UMASK
198 )
199 os.umask(MOCK_UMASK)
200
201 root_path = tmp_path / "cps"
202 root_path.mkdir()
203 files_to_check = [root_path / name, root_path / name / name]
204
205 tar3.seek(0)
206 extract.extract_stream(stream(tar3), root_path, tar_filter=tar_filter)
207 for file in files_to_check:
208 mode = file.stat().st_mode
209 if mode & stat_check:
210 assert not (mode & stat_check), (
211 f"{file}: No {stat_name} due to umask? %o != %o"
212 % (
213 mode,
214 mode & stat_check,
215 )
216 )
217 finally:
218 os.umask(current_umask)
219
220
221 def test_encoding():
222 """
223 Some users do not have "utf-8" as the default sys.getfilesystemencoding() or
224 sys.getdefaultencoding(). Instead of trying to change the system encoding,
225 we prove that stream_conda_component honors the new passed-in encoding which
226 is now "utf-8" by default.
227 """
228
229 tar = not_unicode_tarbz2()
230
231 # Use new default encoding of "utf-8" regardless of what the system says.
232 stream = package_streaming.stream_conda_component(
233 "package.tar.bz2", tar, component="pkg"
234 )
235
236 with pytest.raises(UnicodeEncodeError):
237 for t, member in stream:
238 member.name.encode("utf-8")
239 print(t, member)
240
241 tar.seek(0)
242
243 # Prove that we are passing encoding all the way down to the TarFile() used
244 # for extraction.
245 stream = package_streaming.stream_conda_component(
246 "package.tar.bz2", tar, component="pkg", encoding="latin-1"
247 )
248
249 for t, member in stream:
250 member.name.encode("utf-8")
251 print(t, member)