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
|
# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import gzip
import io
import sys
import pytest
import botocore
from botocore.compress import COMPRESSION_MAPPING, maybe_compress_request
from botocore.config import Config
from tests import mock
def _make_op(
request_compression=None,
has_streaming_input=False,
streaming_metadata=None,
):
op = mock.Mock()
op.request_compression = request_compression
op.has_streaming_input = has_streaming_input
if streaming_metadata is not None:
streaming_shape = mock.Mock()
streaming_shape.metadata = streaming_metadata
op.get_streaming_input.return_value = streaming_shape
return op
OP_NO_COMPRESSION = _make_op()
OP_WITH_COMPRESSION = _make_op({'encodings': ['gzip']})
OP_UNKNOWN_COMPRESSION = _make_op({'encodings': ['foo']})
OP_MULTIPLE_COMPRESSIONS = _make_op({'encodings': ['gzip', 'foo']})
STREAMING_OP_WITH_COMPRESSION = _make_op(
{'encodings': ['gzip']},
True,
{},
)
STREAMING_OP_WITH_COMPRESSION_REQUIRES_LENGTH = _make_op(
{'encodings': ['gzip']},
True,
{'requiresLength': True},
)
REQUEST_BODY = (
b'Action=PutMetricData&Version=2010-08-01&Namespace=Namespace'
b'&MetricData.member.1.MetricName=metric&MetricData.member.1.Unit=Bytes'
b'&MetricData.member.1.Value=128'
)
REQUEST_BODY_COMPRESSED = (
b'\x1f\x8b\x08\x00\x01\x00\x00\x00\x02\xffsL.\xc9\xcc\xcf\xb3\r(-\xf1M-)'
b'\xcaLvI,IT\x0bK-*\x06\x89\x1a\x19\x18\x1a\xe8\x1aX\xe8\x1a\x18\xaa\xf9%'
b'\xe6\xa6\x16\x17$&\xa7\xda\xc2Yj\x08\x1dz\xb9\xa9\xb9I\xa9Ez\x86z\x101\x90'
b'\x1a\xdb\\0\x13\xab\xaa\xd0\xbc\xcc\x12[\xa7\xca\x92\xd4b\xac\xd2a\x899\xa5'
b'\xa9\xb6\x86F\x16\x00\x1e\xdd\t\xfd\x9e\x00\x00\x00'
)
COMPRESSION_CONFIG_128_BYTES = Config(
disable_request_compression=False,
request_min_compression_size_bytes=128,
)
COMPRESSION_CONFIG_1_BYTE = Config(
disable_request_compression=False,
request_min_compression_size_bytes=1,
)
class NonSeekableStream:
def __init__(self, buffer):
self._buffer = buffer
def read(self, size=None):
return self._buffer.read(size)
def _request_dict(body=REQUEST_BODY, headers=None):
if headers is None:
headers = {}
return {
'body': body,
'headers': headers,
}
def request_dict_non_seekable_text_stream():
stream = NonSeekableStream(io.StringIO(REQUEST_BODY.decode('utf-8')))
return _request_dict(stream)
def request_dict_non_seekable_bytes_stream():
return _request_dict(NonSeekableStream(io.BytesIO(REQUEST_BODY)))
class StaticGzipFile(gzip.GzipFile):
def __init__(self, *args, **kwargs):
kwargs['mtime'] = 1
super().__init__(*args, **kwargs)
def static_compress(*args, **kwargs):
kwargs['mtime'] = 1
return gzip.compress(*args, **kwargs)
def _bad_compression(body):
raise ValueError('Reached unintended compression algorithm "foo"')
MOCK_COMPRESSION = {'foo': _bad_compression}
MOCK_COMPRESSION.update(COMPRESSION_MAPPING)
def _assert_compression_body(compressed_body, expected_body):
data = compressed_body
if hasattr(compressed_body, 'read'):
data = compressed_body.read()
assert data == expected_body
def _assert_compression_header(headers, encoding='gzip'):
assert 'Content-Encoding' in headers
assert encoding in headers['Content-Encoding']
def assert_request_compressed(request_dict, expected_body):
_assert_compression_body(request_dict['body'], expected_body)
_assert_compression_header(request_dict['headers'])
@pytest.mark.parametrize(
'request_dict, operation_model',
[
(
_request_dict(),
OP_WITH_COMPRESSION,
),
(
_request_dict(),
OP_MULTIPLE_COMPRESSIONS,
),
(
_request_dict(),
STREAMING_OP_WITH_COMPRESSION,
),
(
_request_dict(bytearray(REQUEST_BODY)),
OP_WITH_COMPRESSION,
),
(
_request_dict(headers={'Content-Encoding': 'identity'}),
OP_WITH_COMPRESSION,
),
(
_request_dict(REQUEST_BODY.decode('utf-8')),
OP_WITH_COMPRESSION,
),
(
_request_dict(io.BytesIO(REQUEST_BODY)),
OP_WITH_COMPRESSION,
),
(
_request_dict(io.StringIO(REQUEST_BODY.decode('utf-8'))),
OP_WITH_COMPRESSION,
),
(
request_dict_non_seekable_bytes_stream(),
STREAMING_OP_WITH_COMPRESSION,
),
(
request_dict_non_seekable_text_stream(),
STREAMING_OP_WITH_COMPRESSION,
),
],
)
@mock.patch.object(botocore.compress, 'GzipFile', StaticGzipFile)
@mock.patch.object(botocore.compress, 'gzip_compress', static_compress)
@pytest.mark.skipif(
sys.version_info < (3, 8), reason='requires python3.8 or higher'
)
def test_compression(request_dict, operation_model):
maybe_compress_request(
COMPRESSION_CONFIG_128_BYTES, request_dict, operation_model
)
assert_request_compressed(request_dict, REQUEST_BODY_COMPRESSED)
@pytest.mark.parametrize(
'config, request_dict, operation_model',
[
(
Config(
disable_request_compression=True,
request_min_compression_size_bytes=1,
),
_request_dict(),
OP_WITH_COMPRESSION,
),
(
Config(
disable_request_compression=False,
request_min_compression_size_bytes=256,
),
_request_dict(),
OP_WITH_COMPRESSION,
),
(
Config(
disable_request_compression=False,
request_min_compression_size_bytes=1,
signature_version='v2',
),
_request_dict(),
OP_WITH_COMPRESSION,
),
(
COMPRESSION_CONFIG_128_BYTES,
_request_dict(),
STREAMING_OP_WITH_COMPRESSION_REQUIRES_LENGTH,
),
(
COMPRESSION_CONFIG_128_BYTES,
_request_dict(),
OP_NO_COMPRESSION,
),
(
COMPRESSION_CONFIG_128_BYTES,
_request_dict(),
OP_UNKNOWN_COMPRESSION,
),
(
COMPRESSION_CONFIG_128_BYTES,
_request_dict(headers={'Content-Encoding': 'identity'}),
OP_UNKNOWN_COMPRESSION,
),
(
COMPRESSION_CONFIG_128_BYTES,
request_dict_non_seekable_bytes_stream(),
OP_WITH_COMPRESSION,
),
],
)
def test_no_compression(config, request_dict, operation_model):
ce_header = request_dict['headers'].get('Content-Encoding')
original_body = request_dict['body']
maybe_compress_request(config, request_dict, operation_model)
assert request_dict['body'] == original_body
assert ce_header == request_dict['headers'].get('Content-Encoding')
@pytest.mark.parametrize(
'operation_model, expected_body',
[
(
OP_WITH_COMPRESSION,
(
b'\x1f\x8b\x08\x00\x01\x00\x00\x00\x02\xffK\xcb'
b'\xcf\xb7MJ,\x02\x00v\x8e5\x1c\x07\x00\x00\x00'
),
),
(OP_NO_COMPRESSION, {'foo': 'bar'}),
],
)
@mock.patch.object(botocore.compress, 'gzip_compress', static_compress)
@pytest.mark.skipif(
sys.version_info < (3, 8), reason='requires python3.8 or higher'
)
def test_dict_compression(operation_model, expected_body):
request_dict = _request_dict({'foo': 'bar'})
maybe_compress_request(
COMPRESSION_CONFIG_1_BYTE, request_dict, operation_model
)
body = request_dict['body']
assert body == expected_body
@pytest.mark.parametrize('body', [1, object(), True, 1.0])
def test_maybe_compress_bad_types(body):
request_dict = _request_dict(body)
maybe_compress_request(
COMPRESSION_CONFIG_1_BYTE, request_dict, OP_WITH_COMPRESSION
)
assert request_dict['body'] == body
@mock.patch.object(botocore.compress, 'GzipFile', StaticGzipFile)
def test_body_streams_position_reset():
request_dict = _request_dict(io.BytesIO(REQUEST_BODY))
maybe_compress_request(
COMPRESSION_CONFIG_128_BYTES,
request_dict,
OP_WITH_COMPRESSION,
)
assert request_dict['body'].tell() == 0
assert_request_compressed(request_dict, REQUEST_BODY_COMPRESSED)
@mock.patch.object(botocore.compress, 'gzip_compress', static_compress)
@mock.patch.object(botocore.compress, 'COMPRESSION_MAPPING', MOCK_COMPRESSION)
@pytest.mark.skipif(
sys.version_info < (3, 8), reason='requires python3.8 or higher'
)
def test_only_compress_once():
request_dict = _request_dict()
maybe_compress_request(
COMPRESSION_CONFIG_128_BYTES,
request_dict,
OP_MULTIPLE_COMPRESSIONS,
)
assert_request_compressed(request_dict, REQUEST_BODY_COMPRESSED)
|