def transmute_to_and_from_with_excluded_items(self): class MixedMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int), 'another': Attr('another', int, serialize=False) } mapping = MixedMappedModel() mapping.test = 1 mapping.another = 2 without_result = '{"test": 1}' result_without = JsonTransmuter.transmute_to(mapping) expect(result_without).to.equal(without_result) # Make sure we can override the serialization preferences result_with = JsonTransmuter.transmute_to(mapping, to_string=False, serialize_all=True) expect(result_with.get('test')).to.equal(1) expect(result_with.get('another')).to.equal(2) result = JsonTransmuter.transmute_from({ 'test': 100, 'another': 200 }, MixedMappedModel) expect(result.test).to.equal(100) expect(result.another).to.equal(200)
def transmute_to_and_from_with_excluded_items(self): class MixedMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int), 'another': Attr('another', int, serialize=False) } mapping = MixedMappedModel() mapping.test = 1 mapping.another = 2 without_result = '{"test": 1}' result_without = JsonTransmuter.transmute_to(mapping) expect(result_without).to.equal(without_result) # Make sure we can override the serialization preferences result_with = JsonTransmuter.transmute_to( mapping, to_string=False, serialize_all=True ) expect(result_with.get('test')).to.equal(1) expect(result_with.get('another')).to.equal(2) result = JsonTransmuter.transmute_from( {'test': 100, 'another': 200}, MixedMappedModel ) expect(result.test).to.equal(100) expect(result.another).to.equal(200)
def save_config_data(self, data, handler, cfg): import boto3 region = self.vars['PARAMETER_STORE_AWS_REGION'] prefix = self.vars['PARAMETER_STORE_PREFIX'] access_id = self.vars.get('PARAMETER_STORE_AWS_ACCESS_ID') access_secret = self.vars.get('PARAMETER_STORE_AWS_ACCESS_SECRET') key_id = self.vars.get('PARAMETER_STORE_AWS_KMS_KEY_ID') params = self.dict_to_params(data, prefix, cfg, []) ssm = boto3.client('ssm', region_name=region, aws_access_key_id=access_id, aws_secret_access_key=access_secret) for param in params: param.key_id = key_id # Because Boto3... req_kwargs = JsonTransmuter.transmute_to(param, to_string=False, coerce_values=False) ssm.put_parameter(**req_kwargs)
def transmute_to_and_from_supports_enums(self): import enum class TestEnum(enum.Enum): RED = 1 GREEN = 2 BLUE = 3 class OtherEnum(enum.Enum): BLUE = 1 GREEN = 2 RED = 3 class EnumMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', TestEnum), 'other': Attr('other', OtherEnum), } mapping = EnumMappedModel() mapping.test = TestEnum.RED mapping.other = OtherEnum.RED serialized = '{"test": 1, "other": 3}' result = JsonTransmuter.transmute_to(mapping) res_dict = json.loads(result) expect(res_dict.get('test')).to.equal(1) expect(res_dict.get('other')).to.equal(3) result = JsonTransmuter.transmute_from(serialized, EnumMappedModel) expect(result.test).to.equal(TestEnum.RED) expect(result.other).to.equal(OtherEnum.RED)
def transmute_to_with_different_attr_naming(self): model = TestDifferentAttrNaming() model.my_thing = 'something' result = JsonTransmuter.transmute_to(model, to_string=False) expect(result['my-thing']).to.equal('something')
def transmute_to_with_empty_submodel(self): model = TestChildMapping() model.child = None result = JsonTransmuter.transmute_to(model, to_string=False) expect(result.get('child')).to.be_none()
def transmute_to_and_from_with_unknown_type(self): class CustomType(object): def __init__(self, something): self.something = something class TestMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', CustomType), } model = TestMappedModel() model.test = CustomType('thing') serialized = '{}' result = JsonTransmuter.transmute_to(model) expect(result).to.equal(serialized) result = JsonTransmuter.transmute_from( '{"test": {"something": "thing"}}', TestMappedModel ) attr = getattr(result, 'test', None) expect(attr).to.be_none()
def transmute_to_and_from_with_custom_serializer(self): mapping = TestWrappedModel() mapping.test = "bam" json_str = '{"#item": {"test": "bam"}}' class Custom(object): @classmethod def dumps(cls, value): value['#item']['test'] = 'allthethings' return json.dumps(value) @classmethod def loads(cls, value): loaded = json.loads(json_str) loaded['#item']['test'] = 'magic' return loaded result = JsonTransmuter.transmute_to(mapping, encoder=Custom) expect(result).to.equal('{"#item": {"test": "allthethings"}}') result = JsonTransmuter.transmute_from(json_str, TestWrappedModel, decoder=Custom) expect(result.test).to.equal('magic')
def transmute_to_and_from_with_expanded_type(self): class CustomType(object): def __init__(self, something): self.something = something class CustomDefinition(ExpandedType): cls = CustomType @classmethod def serialize(self, value): return {'something': value.something} @classmethod def deserialize(self, attr_type, value): return attr_type(**value) class TestMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', CustomType), } model = TestMappedModel() model.test = CustomType('thing') serialized = '{"test": {"something": "thing"}}' alchemize.register_type(CustomDefinition) result = JsonTransmuter.transmute_to(model) expect(result).to.equal(serialized) result = JsonTransmuter.transmute_from(serialized, TestMappedModel) expect(result.test.something).to.equal('thing') alchemize.remove_type(CustomDefinition)
def transmute_to_and_from_with_custom_serializer(self): mapping = TestWrappedModel() mapping.test = "bam" json_str = '{"#item": {"test": "bam"}}' class Custom(object): @classmethod def dumps(cls, value): value['#item']['test'] = 'allthethings' return json.dumps(value) @classmethod def loads(cls, value): loaded = json.loads(json_str) loaded['#item']['test'] = 'magic' return loaded result = JsonTransmuter.transmute_to( mapping, encoder=Custom ) expect(result).to.equal('{"#item": {"test": "allthethings"}}') result = JsonTransmuter.transmute_from( json_str, TestWrappedModel, decoder=Custom ) expect(result.test).to.equal('magic')
def transmute_to(self, to_string=False, serialize_all=False, coerce_values=False, **options): return JsonTransmuter.transmute_to( self, to_string=to_string, coerce_values=coerce_values, serialize_all=serialize_all, **options )
def pet_add(self, pet_obj: Pet) -> ApiResponse: response = post(f"{self.base_url}pet", headers=self.headers, data=JsonTransmuter.transmute_to(pet_obj)) return ApiResponse( response.status_code, ApiResponseType.ok if response.ok else ApiResponseType.error, JsonTransmuter.transmute_from(response.text, Pet) if response.ok else response.text)
def transmute_to_with_all_required_attrs(self): model = TestRequiredMappedModel() model.test = 1 model.other = 2 result = JsonTransmuter.transmute_to(model, to_string=False) expect(result['test']).to.equal(1) expect(result['other']).to.equal(2)
def store_place_order(self, order: Order) -> ApiResponse: response = post(f"{self.base_url}store/order", headers=self.headers, data=JsonTransmuter.transmute_to(order)) return ApiResponse( response.status_code, ApiResponseType.ok if response.ok else ApiResponseType.error, JsonTransmuter.transmute_from(response.text, Order) if response.ok else response.text)
def user_update(self, user_name: str, user: User) -> ApiResponse: response = put(f"{self.base_url}user/{user_name}", headers=self.headers, data=JsonTransmuter.transmute_to(user)) return ApiResponse( response.status_code, ApiResponseType.ok if response.ok else ApiResponseType.error, JsonTransmuter.transmute_from(response.text, User) if response.ok else response.text)
def transmute_to_with_null_value(self): mapping = TestMappedModel() mapping.test = None expected_result = '{"test": null}' result = JsonTransmuter.transmute_to(mapping, assign_all=True, coerce_values=False) expect(result).to.equal(expected_result)
def transmute_to(self, to_string=False, serialize_all=False, coerce_values=False, **options): return JsonTransmuter.transmute_to(self, to_string=to_string, coerce_values=coerce_values, serialize_all=serialize_all, **options)
def transmute_to_with_inherited_mapping(self): model = TestExtendedModel() model.test = 'sample' model.second = 'other' expected_result = json.loads('{"test": "sample", "second": "other"}') result = JsonTransmuter.transmute_to(model) result_dict = json.loads(result) expect(result_dict['test']).to.equal(expected_result['test']) expect(result_dict['second']).to.equal(expected_result['second'])
def transmute_to_with_list_of_child_mappings(self): child_mapping = TestMappedModel() child_mapping.test = 'sample stuff' mapping = TestListChildMapping() mapping.children = [child_mapping] expected_result = '{"children": [{"test": "sample stuff"}]}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def transmute_to_with_zero_int_value(self): class IntMappedModel(JsonMappedModel): __mapping__ = {'test': Attr('test', int)} mapping = IntMappedModel() mapping.test = 0 expected_result = '{"test": 0}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def transmute_to_with_child_mapping(self): child_mapping = TestMappedModel() child_mapping.test = 'sample stuff' mapping = TestChildMapping() mapping.child = child_mapping expected_result = '{"child": {"test": "sample stuff"}}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def transmute_attribute_with_type(self, attr_type, attr_data, attr_result): class FlexMapping(JsonMappedModel): __mapping__ = {'test': ['test', attr_type]} mapping = FlexMapping() mapping.test = attr_result result = JsonTransmuter.transmute_to(mapping) expected_result = '{{"test": {0}}}'.format(attr_data) expect(result).to.equal(expected_result)
def transmute_to_coercion_can_be_overriden_per_attr(self): class IntMappedModel(JsonMappedModel): __mapping__ = {'test': Attr('test', int, coerce=True)} mapping = IntMappedModel() mapping.test = '1' expected_result = '{"test": 1}' result = JsonTransmuter.transmute_to(mapping, coerce_values=False) expect(result).to.equal(expected_result)
def transmute_to_can_coerce_a_null_dict_value(self): class IntMappedModel(JsonMappedModel): __mapping__ = {'test': Attr('test', dict)} mapping = IntMappedModel() mapping.test = None expected_result = '{"test": {}}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def transmute_to_with_null_value(self): mapping = TestMappedModel() mapping.test = None expected_result = '{"test": null}' result = JsonTransmuter.transmute_to( mapping, assign_all=True, coerce_values=False ) expect(result).to.equal(expected_result)
def transmute_to_and_from_with_wrapped_attr_name(self): mapping = TestWrappedModel() mapping.test = "bam" json_str = '{"#item": {"test": "bam"}}' result = JsonTransmuter.transmute_to(mapping, assign_all=True, coerce_values=False) expect(result).to.equal(json_str) result = JsonTransmuter.transmute_from(json_str, TestWrappedModel) expect(result.test).to.equal("bam")
def transmute_to_coercion_can_be_overriden_per_attr(self): class IntMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int, coerce=True) } mapping = IntMappedModel() mapping.test = '1' expected_result = '{"test": 1}' result = JsonTransmuter.transmute_to(mapping, coerce_values=False) expect(result).to.equal(expected_result)
def transmute_attribute_with_type(self, attr_type, attr_data, attr_result): class FlexMapping(JsonMappedModel): __mapping__ = { 'test': ['test', attr_type] } mapping = FlexMapping() mapping.test = attr_result result = JsonTransmuter.transmute_to(mapping) expected_result = '{{"test": {0}}}'.format(attr_data) expect(result).to.equal(expected_result)
def transmute_to_with_zero_int_value(self): class IntMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int) } mapping = IntMappedModel() mapping.test = 0 expected_result = '{"test": 0}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def transmute_to_can_coerce_a_null_dict_value(self): class IntMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', dict) } mapping = IntMappedModel() mapping.test = None expected_result = '{"test": {}}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def wrapper(data_model): result_model = JsonTransmuter.transmute_to(data_model) req_body = result_model res = requests.put(self.url, headers={ "Content-Type": "application/json", "accept": "application/json" }, data=req_body) if res.status_code == 200: return res.json() else: return None
def transmute_to_coerce_decimal_to_int(self): import decimal class IntMappedModel(JsonMappedModel): __mapping__ = {'test': Attr('test', int)} mapping = IntMappedModel() mapping.test = decimal.Decimal(10) expected_result = '{"test": 10}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def transmute_to_coerce_decimal_to_int(self): import decimal class IntMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int) } mapping = IntMappedModel() mapping.test = decimal.Decimal(10) expected_result = '{"test": 10}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result)
def transmute_to_with_old_attr_style(self): class OldStyleMappedModel(JsonMappedModel): __mapping__ = {'test': ['test', int]} mapping = OldStyleMappedModel() mapping.test = 0 expected_result = '{"test": 0}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result) result = JsonTransmuter.transmute_from({'test': 1}, OldStyleMappedModel) expect(result.test).to.equal(1)
def transmute_to_and_from_with_wrapped_attr_name(self): mapping = TestWrappedModel() mapping.test = "bam" json_str = '{"#item": {"test": "bam"}}' result = JsonTransmuter.transmute_to( mapping, assign_all=True, coerce_values=False ) expect(result).to.equal(json_str) result = JsonTransmuter.transmute_from(json_str, TestWrappedModel) expect(result.test).to.equal("bam")
def transmute_to_and_from_supports_a_list_of_strs(self): class StrMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', [str]), } mapping = StrMappedModel() mapping.test = ['tester'] serialized = '{"test": ["tester"]}' result = JsonTransmuter.transmute_to(mapping) res_dict = json.loads(result) expect(res_dict.get('test')).to.equal(["tester"]) result = JsonTransmuter.transmute_from(serialized, StrMappedModel) expect(result.test).to.equal(["tester"])
def transmute_to_with_old_attr_style(self): class OldStyleMappedModel(JsonMappedModel): __mapping__ = { 'test': ['test', int] } mapping = OldStyleMappedModel() mapping.test = 0 expected_result = '{"test": 0}' result = JsonTransmuter.transmute_to(mapping) expect(result).to.equal(expected_result) result = JsonTransmuter.transmute_from( {'test': 1}, OldStyleMappedModel ) expect(result.test).to.equal(1)
def transmute_to_and_from_supports_a_list_of_uuids(self): class UUIDMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', [uuid.UUID]), } zeroed_uuid = uuid.UUID(int=0) mapping = UUIDMappedModel() mapping.test = [zeroed_uuid] serialized = '{"test": ["' + str(zeroed_uuid) + '"]}' result = JsonTransmuter.transmute_to(mapping) res_dict = json.loads(result) expect(res_dict.get('test')).to.equal([str(zeroed_uuid)]) result = JsonTransmuter.transmute_from(serialized, UUIDMappedModel) expect(result.test).to.equal([zeroed_uuid])
def transmute_to_can_disable_nested_coerce(self): class SubMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int), } class TestMappedModel(JsonMappedModel): __mapping__ = { 'nope': Attr('nope', SubMappedModel), } model = TestMappedModel() model.nope = SubMappedModel() model.nope.test = '1' expected_result = '{"nope": {"test": "1"}}' result = JsonTransmuter.transmute_to(model, coerce_values=False) expect(result).to.equal(expected_result)
def transmute_to_and_from_with_unknown_type(self): class CustomType(object): def __init__(self, something): self.something = something class TestMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', CustomType), } model = TestMappedModel() model.test = CustomType('thing') serialized = '{}' result = JsonTransmuter.transmute_to(model) expect(result).to.equal(serialized) result = JsonTransmuter.transmute_from( '{"test": {"something": "thing"}}', TestMappedModel) attr = getattr(result, 'test', None) expect(attr).to.be_none()
def transmute_to_and_from_with_expanded_type(self): class CustomType(object): def __init__(self, something): self.something = something class CustomDefinition(ExpandedType): cls = CustomType @classmethod def serialize(self, value): return { 'something': value.something } @classmethod def deserialize(self, attr_type, value): return attr_type(**value) class TestMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', CustomType), } model = TestMappedModel() model.test = CustomType('thing') serialized = '{"test": {"something": "thing"}}' alchemize.register_type(CustomDefinition) result = JsonTransmuter.transmute_to(model) expect(result).to.equal(serialized) result = JsonTransmuter.transmute_from(serialized, TestMappedModel) expect(result.test.something).to.equal('thing') alchemize.remove_type(CustomDefinition)
def __eq__(self, other): if isinstance(other, self.__class__): return JsonTransmuter.transmute_to( self) == JsonTransmuter.transmute_to(other) else: return False