Debian Codegraph @

tests/test_encoding.py

raw
1 import pytest
2
3 import httplib2
4 from httplib2.decode import LimitDecoder, ZlibDecoder, DecodeLimitError, DecodeRatioError
5 import tests
6
7
8 def test_gzip_head():
9 # Test that we don't try to decompress a HEAD response
10 http = httplib2.Http()
11 response = tests.http_response_bytes(headers={"content-encoding": "gzip", "content-length": 42})
12 with tests.server_const_bytes(response) as uri:
13 response, content = http.request(uri, "HEAD")
14 assert response.status == 200
15 assert int(response["content-length"]) != 0
16 assert content == b""
17
18
19 def test_gzip_get():
20 # Test that we support gzip compression
21 http = httplib2.Http()
22 response = tests.http_response_bytes(
23 headers={"content-encoding": "gzip"},
24 body=tests.gzip_compress(b"properly compressed"),
25 )
26 with tests.server_const_bytes(response) as uri:
27 response, content = http.request(uri, "GET")
28 assert response.status == 200
29 assert "content-encoding" not in response
30 assert "-content-encoding" in response
31 assert int(response["content-length"]) == len(b"properly compressed")
32 assert content == b"properly compressed"
33
34
35 def test_gzip_post_response():
36 http = httplib2.Http()
37 response = tests.http_response_bytes(
38 headers={"content-encoding": "gzip"},
39 body=tests.gzip_compress(b"properly compressed"),
40 )
41 with tests.server_const_bytes(response) as uri:
42 response, content = http.request(uri, "POST", body=b"")
43 assert response.status == 200
44 assert "content-encoding" not in response
45 assert "-content-encoding" in response
46
47
48 def test_gzip_malformed_response():
49 http = httplib2.Http()
50 # Test that we raise a good exception when the gzip fails
51 http.force_exception_to_status_code = False
52 response = tests.http_response_bytes(headers={"content-encoding": "gzip"}, body=b"obviously not compressed")
53 with tests.server_const_bytes(response, request_count=2) as uri:
54 with tests.assert_raises(httplib2.FailedToDecompressContent):
55 http.request(uri, "GET")
56
57 # Re-run the test with out the exceptions
58 http.force_exception_to_status_code = True
59
60 response, content = http.request(uri, "GET")
61 assert response.status == 500
62 assert response.reason.startswith("Content purported")
63
64
65 def test_deflate_get():
66 # Test that we support deflate compression
67 http = httplib2.Http()
68 response = tests.http_response_bytes(
69 headers={"content-encoding": "deflate"},
70 body=tests.deflate_compress(b"properly compressed"),
71 )
72 with tests.server_const_bytes(response) as uri:
73 response, content = http.request(uri, "GET")
74 assert response.status == 200
75 assert "content-encoding" not in response
76 assert int(response["content-length"]) == len(b"properly compressed")
77 assert content == b"properly compressed"
78
79
80 def test_deflate_malformed_response():
81 # Test that we raise a good exception when the deflate fails
82 http = httplib2.Http()
83 http.force_exception_to_status_code = False
84 response = tests.http_response_bytes(headers={"content-encoding": "deflate"}, body=b"obviously not compressed")
85 with tests.server_const_bytes(response, request_count=2) as uri:
86 with tests.assert_raises(httplib2.FailedToDecompressContent):
87 http.request(uri, "GET")
88
89 # Re-run the test with out the exceptions
90 http.force_exception_to_status_code = True
91
92 response, content = http.request(uri, "GET")
93 assert response.status == 500
94 assert response.reason.startswith("Content purported")
95
96
97 def test_zlib_get():
98 # Test that we support zlib compression
99 http = httplib2.Http()
100 response = tests.http_response_bytes(
101 headers={"content-encoding": "deflate"},
102 body=tests.zlib_compress(b"properly compressed"),
103 )
104 with tests.server_const_bytes(response) as uri:
105 response, content = http.request(uri, "GET")
106 assert response.status == 200
107 assert "content-encoding" not in response
108 assert int(response["content-length"]) == len(b"properly compressed")
109 assert content == b"properly compressed"
110
111
112 def test_gzip_excess_ratio():
113 http = httplib2.Http()
114 original = b"\x00" * (50 << 20) # 50 MiB to ~50 KiB
115 response = tests.http_response_bytes(
116 headers={"content-encoding": "gzip"},
117 body=tests.gzip_compress(original),
118 )
119 with tests.server_const_bytes(response) as uri:
120 try:
121 http.request(uri, "GET")
122 assert False, "expected DecodeRatioError"
123 except DecodeRatioError:
124 pass
125
126
127 @pytest.mark.parametrize("safe_limit", (0, 1000, 20000))
128 def test_limitdecoder_normal_decompression_no_limits(safe_limit):
129 """Standard decompression of random data should pass with any safe_limit"""
130 original = tests.randbytes(10 << 10)
131 compressed = tests.zlib_compress(original)
132
133 decoder = LimitDecoder(
134 ZlibDecoder(),
135 ratio=10,
136 safe_limit=safe_limit,
137 hard_limit=len(original) + 1,
138 )
139 result = decoder.consume_bytes(compressed)
140 assert result == original
141 assert decoder._output_length == len(original)
142
143
144 def test_limitdecoder_normal_rechunking():
145 """Passing a massive single chunk should be re-chunked internally without error"""
146 original = b"\x00" * (10 << 20)
147 compressed = tests.zlib_compress(original)
148 assert len(compressed) > 2000
149
150 decoder = LimitDecoder(
151 ZlibDecoder(),
152 ratio=2000,
153 chunk_size=512,
154 safe_limit=0,
155 hard_limit=len(original) + 1,
156 )
157 result = decoder.consume_bytes(compressed, chunk_size=0)
158 assert result == original
159 assert decoder._consumed_length == len(compressed)
160
161
162 def test_limitdecoder_amplification_ratio_exceeded():
163 """High ratio should trigger DecodeRatioError above safe_limit"""
164 original = b"\x00" * (1 << 20)
165 compressed = tests.zlib_compress(original)
166
167 decoder = LimitDecoder(
168 ZlibDecoder(),
169 ratio=10,
170 chunk_size=512,
171 safe_limit=0,
172 hard_limit=len(original) + 1,
173 )
174 try:
175 decoder.consume_bytes(compressed, chunk_size=0)
176 assert False, "expected DecodeRatioError"
177 except DecodeRatioError:
178 pass
179 assert decoder._consumed_length == 512, "expected ratio error on first chunk"
180
181
182 @pytest.mark.parametrize("ratio", (0, 10, 1000))
183 def test_limitdecoder_hard_limit_exceeded(ratio):
184 """Output exceeding hard_limit must trigger DecodeLimitError regardless of ratio"""
185 original = b"\x00" * (10 << 10)
186 compressed = tests.zlib_compress(original)
187
188 decoder = LimitDecoder(
189 ZlibDecoder(),
190 ratio=ratio,
191 safe_limit=0,
192 hard_limit=len(original) - 1,
193 )
194 try:
195 decoder.consume_bytes(compressed)
196 assert False, "expected DecodeLimitError"
197 except DecodeLimitError:
198 pass
199
200
201 @pytest.mark.parametrize("ratio", (0, 10, 1000))
202 def test_limitdecoder_safe_limit_bypass(ratio):
203 """Any ratio allowed if total output < safe_limit"""
204 original = b"\x00" * (10 << 10)
205 compressed = tests.zlib_compress(original)
206
207 decoder = LimitDecoder(
208 ZlibDecoder(),
209 ratio=ratio,
210 safe_limit=len(original) + 1,
211 hard_limit=len(original) + 1,
212 )
213 result = decoder.consume_bytes(compressed)
214 assert result == original
215 assert decoder._output_length == len(original)
216
217
218 def test_limitdecoder_single_byte_feeding():
219 """Feeding compressed data 1 byte at a time should still decode correctly"""
220 original = tests.randbytes(10 << 10)
221 compressed = tests.zlib_compress(original)
222
223 decoder = LimitDecoder(
224 ZlibDecoder(),
225 ratio=10,
226 safe_limit=5 << 10,
227 hard_limit=len(original) + 1,
228 )
229 result = decoder.consume_bytes(compressed, chunk_size=1)
230 assert result == original
231
232
233 def test_limitdecoder_invalid_argument():
234 checks = (
235 ("ratio", dict(ratio=-1)),
236 ("chunk_size", dict(chunk_size=-1)),
237 ("safe_limit", dict(safe_limit=-1)),
238 ("hard_limit", dict(hard_limit=-1)),
239 )
240 for name, check in checks:
241 zd = ZlibDecoder()
242 try:
243 LimitDecoder(zd, **check)
244 assert False, f"check={name} expected ValueError"
245 except ValueError as e:
246 assert "expected >= 0" in str(e).lower(), str(e)
247
248
249 def test_zlibdecoder_invalid_after_flush():
250 checks = (
251 ("needs_input", lambda d: d.needs_input),
252 ("decode", lambda d: d.decode(b"")),
253 ("flush", lambda d: d.flush()),
254 )
255 for name, check in checks:
256 d = ZlibDecoder()
257 d.decode(tests.zlib_compress(b""))
258 d.flush()
259 try:
260 check(d)
261 assert False, f"check={name} expected RuntimeError"
262 except RuntimeError as e:
263 assert "used after flush" in str(e).lower(), str(e)