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
|
# Copyright 2012-2014 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 os
import glob
import json
import pprint
import logging
import difflib
from tests import create_session
import botocore.session
from botocore import xform_name
from botocore import parsers
log = logging.getLogger(__name__)
SPECIAL_CASES = [
'iam-get-user-policy.xml', # Needs the JSON decode from handlers.py
'iam-list-roles.xml', # Needs the JSON decode from handlers.py for the policy
's3-get-bucket-location.xml', # Confirmed, this will need a special handler
#'s3-list-multipart-uploads.xml', # Bug in model, missing delimeter
'cloudformation-get-template.xml', # Need to JSON decode the template body.
]
def _test_parsed_response(xmlfile, response_body, operation_model, expected):
response = {
'body': response_body,
'status_code': 200,
'headers': {}
}
for case in SPECIAL_CASES:
if case in xmlfile:
print("SKIP: %s" % xmlfile)
return
if 'errors' in xmlfile:
response['status_code'] = 400
# Handle the special cased __headers__ key if it exists.
if b'__headers__' in response_body:
loaded = json.loads(response_body.decode('utf-8'))
response['headers'] = loaded.pop('__headers__')
response['body'] = json.dumps(loaded).encode('utf-8')
protocol = operation_model.service_model.protocol
parser_cls = parsers.PROTOCOL_PARSERS[protocol]
parser = parser_cls(timestamp_parser=lambda x: x)
parsed = parser.parse(response, operation_model.output_shape)
parsed = _convert_bytes_to_str(parsed)
expected['ResponseMetadata']['HTTPStatusCode'] = response['status_code']
expected['ResponseMetadata']['HTTPHeaders'] = response['headers']
d2 = parsed
d1 = expected
if d1 != d2:
log.debug('-' * 40)
log.debug("XML FILE:\n" + xmlfile)
log.debug('-' * 40)
log.debug("ACTUAL:\n" + pprint.pformat(parsed))
log.debug('-' * 40)
log.debug("EXPECTED:\n" + pprint.pformat(expected))
if not d1 == d2:
# Borrowed from assertDictEqual, though this doesn't
# handle the case when unicode literals are used in one
# dict but not in the other (and we want to consider them
# as being equal).
print(d1)
print()
print(d2)
pretty_d1 = pprint.pformat(d1, width=1).splitlines()
pretty_d2 = pprint.pformat(d2, width=1).splitlines()
diff = ('\n' + '\n'.join(difflib.ndiff(pretty_d1, pretty_d2)))
raise AssertionError("Dicts are not equal:\n%s" % diff)
def _convert_bytes_to_str(parsed):
if isinstance(parsed, dict):
new_dict = {}
for key, value in parsed.items():
new_dict[key] = _convert_bytes_to_str(value)
return new_dict
elif isinstance(parsed, bytes):
return parsed.decode('utf-8')
elif isinstance(parsed, list):
new_list = []
for item in parsed:
new_list.append(_convert_bytes_to_str(item))
return new_list
else:
return parsed
def test_xml_parsing():
for dp in ['responses', 'errors']:
data_path = os.path.join(os.path.dirname(__file__), 'xml')
data_path = os.path.join(data_path, dp)
session = create_session()
xml_files = glob.glob('%s/*.xml' % data_path)
service_names = set()
for fn in xml_files:
service_names.add(os.path.split(fn)[1].split('-')[0])
for service_name in service_names:
service_model = session.get_service_model(service_name)
service_xml_files = glob.glob('%s/%s-*.xml' % (data_path,
service_name))
for xmlfile in service_xml_files:
expected = _get_expected_parsed_result(xmlfile)
operation_model = _get_operation_model(service_model, xmlfile)
raw_response_body = _get_raw_response_body(xmlfile)
yield _test_parsed_response, xmlfile, raw_response_body, \
operation_model, expected
def _get_raw_response_body(xmlfile):
with open(xmlfile, 'rb') as f:
return f.read()
def _get_operation_model(service_model, filename):
dirname, filename = os.path.split(filename)
basename = os.path.splitext(filename)[0]
sn, opname = basename.split('-', 1)
# In order to have multiple tests for the same
# operation a '#' char is used to separate
# operation names from some other suffix so that
# the tests have a different filename, e.g
# my-operation#1.xml, my-operation#2.xml.
opname = opname.split('#')[0]
operation_names = service_model.operation_names
for operation_name in operation_names:
if xform_name(operation_name) == opname.replace('-', '_'):
return service_model.operation_model(operation_name)
return operation
def _get_expected_parsed_result(filename):
dirname, filename = os.path.split(filename)
basename = os.path.splitext(filename)[0]
jsonfile = os.path.join(dirname, basename + '.json')
with open(jsonfile) as f:
return json.load(f)
def test_json_errors_parsing():
# The outputs/ directory has sample output responses
# For each file in outputs/ there's a corresponding file
# in expected/ that has the expected parsed response.
base_dir = os.path.join(os.path.dirname(__file__), 'json')
json_responses_dir = os.path.join(base_dir, 'errors')
expected_parsed_dir = os.path.join(base_dir, 'expected')
session = botocore.session.get_session()
for json_response_file in os.listdir(json_responses_dir):
# Files look like: 'datapipeline-create-pipeline.json'
service_name, operation_name = os.path.splitext(
json_response_file)[0].split('-', 1)
expected_parsed_response = os.path.join(expected_parsed_dir,
json_response_file)
raw_response_file = os.path.join(json_responses_dir,
json_response_file)
with open(expected_parsed_response) as f:
expected = json.load(f)
service_model = session.get_service_model(service_name)
operation_names = service_model.operation_names
operation_model = None
for op_name in operation_names:
if xform_name(op_name) == operation_name.replace('-', '_'):
operation_model = service_model.operation_model(op_name)
with open(raw_response_file, 'rb') as f:
raw_response_body = f.read()
yield _test_parsed_response, raw_response_file, \
raw_response_body, operation_model, expected
def _uhg_test_json_parsing():
input_path = os.path.join(os.path.dirname(__file__), 'json')
input_path = os.path.join(input_path, 'inputs')
output_path = os.path.join(os.path.dirname(__file__), 'json')
output_path = os.path.join(output_path, 'outputs')
session = botocore.session.get_session()
jsonfiles = glob.glob('%s/*.json' % input_path)
service_names = set()
for fn in jsonfiles:
service_names.add(os.path.split(fn)[1].split('-')[0])
for service_name in service_names:
service_model = session.get_service_model(service_name)
service_json_files = glob.glob('%s/%s-*.json' % (input_path,
service_name))
for jsonfile in service_json_files:
expected = _get_expected_parsed_result(jsonfile)
operation_model = _get_operation_model(service_model, jsonfile)
with open(jsonfile, 'rb') as f:
raw_response_body = f.read()
yield _test_parsed_response, jsonfile, \
raw_response_body, operation_model, expected
# TODO: handle the __headers crap.
#class TestHeaderParsing(unittest.TestCase):
#
# maxDiff = None
#
# def setUp(self):
# self.session = botocore.session.get_session()
# self.s3 = self.session.get_service('s3')
#
# def test_put_object(self):
# http_response = Mock()
# http_response.encoding = 'utf-8'
# http_response.headers = CaseInsensitiveDict(
# {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT',
# 'Content-Length': '0',
# 'x-amz-request-id': '2B74ECB010FF029E',
# 'ETag': '"b081e66e7e0c314285c655cafb4d1e71"',
# 'x-amz-id-2': 'bKECRRBFttBRVbJPIVBLQwwipI0i+s9HMvNFdttR17ouR0pvQSKEJUR+1c6cW1nQ',
# 'Server': 'AmazonS3',
# 'content-type': 'text/xml'})
# http_response.content = ''
# put_object = self.s3.get_operation('PutObject')
# expected = {"ETag": '"b081e66e7e0c314285c655cafb4d1e71"'}
# response_data = get_response(self.session, put_object, http_response)[1]
# self.assertEqual(response_data, expected)
#
# def test_head_object(self):
# http_response = Mock()
# http_response.encoding = 'utf-8'
# http_response.headers = CaseInsensitiveDict(
# {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT',
# 'Content-Length': '265',
# 'x-amz-request-id': '2B74ECB010FF029E',
# 'ETag': '"40d06eb6194712ac1c915783004ef730"',
# 'Server': 'AmazonS3',
# 'content-type': 'binary/octet-stream',
# 'Content-Type': 'binary/octet-stream',
# 'accept-ranges': 'bytes',
# 'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT',
# 'x-amz-server-side-encryption': 'AES256',
# 'x-amz-meta-mykey1': 'value1',
# 'x-amz-meta-mykey2': 'value2',
# })
# http_response.content = ''
# http_response.request.method = 'HEAD'
# put_object = self.s3.get_operation('HeadObject')
# expected = {"AcceptRanges": "bytes",
# "ContentType": "binary/octet-stream",
# "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
# "ContentLength": "265",
# "ETag": '"40d06eb6194712ac1c915783004ef730"',
# "ServerSideEncryption": "AES256",
# "Metadata": {
# 'mykey1': 'value1',
# 'mykey2': 'value2',
# }}
# response_data = get_response(self.session, put_object,
# http_response)[1]
# self.assertEqual(response_data, expected)
#
# def test_list_objects_with_invalid_content_length(self):
# http_response = Mock()
# http_response.encoding = 'utf-8'
# http_response.headers = CaseInsensitiveDict(
# {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT',
# # We say we have 265 bytes but we're returning 0,
# # this should raise an exception because this is not
# # a HEAD request.
# 'Content-Length': '265',
# 'x-amz-request-id': '2B74ECB010FF029E',
# 'ETag': '"40d06eb6194712ac1c915783004ef730"',
# 'Server': 'AmazonS3',
# 'content-type': 'binary/octet-stream',
# 'Content-Type': 'binary/octet-stream',
# 'accept-ranges': 'bytes',
# 'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT',
# 'x-amz-server-side-encryption': 'AES256'
# })
# http_response.content = ''
# http_response.request.method = 'GET'
# list_objects = self.s3.get_operation('ListObjects')
# expected = {"AcceptRanges": "bytes",
# "ContentType": "binary/octet-stream",
# "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
# "ContentLength": "265",
# "ETag": '"40d06eb6194712ac1c915783004ef730"',
# "ServerSideEncryption": "AES256"
# }
# with self.assertRaises(IncompleteReadError):
# response_data = get_response(self.session, list_objects,
# http_response)[1]
#
# def test_head_object_with_json(self):
# http_response = Mock()
# http_response.encoding = 'utf-8'
# http_response.headers = CaseInsensitiveDict(
# {'Date': 'Thu, 22 Aug 2013 02:11:57 GMT',
# 'Content-Length': '0',
# 'x-amz-request-id': '2B74ECB010FF029E',
# 'ETag': '"40d06eb6194712ac1c915783004ef730"',
# 'Server': 'AmazonS3',
# 'content-type': 'application/json',
# 'Content-Type': 'application/json',
# 'accept-ranges': 'bytes',
# 'Last-Modified': 'Tue, 20 Aug 2013 18:33:25 GMT',
# 'x-amz-server-side-encryption': 'AES256'})
# http_response.content = ''
# put_object = self.s3.get_operation('HeadObject')
# expected = {"AcceptRanges": "bytes",
# "ContentType": "application/json",
# "LastModified": "Tue, 20 Aug 2013 18:33:25 GMT",
# "ContentLength": "0",
# "ETag": '"40d06eb6194712ac1c915783004ef730"',
# "ServerSideEncryption": "AES256"
# }
# response_data = get_response(self.session, put_object,
# http_response)[1]
# self.assertEqual(response_data, expected)
|