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_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_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 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_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_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_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 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_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 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_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 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 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_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 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 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_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 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 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_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 test_pet_find_by_id(self, api, dp_pet_id, logger): _pet = JsonTransmuter.transmute_from( dp_pet_id[1], Pet) if dp_pet_id[2] == 200 else None logger.info(f"Test case for finding pet by ID={dp_pet_id[0]}") response = api.pet_find_by_id(dp_pet_id[0]) assert response.code == dp_pet_id[2] if response.type == ApiResponseType.ok: assert _pet == response.message else: assert response.message == dp_pet_id[1] logger.info("Test PASSED")
def test_user_update(self, api, logger, dp_user_update): _user = JsonTransmuter.transmute_from(dp_user_update[1], User) logger.info(f"Test case for updating user with name={dp_user_update[0]}") response = api.user_update(dp_user_update[0], _user) assert response.code == dp_user_update[2] assert response.type == ApiResponseType.ok assert response.message == _user logger.info(f"User {dp_user_update[0]} was updated") response = api.user_find_by_name(_user) assert response.code == 200 assert response.message == _user logger.info("Test PASSED")
def test_pet_update(self, api, dp_pet_update, logger): _pet = JsonTransmuter.transmute_from(dp_pet_update[0], Pet) logger.info("Test case for updating pet to the store") response = api.pet_update(_pet) assert response.code == dp_pet_update[1] assert response.type == ApiResponseType.ok assert _pet == response.message logger.info(f"Pet with ID={_pet.id} was updated.") response = api.pet_find_by_id(_pet.id) assert response.type == ApiResponseType.ok assert response.message == _pet logger.info("Test PASSED")
def test_pet_add(self, api, dp_pet_add, logger): _pet = JsonTransmuter.transmute_from(dp_pet_add[0], Pet) logger.info(f"Test case for adding pet with ID={_pet.id}") response = api.pet_add(_pet) assert response.code == dp_pet_add[1] assert response.type == ApiResponseType.ok assert _pet == response.message logger.info(f"Pet with ID={_pet.id} was added.") response = api.pet_find_by_id(_pet.id) assert response.type == ApiResponseType.ok assert response.message == _pet logger.info("Test PASSED")
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 test_user_create(self, api, logger, dp_user_add): _user = JsonTransmuter.transmute_from(dp_user_add[0], User) logger.info(f"Test case for adding user with ID={_user.id}") response = api.user_create(_user) assert response.code == dp_user_add[1] assert response.type == ApiResponseType.ok assert _user == response.message logger.info(f"User with ID={_user.id} was created.") response = api.user_find_by_name(_user.name) assert response.type == ApiResponseType.ok assert response.message == _user logger.info("Test PASSED")
def test_store_place_order(self, api, logger, dp_order_place): _order = JsonTransmuter.transmute_from(dp_order_place[0], Order) logger.info(f"Test case for placing an order, ID={_order.id}") response = api.store_place_order(_order) assert response.code == dp_order_place[1] assert response.message == _order logger.info(f"Order with ID={_order.id} was placed") response = api.store_find_order_by_id(_order.id) assert response.code == 200 assert response.type == ApiResponseType.ok assert response.message == _order logger.info("Test PASSED")
def pet_upload_image(self, pet_id: int, metadata: str, image) -> ApiResponse: headers_ = self.headers.copy() headers_["Content-Type"] = "application/octet-stream" response = post(f"{self.base_url}pet/{pet_id}/uploadImage", headers=headers_, params={"additionalMetadata": metadata}, data=image) 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 user_create_with_list(self, user_list: [User]) -> ApiResponse: response = post(f"{self.base_url}createWithList", headers=self.headers, data=str( list(map(JsonTransmuter.transmute_to, user_list)))) return ApiResponse( response.status_code, ApiResponseType.ok if response.ok else ApiResponseType.error, list( map( lambda x: JsonTransmuter.transmute_from( response.text, User), response.json())) if response.ok else response.text)
def pet_update_by_form_data(self, pet_id: int, name: str, status: PetStatus) -> ApiResponse: response = post(f"{self.base_url}pet/{pet_id}", headers=self.headers, params={ "name": name, "status": status.value }) 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_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_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_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)
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_from_can_disable_nested_coerce(self): class SubMappedModel(JsonMappedModel): __mapping__ = { 'test': Attr('test', int), } class TestMappedModel(JsonMappedModel): __mapping__ = { 'nope': Attr('nope', SubMappedModel), } test_json = '{"nope": {"test": "1"}}' result = JsonTransmuter.transmute_from( test_json, TestMappedModel, coerce_values=False ) expect(result.nope.test).to.equal('1') expect(result.nope.test).not_to.be_an_instance_of(int)
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(cls, data, **options): return JsonTransmuter.transmute_from(data, cls, **options)