Debian Codegraph @

tests/test_extract.py

raw ◀ ▶
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 @pytest.mark.skip(reason="Conda is not yet available for Debian")
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 @pytest.mark.skip(reason="Conda is not yet available for Debian")
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 @pytest.mark.skip(reason="Conda is not yet available for Debian")
129 def test_chown(conda_paths, tmp_path):
130 for package in conda_paths[:2]:
131 print(package)
132 with open(package, "rb") as fileobj:
133 stream = package_streaming.stream_conda_component(
134 package, fileobj, component=package_streaming.CondaComponent.pkg
135 )
136
137 for tar, member in stream:
138 assert isinstance(tar, package_streaming.TarfileNoSameOwner), tar
139 break
140
141
142 @pytest.mark.parametrize(
143 "tar_filter",
144 (pytest.param(None, id="no tar filter"), pytest.param("data", id="data_filter")),
145 )
146 def test_umask(tmp_path, monkeypatch, tar_filter):
147 """
148 Demonstrate that umask-respecting tar implementation works.
149
150 Mock umask in case it is different on your system.
151 """
152 if tar_filter is not None and not HAS_TAR_FILTER:
153 pytest.skip("Requires tar_filter")
154 try:
155 MOCK_UMASK = 0o022
156 current_umask = os.umask(MOCK_UMASK)
157 monkeypatch.setattr(
158 "conda_package_streaming.package_streaming.UMASK", MOCK_UMASK
159 )
160
161 assert (
162 package_streaming.TarfileNoSameOwner(
163 fileobj=empty_tarfile("file.txt")
164 ).umask
165 == MOCK_UMASK
166 )
167
168 # [
169 # ('S_IFREG', 32768),
170 # ('UF_HIDDEN', 32768),
171 # ('FILE_ATTRIBUTE_INTEGRITY_STREAM', 32768)
172 # ]
173
174 # Of the high bits 100755 highest bit 1 can mean just "is regular file"
175
176 name = "naughty_umask"
177 tar3 = empty_tarfile(name=name, mode=0o777, create_subdir=True)
178
179 stat_check = stat.S_IRGRP
180 stat_name = "S_IRGRP"
181
182 root_path = tmp_path / "stdlib"
183 root_path.mkdir()
184 files_to_check = [root_path / name, root_path / name / name]
185
186 extract.extract_stream(stream_stdlib(tar3), root_path, tar_filter=tar_filter)
187 for file in files_to_check:
188 mode = file.stat().st_mode
189 # is the new .extractall(filter=) erasing "stat_name"?
190 assert mode & stat_check, f"{file} has {stat_name}? %o != %o" % (
191 mode,
192 mode & stat_check,
193 )
194
195 # specifically forbid that stat bit
196 MOCK_UMASK |= stat_check
197 monkeypatch.setattr(
198 "conda_package_streaming.package_streaming.UMASK", MOCK_UMASK
199 )
200 os.umask(MOCK_UMASK)
201
202 root_path = tmp_path / "cps"
203 root_path.mkdir()
204 files_to_check = [root_path / name, root_path / name / name]
205
206 tar3.seek(0)
207 extract.extract_stream(stream(tar3), root_path, tar_filter=tar_filter)
208 for file in files_to_check:
209 mode = file.stat().st_mode
210 if mode & stat_check:
211 assert not (mode & stat_check), (
212 f"{file}: No {stat_name} due to umask? %o != %o"
213 % (
214 mode,
215 mode & stat_check,
216 )
217 )
218 finally:
219 os.umask(current_umask)
220
221
222 def test_encoding():
223 """
224 Some users do not have "utf-8" as the default sys.getfilesystemencoding() or
225 sys.getdefaultencoding(). Instead of trying to change the system encoding,
226 we prove that stream_conda_component honors the new passed-in encoding which
227 is now "utf-8" by default.
228 """
229
230 tar = not_unicode_tarbz2()
231
232 # Use new default encoding of "utf-8" regardless of what the system says.
233 stream = package_streaming.stream_conda_component(
234 "package.tar.bz2", tar, component="pkg"
235 )
236
237 with pytest.raises(UnicodeEncodeError):
238 for t, member in stream:
239 member.name.encode("utf-8")
240 print(t, member)
241
242 tar.seek(0)
243
244 # Prove that we are passing encoding all the way down to the TarFile() used
245 # for extraction.
246 stream = package_streaming.stream_conda_component(
247 "package.tar.bz2", tar, component="pkg", encoding="latin-1"
248 )
249
250 for t, member in stream:
251 member.name.encode("utf-8")
252 print(t, member)