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_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_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_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_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_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 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 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_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_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_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_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 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_from_with_different_attr_naming(self): test_json = '{"my-thing": "something"}' result = JsonTransmuter.transmute_from(test_json, TestDifferentAttrNaming) expect(result.my_thing).to.equal('something')
def transmute_from_with_child_mapping(self): data = '{"other": "sample", "child": {"test": "sample stuff"}}' result = JsonTransmuter.transmute_from(data, TestChildMapping) require(result.child).not_to.be_none() expect(result.child.test).to.equal('sample stuff')
def transmute_from_with_inherited_mapping(self): data = '{"test": "sample", "second": "other"}' result = JsonTransmuter.transmute_from(data, TestExtendedModel) expect(result.test).to.equal('sample') expect(result.second).to.equal('other')
def pet_find_by_id(self, pet_id: int) -> ApiResponse: response = get(f"{self.base_url}pet/{pet_id}", headers=self.headers) 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 test_user_create_with_list(self, api, logger, dp_user_add_list): _user_list = list(map(lambda x: JsonTransmuter.transmute_from(x, User), dp_user_add_list[0])) logger.info(f"Test case for creating users from list") response = api.user_create_with_list(_user_list) assert response.code == dp_user_add_list[1] assert len(response.message) == len(_user_list) logger.info("Test PASSED")
def transmute_from_with_all_required_attrs(self): result = JsonTransmuter.transmute_from( '{"test": 1, "other": 2}', TestRequiredMappedModel, ) expect(result.test).to.equal(1) expect(result.other).to.equal(2)
def store_find_order_by_id(self, order_id: int) -> ApiResponse: response = get(f"{self.base_url}store/order/{order_id}", headers=self.headers) 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_find_by_name(self, user_name: str) -> ApiResponse: response = get(f"{self.base_url}user/{user_name}", headers=self.headers) 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_attribute_with_type(self, attr_type, attr_data, attr_result): class FlexMapping(JsonMappedModel): __mapping__ = {'test': Attr('test', attr_type)} data = '{{"test": {0} }}'.format(attr_data) result = JsonTransmuter.transmute_from(data, FlexMapping) expect(result.test).to.equal(attr_result)
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_from_with_list_of_child_mappings(self): data = '{"children": [{"test": "sample1"}, {"test": "sample2"}]}' result = JsonTransmuter.transmute_from(data, TestListChildMapping) require(result.children).not_to.be_none() expect(len(result.children)).to.equal(2) expect(result.children[0].test).to.equal('sample1') expect(result.children[1].test).to.equal('sample2')
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 transmute_from_with_different_attr_naming(self): test_json = '{"my-thing": "something"}' result = JsonTransmuter.transmute_from( test_json, TestDifferentAttrNaming ) expect(result.my_thing).to.equal('something')
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 test_pet_find_by_tags(self, api, logger, dp_pet_tag): logger.info("Test case for finding pet by tags list") tag_list = list( map(lambda x: JsonTransmuter.transmute_from(x, Tag), dp_pet_tag[0])) response = api.pet_find_by_tags(tag_list) assert response.code == dp_pet_tag[1] assert response.type == ApiResponseType.ok # assert all(lambda x: x.tag.name == "tag1" and x.tag.id == 1 for x in response) logger.info("PASSED")
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_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_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(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_find_by_status(self, status: PetStatus) -> ApiResponse: response = get(f"{self.base_url}pet/findByStatus", headers=self.headers, params={"status": status.value}) return ApiResponse( response.status_code, ApiResponseType.ok if response.ok else ApiResponseType.error, list( map(lambda x: JsonTransmuter.transmute_from(x, Pet), response.json())) if response.ok else response.text)
def transmute_attribute_with_type(self, attr_type, attr_data, attr_result): class FlexMapping(JsonMappedModel): __mapping__ = { 'test': Attr('test', attr_type) } data = '{{"test": {0} }}'.format(attr_data) result = JsonTransmuter.transmute_from(data, FlexMapping) expect(result.test).to.equal(attr_result)
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_from_leaves_default_if_not_there(self): class TestMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', str), } test = '' test_json = '{"not-in-here": "1"}' result = JsonTransmuter.transmute_from(test_json, TestMappedModel) expect(result.test).to.equal('')
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_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_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_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_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_from_coercion_can_be_overriden_per_attr(self): class TestMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int, coerce=False), } test_json = '{"test": "1"}' result = JsonTransmuter.transmute_from( test_json, TestMappedModel, coerce_values=True ) expect(result.test).to.equal('1')
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_from_can_coerce_types(self): class TestMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int), } test_json = '{"test": "1"}' result = JsonTransmuter.transmute_from( test_json, TestMappedModel, coerce_values=True ) expect(result.test).to.equal(1) expect(result.test).to.be_an_instance_of(int)