diff --git a/imagekitio/file.py b/imagekitio/file.py index 4f7c62c..92092ee 100644 --- a/imagekitio/file.py +++ b/imagekitio/file.py @@ -1,3 +1,4 @@ +import ast from json import dumps from typing import Any, Dict @@ -162,10 +163,10 @@ def get_file_versions(self, file_id: str = None) -> ListFileResult: elif resp.status_code == 404: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -191,10 +192,10 @@ def get_file_version_details( elif resp.status_code == 404: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -288,8 +289,10 @@ def delete_file_version(self, file_id, version_id) -> ResponseMetadataResult: elif resp.status_code == 400 or resp.status_code == 404: response = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = response["message"] if type(response) == dict else "" - response_help = response["help"] if type(response) == dict else "" + if type(response) == str: + response = ast.literal_eval(response) + error_message = response['message'] if type(response) == dict else "" + response_help = response['help'] if type(response) == dict else "" if resp.status_code == 400: raise BadRequestException( error_message, response_help, response_meta_data @@ -337,8 +340,10 @@ def copy_file( elif resp.status_code == 404: response = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = response["message"] if type(response) == dict else "" - response_help = response["help"] if type(response) == dict else "" + if type(response) == str: + response = ast.literal_eval(response) + error_message = response['message'] if type(response) == dict else "" + response_help = response['help'] if type(response) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -360,8 +365,10 @@ def move_file( elif resp.status_code == 404: response = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = response["message"] if type(response) == dict else "" - response_help = response["help"] if type(response) == dict else "" + if type(response) == str: + response = ast.literal_eval(response) + error_message = response['message'] if type(response) == dict else "" + response_help = response['help'] if type(response) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -383,8 +390,10 @@ def rename_file(self, options: RenameFileRequestOptions = None) -> RenameFileRes elif resp.status_code == 409: response = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = response["message"] if type(response) == dict else "" - response_help = response["help"] if type(response) == dict else "" + if type(response) == str: + response = ast.literal_eval(response) + error_message = response['message'] if type(response) == dict else "" + response_help = response['help'] if type(response) == dict else "" raise ConflictException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -408,8 +417,10 @@ def restore_file_version( elif resp.status_code == 404: response = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = response["message"] if type(response) == dict else "" - response_help = response["help"] if type(response) == dict else "" + if type(response) == str: + response = ast.literal_eval(response) + error_message = response['message'] if type(response) == dict else "" + response_help = response['help'] if type(response) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -430,8 +441,10 @@ def create_folder( else: response = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = response["message"] if type(response) == dict else "" - response_help = response["help"] if type(response) == dict else "" + if type(response) == str: + response = ast.literal_eval(response) + error_message = response['message'] if type(response) == dict else "" + response_help = response['help'] if type(response) == dict else "" raise UnknownException(error_message, response_help, response_meta_data) def delete_folder( @@ -450,10 +463,10 @@ def delete_folder( elif resp.status_code == 404: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -473,10 +486,10 @@ def copy_folder(self, options: CopyFolderRequestOptions = None) -> FolderResult: elif resp.status_code == 404: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -497,10 +510,10 @@ def move_folder(self, options: MoveFolderRequestOptions = None) -> FolderResult: elif resp.status_code == 404: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" raise NotFoundException(error_message, response_help, response_meta_data) else: general_api_throw_exception(resp) @@ -609,10 +622,10 @@ def create_custom_metadata_fields( else: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" if resp.status_code == 400: raise BadRequestException( error_message, response_help, response_meta_data @@ -625,7 +638,7 @@ def get_custom_metadata_fields( ) -> ListCustomMetadataFieldsResult: """get custom metadata fields""" url = "{}/v1/customMetadataFields".format(URL.API_BASE_URL) - param = {"includeDeleted": include_deleted} + param = {"includeDeleted": str(include_deleted).lower()} resp = self.request.request( method="GET", url=url, headers=self.request.create_headers(), params=param ) @@ -637,8 +650,10 @@ def get_custom_metadata_fields( else: response = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = response["message"] if type(response) == dict else "" - response_help = response["help"] if type(response) == dict else "" + if type(response) == str: + response = ast.literal_eval(response) + error_message = response['message'] if type(response) == dict else "" + response_help = response['help'] if type(response) == dict else "" raise UnknownException(error_message, response_help, response_meta_data) @@ -668,10 +683,10 @@ def update_custom_metadata_fields( else: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" if resp.status_code == 400: raise BadRequestException( error_message, response_help, response_meta_data @@ -695,10 +710,10 @@ def delete_custom_metadata_field(self, field_id: str) -> ResponseMetadataResult: else: response_json = get_response_json(resp) response_meta_data = populate_response_metadata(resp) - error_message = ( - response_json["message"] if type(response_json) == dict else "" - ) - response_help = response_json["help"] if type(response_json) == dict else "" + if type(response_json) == str: + response_json = ast.literal_eval(response_json) + error_message = response_json['message'] if type(response_json) == dict else "" + response_help = response_json['help'] if type(response_json) == dict else "" if resp.status_code == 404: raise NotFoundException( error_message, response_help, response_meta_data diff --git a/imagekitio/models/results/FileResult.py b/imagekitio/models/results/FileResult.py index 187dbdb..2263f5b 100644 --- a/imagekitio/models/results/FileResult.py +++ b/imagekitio/models/results/FileResult.py @@ -12,7 +12,7 @@ def __init__( updated_at, file_id, tags, - ai_tags: List[dict] = [], + ai_tags: List[AITags] = [], version_info: dict = {}, embedded_metadata: dict = {}, custom_coordinates: str = "", @@ -38,7 +38,9 @@ def __init__( self.ai_tags: List[AITags] = [] if ai_tags is not None: for i in ai_tags: - self.ai_tags.append(AITags(i["name"], i["confidence"], i["source"])) + self.ai_tags.append(AITags(i["name"] if "name" in i else None, + i["confidence"] if "confidence" in i else None, + i["source"] if 'source' in i else None)) self.version_info = VersionInfo(version_info["id"], version_info["name"]) self.embedded_metadata = embedded_metadata self.custom_coordinates = custom_coordinates diff --git a/imagekitio/models/results/FileResultWithResponseMetadata.py b/imagekitio/models/results/FileResultWithResponseMetadata.py index eafbef1..bc1f6a9 100644 --- a/imagekitio/models/results/FileResultWithResponseMetadata.py +++ b/imagekitio/models/results/FileResultWithResponseMetadata.py @@ -11,10 +11,10 @@ def __init__( self, type, name, - created_at, - updated_at, - file_id, - tags, + created_at=None, + updated_at=None, + file_id=None, + tags=None, ai_tags: List[AITags] = AITags(None, None, None), version_info: VersionInfo = VersionInfo(None, None), embedded_metadata=None, diff --git a/imagekitio/utils/utils.py b/imagekitio/utils/utils.py index 40c05cd..4c5aaa2 100644 --- a/imagekitio/utils/utils.py +++ b/imagekitio/utils/utils.py @@ -1,3 +1,4 @@ +import ast from json import loads, dumps from requests.models import Response @@ -36,8 +37,10 @@ def populate_response_metadata(response: Response): def general_api_throw_exception(response: Response): resp = get_response_json(response) response_meta_data = populate_response_metadata(response) - error_message = resp["message"] if type(resp) == dict else "" - response_help = resp["help"] if type(resp) == dict and "help" in resp else "" + if type(resp) == str: + resp = ast.literal_eval(resp) + error_message = resp['message'] if type(resp) == dict else "" + response_help = resp['help'] if type(resp) == dict and 'help' in resp else "" if response.status_code == 400: raise BadRequestException(error_message, response_help, response_meta_data) elif response.status_code == 401: @@ -60,8 +63,10 @@ def general_api_throw_exception(response: Response): def throw_other_exception(response: Response): resp = get_response_json(response) response_meta_data = populate_response_metadata(response) - error_message = resp["message"] if type(resp) == dict else "" - response_help = resp["help"] if type(resp) == dict else "" + if type(resp) == str: + resp = ast.literal_eval(resp) + error_message = resp['message'] if type(resp) == dict else "" + response_help = resp['help'] if type(resp) == dict else "" if response.status_code == 207: raise PartialSuccessException(error_message, response_help, response_meta_data) elif response.status_code == 404: diff --git a/requirements/test.txt b/requirements/test.txt index e9dcd7c..16982d3 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -2,5 +2,5 @@ requests>=2.22.0 black==19.10b0 coverage==4.5.4 tox==3.14.2 -responses==0.21.0 +responses==0.17.0 requests_toolbelt==0.9.1 \ No newline at end of file diff --git a/tests/helpers.py b/tests/helpers.py index 822ccb1..4b9daf4 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -1,4 +1,5 @@ import base64 +import re import unittest from unittest.mock import patch @@ -38,3 +39,7 @@ def get_auth_headers_for_test(): "utf-8" ) return {"Authorization": "Basic {}".format(encoded_private_key)} + + +def make_string_to_single_line(multiline_string): + return re.sub(r'\s(?=\s)', '', re.sub(r'\s', ' ', multiline_string)).replace('{ ', '{').replace(' }', '}') diff --git a/tests/test_custom_metadata_fields_ops.py b/tests/test_custom_metadata_fields_ops.py index af332dc..eddf066 100644 --- a/tests/test_custom_metadata_fields_ops.py +++ b/tests/test_custom_metadata_fields_ops.py @@ -1,5 +1,3 @@ -import json - import responses from responses import matchers @@ -13,7 +11,7 @@ from imagekitio.models.CustomMetadataFieldsSchema import CustomMetadataFieldsSchema from imagekitio.models.UpdateCustomMetadataFieldsRequestOptions import UpdateCustomMetadataFieldsRequestOptions from imagekitio.utils.formatter import camel_dict_to_snake_dict -from tests.helpers import ClientTestCase, create_headers_for_test +from tests.helpers import ClientTestCase, create_headers_for_test, make_string_to_single_line class TestCustomMetadataFields(ClientTestCase): @@ -23,7 +21,6 @@ class TestCustomMetadataFields(ClientTestCase): field_id = "field_id" - @responses.activate def test_get_custom_metadata_fields_fails_on_unauthenticated_request(self): """ @@ -36,8 +33,8 @@ def test_get_custom_metadata_fields_fails_on_unauthenticated_request(self): responses.GET, url, status=403, - body=json.dumps({'message': 'Your account cannot be authenticated.' - , 'help': 'For support kindly contact us at support@imagekit.io .'}), + body='''{"message": "Your account cannot be authenticated." + , "help": "For support kindly contact us at support@imagekit.io ."}''', ) self.client.get_custom_metadata_fields(True) self.assertRaises(ForbiddenException) @@ -56,28 +53,28 @@ def test_get_custom_metadata_fields_succeeds(self): responses.add( responses.GET, url, - body=json.dumps([{ - "id": "62a9d5f6db485107347bb7f2", - "name": "test10", - "label": "test10", - "schema": { - "type": "Number", - "isValueRequired": False, - "minValue": 10, - "maxValue": 1000 - } - }, { - "id": "62aab2cfdb4851833b8f5e64", - "name": "test11", - "label": "test11", - "schema": { - "type": "Number", - "isValueRequired": False, - "minValue": 10, - "maxValue": 1000 - } - }]), - match=[matchers.query_string_matcher("includeDeleted=False")], + body='''[{ + "id": "62a9d5f6db485107347bb7f2", + "name": "test10", + "label": "test10", + "schema": { + "type": "Number", + "isValueRequired": false, + "minValue": 10, + "maxValue": 1000 + } + }, { + "id": "62aab2cfdb4851833b8f5e64", + "name": "test11", + "label": "test11", + "schema": { + "type": "Number", + "isValueRequired": false, + "minValue": 10, + "maxValue": 1000 + } + }]''', + match=[matchers.query_string_matcher("includeDeleted=false")], headers=headers ) resp = self.client.get_custom_metadata_fields() @@ -115,7 +112,7 @@ def test_get_custom_metadata_fields_succeeds(self): self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual('62a9d5f6db485107347bb7f2', resp.list[0].id) self.assertEqual('62aab2cfdb4851833b8f5e64', resp.list[1].id) - self.assertEqual("http://test.com/v1/customMetadataFields?includeDeleted=False", responses.calls[0].request.url) + self.assertEqual("http://test.com/v1/customMetadataFields?includeDeleted=false", responses.calls[0].request.url) @responses.activate def test_delete_custom_metadata_fields_succeeds(self): @@ -130,7 +127,7 @@ def test_delete_custom_metadata_fields_succeeds(self): url, status=204, headers=headers, - body=json.dumps({}) + body="{}" ) resp = self.client.delete_custom_metadata_field(self.field_id) @@ -161,8 +158,8 @@ def test_delete_custom_metadata_fields_fails_with_404(self): url, status=404, headers=headers, - body=json.dumps({"message": "No such custom metadata field exists", - "help": "For support kindly contact us at support@imagekit.io ."}) + body='''{"message": "No such custom metadata field exists", + "help": "For support kindly contact us at support@imagekit.io ."}''' ) self.client.delete_custom_metadata_field(self.field_id) self.assertRaises(NotFoundException) @@ -182,8 +179,8 @@ def test_create_custom_metadata_fields_fails_with_400(self): responses.POST, url, status=400, - body=json.dumps({"message": "A custom metadata field with this name already exists" - , "help": "For support kindly contact us at support@imagekit.io ."}) + body='''{"message": "A custom metadata field with this name already exists" + , "help": "For support kindly contact us at support@imagekit.io ."}''' ) self.client.create_custom_metadata_fields(options=CreateCustomMetadataFieldsRequestOptions(name="test", label="test", @@ -212,7 +209,7 @@ def test_create_custom_metadata_fields_succeeds_with_type_number(self): url, status=201, headers=headers, - body=json.dumps({ + body='''{ "id": "62dfc03b1b02a58936efca37", "name": "test", "label": "test", @@ -221,7 +218,7 @@ def test_create_custom_metadata_fields_succeeds_with_type_number(self): "minValue": 100, "maxValue": 200 } - }) + }''' ) resp = self.client.create_custom_metadata_fields(options=CreateCustomMetadataFieldsRequestOptions(name="test", label="test", @@ -251,7 +248,7 @@ def test_create_custom_metadata_fields_succeeds_with_type_number(self): } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "name": "test", "label": "test", "schema": { @@ -259,11 +256,11 @@ def test_create_custom_metadata_fields_succeeds_with_type_number(self): "minValue": 100, "maxValue": 200 } - }) + }''') self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/customMetadataFields", responses.calls[0].request.url) - self.assertEqual(request_body, responses.calls[0].request.body) + self.assertMultiLineEqual(request_body, responses.calls[0].request.body) @responses.activate def test_create_custom_metadata_fields_succeeds_with_type_textarea(self): @@ -279,18 +276,18 @@ def test_create_custom_metadata_fields_succeeds_with_type_textarea(self): url, status=201, headers=headers, - body=json.dumps({ + body='''{ "id": "62e0d7ae1b02a589360dc1fd", "name": "test", "label": "test", "schema": { - "isValueRequired": True, + "isValueRequired": true, "defaultValue": "The", "type": "Textarea", "minLength": 3, "maxLength": 200 } - }) + }''' ) resp = self.client.create_custom_metadata_fields(options=CreateCustomMetadataFieldsRequestOptions(name="test", label="test", @@ -323,17 +320,17 @@ def test_create_custom_metadata_fields_succeeds_with_type_textarea(self): } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "name": "test", "label": "test", "schema": { "type": "Textarea", "defaultValue": "The", - "isValueRequired": True, + "isValueRequired": true, "minLength": 3, "maxLength": 200 } - }) + }''') self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/customMetadataFields", responses.calls[0].request.url) @@ -353,7 +350,7 @@ def test_create_custom_metadata_fields_succeeds_with_type_date(self): url, status=201, headers=headers, - body=json.dumps({ + body='''{ "id": "62dfc9f41b02a58936f0d284", "name": "test-date", "label": "test-date", @@ -362,7 +359,7 @@ def test_create_custom_metadata_fields_succeeds_with_type_date(self): "minValue": "2022-11-29T10:11:10+00:00", "maxValue": "2022-11-30T10:11:10+00:00" } - }) + }''' ) resp = self.client.create_custom_metadata_fields( options=CreateCustomMetadataFieldsRequestOptions(name="test-date", @@ -393,15 +390,15 @@ def test_create_custom_metadata_fields_succeeds_with_type_date(self): } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "name": "test-date", "label": "test-date", "schema": { - 'type': 'Date', + "type": "Date", "minValue": "2022-11-29T10:11:10+00:00", "maxValue": "2022-11-30T10:11:10+00:00" } - }) + }''') self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/customMetadataFields", responses.calls[0].request.url) @@ -421,16 +418,16 @@ def test_create_custom_metadata_fields_succeeds_with_type_boolean(self): url, status=201, headers=headers, - body=json.dumps({ + body='''{ "id": "62dfcb801b02a58936f0fc39", "name": "test-boolean", "label": "test-boolean", "schema": { "type": "Boolean", - "isValueRequired": True, - "defaultValue": True + "isValueRequired": true, + "defaultValue": true } - }) + }''' ) resp = self.client.create_custom_metadata_fields( options=CreateCustomMetadataFieldsRequestOptions(name="test-boolean", @@ -461,15 +458,15 @@ def test_create_custom_metadata_fields_succeeds_with_type_boolean(self): } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "name": "test-boolean", "label": "test-boolean", "schema": { "type": "Boolean", - "defaultValue": True, - "isValueRequired": True + "defaultValue": true, + "isValueRequired": true } - }) + }''') self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/customMetadataFields", responses.calls[0].request.url) @@ -489,15 +486,15 @@ def test_create_custom_metadata_fields_succeeds_with_type_single_select(self): url, status=201, headers=headers, - body=json.dumps({ + body='''{ "id": "62dfcdb21b02a58936f14c97", "name": "test", "label": "test", "schema": { "type": "SingleSelect", - "selectOptions": ["small", "medium", "large", 30, 40, True] + "selectOptions": ["small", "medium", "large", 30, 40, true] } - }) + }''' ) resp = self.client.create_custom_metadata_fields(options=CreateCustomMetadataFieldsRequestOptions(name="test", label="test", @@ -536,15 +533,15 @@ def test_create_custom_metadata_fields_succeeds_with_type_single_select(self): } } - request_body = json.dumps({"name": "test", + request_body = make_string_to_single_line('''{"name": "test", "label": "test", "schema": { "type": "SingleSelect", "selectOptions": ["small", "medium", "large", 30, 40, - True] + true] } - }) + }''') self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/customMetadataFields", responses.calls[0].request.url) @@ -564,17 +561,17 @@ def test_create_custom_metadata_fields_succeeds_with_type_multi_select(self): url, status=201, headers=headers, - body=json.dumps({ + body='''{ "id": "62dfcf001b02a58936f17808", "name": "test", "label": "test", "schema": { "type": "MultiSelect", - "isValueRequired": True, - "defaultValue": ["small", 30, True], - "selectOptions": ["small", "medium", "large", 30, 40, True] + "isValueRequired": true, + "defaultValue": ["small", 30, true], + "selectOptions": ["small", "medium", "large", 30, 40, true] } - }) + }''' ) resp = self.client.create_custom_metadata_fields(options=CreateCustomMetadataFieldsRequestOptions(name="test", label="test", @@ -623,16 +620,16 @@ def test_create_custom_metadata_fields_succeeds_with_type_multi_select(self): } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "name": "test", "label": "test", "schema": { "type": "MultiSelect", - "selectOptions": ["small", "medium", "large", 30, 40, True], - "defaultValue": ["small", 30, True], - "isValueRequired": True + "selectOptions": ["small", "medium", "large", 30, 40, true], + "defaultValue": ["small", 30, true], + "isValueRequired": true } - }) + }''') self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/customMetadataFields", responses.calls[0].request.url) @@ -651,7 +648,7 @@ def test_update_custom_metadata_fields_succeeds(self): responses.PATCH, url, headers=headers, - body=json.dumps({ + body='''{ "id": "62a9d5f6db485107347bb7f2", "name": "test", "label": "test-update", @@ -660,7 +657,7 @@ def test_update_custom_metadata_fields_succeeds(self): "maxValue": 200, "type": "Number" } - }) + }''' ) resp = self.client.update_custom_metadata_fields(self.field_id, @@ -689,13 +686,13 @@ def test_update_custom_metadata_fields_succeeds(self): } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "label": "test-update", "schema": { "minValue": 100, "maxValue": 200 } - }) + }''') self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual('62a9d5f6db485107347bb7f2', resp.id) @@ -715,10 +712,10 @@ def test_update_custom_metadata_fields_fails_with_404(self): responses.PATCH, url, status=404, - body=json.dumps({ + body='''{ "message": "No such custom metadata field exists", "help": "For support kindly contact us at support@imagekit.io ." - }) + }''' ) self.client.update_custom_metadata_fields(self.field_id, @@ -744,10 +741,10 @@ def test_update_custom_metadata_fields_fails_with_400(self): responses.PATCH, url, status=400, - body=json.dumps({ + body='''{ "message": "Your request contains invalid ID parameter.", "help": "For support kindly contact us at support@imagekit.io ." - }) + }''' ) self.client.update_custom_metadata_fields(self.field_id, diff --git a/tests/test_files_ops.py b/tests/test_files_ops.py index 7856914..9b2437d 100644 --- a/tests/test_files_ops.py +++ b/tests/test_files_ops.py @@ -1,5 +1,4 @@ import base64 -import json import os import responses @@ -22,6 +21,7 @@ ClientTestCase, create_headers_for_test, get_auth_headers_for_test, + make_string_to_single_line, ) imagekit_obj = ImageKit( @@ -57,12 +57,8 @@ def test_upload_fails_on_unauthenticated_request(self): responses.POST, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "Your account cannot be authenticated." + , "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.upload_file( file=self.image, @@ -97,8 +93,7 @@ def test_upload_fails_on_unauthenticated_request(self): overwrite_tags=False, overwrite_custom_metadata=True, custom_metadata={"testss": 12}, - ), - ) + )) self.assertRaises(ForbiddenException) except ForbiddenException as e: self.assertEqual(e.message, "Your account cannot be authenticated.") @@ -115,42 +110,42 @@ def test_binary_upload_succeeds(self): responses.add( responses.POST, url, - body=json.dumps( - { - "fileId": "fake_file_id1234", - "name": "file_name.jpg", - "size": 102117, - "versionInfo": { - "id": "62d670648cdb697522602b45", - "name": "Version 11", - }, - "filePath": "/testing-python-folder/file_name.jpg", - "url": "https://ik.imagekit.io/your_imagekit_id/testing-python-folder/file_name.jpg", - "fileType": "image", - "height": 700, - "width": 1050, - "thumbnailUrl": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/testing-python-folder" - "/file_name.jpg", - "tags": ["abc", "def"], - "AITags": [ - { - "name": "Computer", - "confidence": 97.66, - "source": "google-auto-tagging", - }, - { - "name": "Personal computer", - "confidence": 94.96, - "source": "google-auto-tagging", + body="""{ + "fileId": "fake_file_id1234", + "name": "file_name.jpg", + "size": 102117, + "versionInfo": { + "id": "62d670648cdb697522602b45", + "name": "Version 11" }, - ], - "isPrivateFile": True, - "extensionStatus": { - "remove-bg": "pending", - "google-auto-tagging": "success", - }, - } - ), + "filePath": "/testing-python-folder/file_name.jpg", + "url": "https://ik.imagekit.io/your_imagekit_id/testing-python-folder/file_name.jpg", + "fileType": "image", + "height": 700, + "width": 1050, + "thumbnailUrl": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/testing-python-folder/file_name.jpg", + "tags": [ + "abc", + "def" + ], + "AITags": [ + { + "name": "Computer", + "confidence": 97.66, + "source": "google-auto-tagging" + }, + { + "name": "Personal computer", + "confidence": 94.96, + "source": "google-auto-tagging" + } + ], + "isPrivateFile": true, + "extensionStatus": { + "remove-bg": "pending", + "google-auto-tagging": "success" + } + }""", headers=headers, ) @@ -181,66 +176,63 @@ def test_binary_upload_succeeds(self): ), ) mock_response_metadata = { - "raw": { - "fileId": "fake_file_id1234", - "name": "file_name.jpg", - "size": 102117, - "versionInfo": {"id": "62d670648cdb697522602b45", "name": "Version 11"}, - "filePath": "/testing-python-folder/file_name.jpg", - "url": "https://ik.imagekit.io/your_imagekit_id/testing-python-folder/file_name.jpg", - "fileType": "image", - "height": 700, - "width": 1050, - "thumbnailUrl": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/testing-python-folder/file_name.jpg", - "tags": ["abc", "def"], - "AITags": [ - { - "name": "Computer", - "confidence": 97.66, - "source": "google-auto-tagging", - }, - { - "name": "Personal computer", - "confidence": 94.96, - "source": "google-auto-tagging", - }, - ], - "isPrivateFile": True, - "extensionStatus": { - "remove-bg": "pending", - }, - }, - "httpStatusCode": 200, - "headers": { - "Content-Type": "text/plain", - "Accept-Encoding": "gzip, deflate", - "Authorization": "Basic ZmFrZTEyMjo=", + 'headers': { + 'Content-Type': 'text/plain', + 'Accept-Encoding': 'gzip, deflate', + 'Authorization': 'Basic ZmFrZTEyMjo=' }, + 'http_status_code': 200, + 'raw': { + 'AITags': [{ + 'confidence': 97.66, + 'name': 'Computer', + 'source': 'google-auto-tagging' + }, { + 'confidence': 94.96, + 'name': 'Personal computer', + 'source': 'google-auto-tagging' + }], + 'extensionStatus': { + 'google-auto-tagging': 'success', + 'remove-bg': 'pending' + }, + 'fileId': 'fake_file_id1234', + 'filePath': '/testing-python-folder/file_name.jpg', + 'fileType': 'image', + 'height': 700, + 'isPrivateFile': True, + 'name': 'file_name.jpg', + 'size': 102117, + 'tags': ['abc', 'def'], + 'thumbnailUrl': 'https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/testing-python-folder/file_name.jpg', + 'url': 'https://ik.imagekit.io/your_imagekit_id/testing-python-folder/file_name.jpg', + 'versionInfo': { + 'id': '62d670648cdb697522602b45', + 'name': 'Version 11' + }, + 'width': 1050 + } } - request_body = json.loads( - json.dumps( - { - "file": "<_io.BufferedReader name='sample.jpg'>", - "fileName": "file_name.jpg", - "useUniqueFileName": "false", - "responseFields": "isPrivateFile,tags", - "isPrivateFile": "true", - "folder": "/testing-python-folder/", - "tags": "abc,def", - "extensions": '[{"name": "remove-bg", "options": {"add_shadow": true, "bg_color": "pink"}}, {"name": ' - '"google-auto-tagging", "minConfidence": 80, "maxTags": 10}]', - "webhookUrl": "url", - "overwriteFile": "true", - "overwriteAITags": "false", - "overwriteTags": "false", - "overwriteCustomMetadata": "true", - "customMetadata": '{"test100": 11}', - } - ) - ) + request_body = make_string_to_single_line("""{ + \'file\': \"<_io.BufferedReader name=\'sample.jpg\'>\", + \'fileName\': \'file_name.jpg\', + \'useUniqueFileName\': \'false\', + \'tags\': \'abc,def\', + \'folder\': \'/testing-python-folder/\', + \'isPrivateFile\': \'true\', + \'responseFields\': \'isPrivateFile,tags\', + \'extensions\': \'[{\"name\": \"remove-bg\", \"options\": {\"add_shadow\": true, \"bg_color\": \"pink\"}}, + {\"name\": \"google-auto-tagging\", \"minConfidence\": 80, \"maxTags\": 10}]\', + \'webhookUrl\': \'url\', + \'overwriteFile\': \'true\', + \'overwriteAITags\': \'false\', + \'overwriteTags\': \'false\', + \'overwriteCustomMetadata\': \'true\', + \'customMetadata\': \'{\"test100\": 11}\' + }""") actual_body = responses.calls[0].request.body.__dict__.__getitem__("fields") actual_body["file"] = "<_io.BufferedReader name='sample.jpg'>" - self.assertEqual(request_body, actual_body) + self.assertEqual(request_body, str(actual_body)) self.assertEqual( camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__, @@ -279,13 +271,11 @@ def test_upload_fails_with_400_exception(self) -> None: responses.POST, url, status=400, - body=json.dumps( - { + body='''{ "message": "A file with the same name already exists at the exact location. We " "could not overwrite it because both overwriteFile and " "useUniqueFileName are set to false." - } - ), + }''' ) self.client.upload_file( file=self.image, @@ -348,17 +338,13 @@ def test_list_files_fails_on_unauthenticated_request(self) -> None: responses.GET, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.list_files(self.options) self.assertRaises(ForbiddenException) except ForbiddenException as e: - self.assertEqual(e.message, "Your account cannot be authenticated.") + self.assertEqual("Your account cannot be authenticated.", e.message) self.assertEqual(403, e.response_metadata.http_status_code) @responses.activate @@ -374,46 +360,43 @@ def test_list_files_succeeds_with_basic_request(self) -> None: responses.add( responses.GET, url, - body=json.dumps( - [ - { - "type": "file", - "name": "sample-cat-image_gr64HPlJS.jpg", - "createdAt": "2022-06-15T08:19:00.843Z", - "updatedAt": "2022-06-15T08:19:45.169Z", - "fileId": "62a995f4d875ec08dc587b72", - "tags": ["{Tag_1", " Tag_2", " Tag_3}", "tag-to-add-2"], - "AITags": None, - "versionInfo": { - "id": "62a995f4d875ec08dc587b72", - "name": "Version 1", - }, - "embeddedMetadata": { - "XResolution": 250, - "YResolution": 250, - "DateCreated": "2022-06-15T08:19:01.523Z", - "DateTimeCreated": "2022-06-15T08:19:01.524Z", - }, - "customCoordinates": "10,10,20,20", - "customMetadata": {"test100": 10}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your_imagekit_id/sample-cat-image_gr64HPlJS.jpg", - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/sample-cat-image_gr64HPlJS.jpg", - "fileType": "image", - "filePath": "/sample-cat-image_gr64HPlJS.jpg", - "height": 354, - "width": 236, - "size": 23023, - "hasAlpha": False, - "mime": "image/jpeg", - } - ] - ), + body="""[{ + "type": "file", + "name": "sample-cat-image_gr64HPlJS.jpg", + "createdAt": "2022-06-15T08:19:00.843Z", + "updatedAt": "2022-06-15T08:19:45.169Z", + "fileId": "62a995f4d875ec08dc587b72", + "tags": ["{Tag_1", " Tag_2", " Tag_3}", "tag-to-add-2"], + "AITags": "", + "versionInfo": { + "id": "62a995f4d875ec08dc587b72", + "name": "Version 1" + }, + "embeddedMetadata": { + "XResolution": 250, + "YResolution": 250, + "DateCreated": "2022-06-15T08:19:01.523Z", + "DateTimeCreated": "2022-06-15T08:19:01.524Z" + }, + "customCoordinates": "10,10,20,20", + "customMetadata": { + "test100": 10 + }, + "isPrivateFile": false, + "url": "https://ik.imagekit.io/your_imagekit_id/sample-cat-image_gr64HPlJS.jpg", + "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/sample-cat-image_gr64HPlJS.jpg", + "fileType": "image", + "filePath": "/sample-cat-image_gr64HPlJS.jpg", + "height": 354, + "width": 236, + "size": 23023, + "hasAlpha": false, + "mime": "image/jpeg" + }]""", headers=headers, match=[ matchers.query_string_matcher( - "type=file&sort=ASC_CREATED&path=%2F&search_query=created_at+%3E%3D+%272d%27+OR+size+%3C+%272mb%27+OR+format%3D%27png%27&file_type=all&limit=1&skip=0&tags=Tag-1%2C+Tag-2%2C+Tag-3" - ) + "%7B%22type%22:%20%22file%22,%20%22sort%22:%20%22ASC_CREATED%22,%20%22path%22:%20%22/%22,%20%22searchQuery%22:%20%22created_at%20%3E=%20'2d'%20OR%20size%20%3C%20'2mb'%20OR%20format='png'%22,%20%22fileType%22:%20%22all%22,%20%22limit%22:%201,%20%22skip%22:%200,%20%22tags%22:%20%22Tag-1,%20Tag-2,%20Tag-3%22%7D") ], ) @@ -428,7 +411,7 @@ def test_list_files_succeeds_with_basic_request(self) -> None: "httpStatusCode": 200, "raw": [ { - "AITags": None, + "AITags": "", "createdAt": "2022-06-15T08:19:00.843Z", "customCoordinates": "10,10,20,20", "customMetadata": {"test100": 10}, @@ -461,7 +444,7 @@ def test_list_files_succeeds_with_basic_request(self) -> None: ], } self.assertEqual( - "http://test.com/v1/files?type=file&sort=ASC_CREATED&path=%2F&search_query=created_at+%3E%3D+%272d%27+OR+size+%3C+%272mb%27+OR+format%3D%27png%27&file_type=all&limit=1&skip=0&tags=Tag-1%2C+Tag-2%2C+Tag-3", + "http://test.com/v1/files?%7B%22type%22:%20%22file%22,%20%22sort%22:%20%22ASC_CREATED%22,%20%22path%22:%20%22/%22,%20%22searchQuery%22:%20%22created_at%20%3E=%20'2d'%20OR%20size%20%3C%20'2mb'%20OR%20format='png'%22,%20%22fileType%22:%20%22all%22,%20%22limit%22:%201,%20%22skip%22:%200,%20%22tags%22:%20%22Tag-1,%20Tag-2,%20Tag-3%22%7D", responses.calls[0].request.url, ) self.assertEqual( @@ -480,17 +463,13 @@ def test_list_files_fails_with_400_exception(self) -> None: responses.GET, url, status=400, - body=json.dumps( - { - "message": "Invalid search query - createdAt field must have a valid date value. Make " - "sure the value is enclosed within quotes. Please refer to the " - "documentation for syntax specification.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "Invalid search query - createdAt field must have a valid date value. Make " + "sure the value is enclosed within quotes. Please refer to the " + "documentation for syntax specification.", + "help": "For support kindly contact us at support@imagekit.io ."}""", match=[ matchers.query_string_matcher( - "type=file&sort=ASC_CREATED&path=%2F&search_query=created_at+%3E%3D+%272d%27+OR+size+%3C+%272mb%27+OR+format%3D%27png%27&file_type=all&limit=1&skip=0&tags=Tag-1%2C+Tag-2%2C+Tag-3" + "%7B%22type%22:%20%22file%22,%20%22sort%22:%20%22ASC_CREATED%22,%20%22path%22:%20%22/%22,%20%22searchQuery%22:%20%22created_at%20%3E=%20'2d'%20OR%20size%20%3C%20'2mb'%20OR%20format='png'%22,%20%22fileType%22:%20%22all%22,%20%22limit%22:%201,%20%22skip%22:%200,%20%22tags%22:%20%22Tag-1,%20Tag-2,%20Tag-3%22%7D" ) ], ) @@ -525,12 +504,8 @@ def test_get_file_details_fails_on_unauthenticated_request(self) -> None: responses.GET, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.get_file_details(self.file_id) self.assertRaises(ForbiddenException) @@ -547,99 +522,88 @@ def test_file_details_succeeds_with_id(self) -> None: responses.add( responses.GET, url, - body=json.dumps( - { - "type": "file", - "name": "new_car.jpg", - "createdAt": "2022-06-15T11:34:36.294Z", - "updatedAt": "2022-07-04T10:15:50.067Z", - "fileId": "fake_file_id1234", - "tags": ["Tag_1", "Tag_2", "Tag_3"], - "AITags": [ - { - "name": "Clothing", - "confidence": 98.77, - "source": "google-auto-tagging", + body="""{ + "type": "file", + "name": "default-image.jpg", + "createdAt": "2022-06-15T08:19:00.843Z", + "updatedAt": "2022-08-19T12:19:22.726Z", + "fileId": "fake_file_id1234", + "tags": [ + "{Software", + " Developer", + " Engineer}", + "tag-to-add-2" + ], + "AITags": null, + "versionInfo": { + "id": "62a995f4d875ec08dc587b72", + "name": "Version 1" }, - { - "name": "Smile", - "confidence": 95.31, - "source": "google-auto-tagging", + "embeddedMetadata": { + "XResolution": 250, + "YResolution": 250, + "DateCreated": "2022-06-15T08:19:01.523Z", + "DateTimeCreated": "2022-06-15T08:19:01.524Z" }, - ], - "versionInfo": { - "id": "62b97749f63122840530fda9", - "name": "Version 4", - }, - "embeddedMetadata": { - "DateCreated": "2022-07-04T10:15:50.066Z", - "DateTimeCreated": "2022-07-04T10:15:50.066Z", - }, - "customCoordinates": "null", - "customMetadata": {"test100": 10, "test10": 11}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your-imagekit-id/new_car.jpg", - "thumbnail": "https://ik.imagekit.io/your-imagekit-id/tr:n-ik_ml_thumbnail/new_car.jpg", - "fileType": "image", - "filePath": "/new_car.jpg", - "height": 354, - "width": 236, - "size": 7390, - "hasAlpha": False, - "mime": "image/jpeg", - } - ), + "customCoordinates": "10,10,20,20", + "customMetadata": { + "test100": 10 + }, + "isPrivateFile": false, + "url": "https://ik.imagekit.io/xyxt2lnil/default-image.jpg", + "thumbnail": "https://ik.imagekit.io/xyxt2lnil/tr:n-ik_ml_thumbnail/default-image.jpg", + "fileType": "image", + "filePath": "/default-image.jpg", + "height": 354, + "width": 236, + "size": 23023, + "hasAlpha": false, + "mime": "image/jpeg" + }""", headers=headers, ) resp = self.client.get_file_details(self.file_id) mock_response_metadata = { - "headers": { - "Content-Type": "text/plain", - "Accept-Encoding": "gzip, deflate", - "Authorization": "Basic ZmFrZTEyMjo=", + 'headers': { + 'Content-Type': 'text/plain', + 'Accept-Encoding': 'gzip, deflate', + 'Authorization': 'Basic ZmFrZTEyMjo=' }, - "httpStatusCode": 200, - "raw": { - "AITags": [ - { - "confidence": 98.77, - "name": "Clothing", - "source": "google-auto-tagging", - }, - { - "confidence": 95.31, - "name": "Smile", - "source": "google-auto-tagging", - }, - ], - "createdAt": "2022-06-15T11:34:36.294Z", - "customCoordinates": "null", - "customMetadata": {"test10": 11, "test100": 10}, - "embeddedMetadata": { - "DateCreated": "2022-07-04T10:15:50.066Z", - "DateTimeCreated": "2022-07-04T10:15:50.066Z", + 'http_status_code': 200, + 'raw': { + 'AITags': None, + 'createdAt': '2022-06-15T08:19:00.843Z', + 'customCoordinates': '10,10,20,20', + 'customMetadata': { + 'test100': 10 }, - "fileId": "fake_file_id1234", - "filePath": "/new_car.jpg", - "fileType": "image", - "hasAlpha": False, - "height": 354, - "isPrivateFile": False, - "mime": "image/jpeg", - "name": "new_car.jpg", - "size": 7390, - "tags": ["Tag_1", "Tag_2", "Tag_3"], - "thumbnail": "https://ik.imagekit.io/your-imagekit-id/tr:n-ik_ml_thumbnail/new_car.jpg", - "type": "file", - "updatedAt": "2022-07-04T10:15:50.067Z", - "url": "https://ik.imagekit.io/your-imagekit-id/new_car.jpg", - "versionInfo": { - "id": "62b97749f63122840530fda9", - "name": "Version " "4", + 'embeddedMetadata': { + 'DateCreated': '2022-06-15T08:19:01.523Z', + 'DateTimeCreated': '2022-06-15T08:19:01.524Z', + 'XResolution': 250, + 'YResolution': 250 }, - "width": 236, - }, + 'fileId': 'fake_file_id1234', + 'filePath': '/default-image.jpg', + 'fileType': 'image', + 'hasAlpha': False, + 'height': 354, + 'isPrivateFile': False, + 'mime': 'image/jpeg', + 'name': 'default-image.jpg', + 'size': 23023, + 'tags': ['{Software', ' Developer', ' Engineer}', 'tag-to-add-2'], + 'thumbnail': 'https://ik.imagekit.io/xyxt2lnil/tr:n-ik_ml_thumbnail/default-image.jpg', + 'type': 'file', + 'updatedAt': '2022-08-19T12:19:22.726Z', + 'url': 'https://ik.imagekit.io/xyxt2lnil/default-image.jpg', + 'versionInfo': { + 'id': '62a995f4d875ec08dc587b72', + 'name': 'Version 1' + }, + 'width': 236 + } } self.assertEqual( @@ -663,12 +627,8 @@ def test_file_details_fails_with_400_exception(self) -> None: responses.GET, url, status=400, - body=json.dumps( - { - "message": "Your request contains invalid fileId parameter.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "Your request contains invalid fileId parameter.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.get_file_details(self.file_id) self.assertRaises(BadRequestException) @@ -681,7 +641,6 @@ def test_file_details_fails_with_400_exception(self) -> None: class TestDeleteFile(ClientTestCase): file_id = "fax_abx1223" - bulk_delete_ids = ["fake_123", "fake_222"] @responses.activate @@ -699,12 +658,8 @@ def test_bulk_file_delete_fails_on_unauthenticated_request(self) -> None: responses.POST, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.bulk_file_delete(self.bulk_delete_ids) self.assertRaises(ForbiddenException) @@ -726,7 +681,7 @@ def test_bulk_file_delete_succeeds(self): responses.add( responses.POST, url, - body=json.dumps({"successfullyDeletedFileIds": ["fake_123", "fake_222"]}), + body='{"successfullyDeletedFileIds": ["fake_123", "fake_222"]}', headers=headers, ) @@ -741,8 +696,7 @@ def test_bulk_file_delete_succeeds(self): }, } self.assertEqual( - json.dumps({"fileIds": ["fake_123", "fake_222"]}), - responses.calls[0].request.body, + '{"fileIds": ["fake_123", "fake_222"]}', responses.calls[0].request.body ) self.assertEqual( camel_dict_to_snake_dict(mock_response_metadata), @@ -767,13 +721,11 @@ def test_bulk_file_delete_fails_with_404_exception(self) -> None: responses.POST, url, status=404, - body=json.dumps( - { - "message": "The requested file(s) does not exist.", - "help": "For support kindly contact us at support@imagekit.io .", - "missingFileIds": ["fake_123", "fake_222"], - } - ), + body="""{ + "message": "The requested file(s) does not exist.", + "help": "For support kindly contact us at support@imagekit.io .", + "missingFileIds": ["fake_123", "fake_222"] + }""", headers=headers, ) self.client.bulk_file_delete(self.bulk_delete_ids) @@ -801,12 +753,10 @@ def test_file_delete_fails_with_400_exception(self): responses.DELETE, url, status=400, - body=json.dumps( - { - "message": "Your request contains invalid fileId parameter.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{ + "message": "Your request contains invalid fileId parameter.", + "help": "For support kindly contact us at support@imagekit.io ." + }""", headers=headers, ) self.client.delete_file(self.file_id) @@ -827,9 +777,7 @@ def test_file_delete_succeeds(self): headers = {"Content-Type": "application/json"} headers.update(get_auth_headers_for_test()) - responses.add( - responses.DELETE, url, body=json.dumps({}), status=204, headers=headers - ) + responses.add(responses.DELETE, url, body="{}", status=204, headers=headers) resp = self.client.delete_file(self.file_id) @@ -865,12 +813,8 @@ def test_purge_file_cache_fails_on_unauthenticated_request(self): responses.POST, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.purge_file_cache(self.fake_image_url) self.assertRaises(ForbiddenException) @@ -890,7 +834,7 @@ def test_purge_file_cache_fails_with_400(self): responses.POST, url, status=400, - body=json.dumps({"message": "Invalid url"}), + body='{"message": "Invalid url"}', ) self.client.purge_file_cache("url") self.assertRaises(BadRequestException) @@ -909,7 +853,7 @@ def test_purge_file_cache_succeeds(self): responses.POST, url, status=201, - body=json.dumps({"requestId": "requestId"}), + body='{"requestId": "requestId"}', ) resp = self.client.purge_file_cache(self.fake_image_url) mock_response_metadata = { @@ -926,7 +870,7 @@ def test_purge_file_cache_succeeds(self): "http://test.com/v1/files/purge", responses.calls[0].request.url ) self.assertEqual( - json.dumps({"url": "https://example.com/fakeid/fakeimage.jpg"}), + '{"url": "https://example.com/fakeid/fakeimage.jpg"}', responses.calls[0].request.body, ) @@ -946,12 +890,8 @@ def test_purge_file_cache_status_fails_with_400(self): responses.GET, url, status=400, - body=json.dumps( - { - "message": "No request found for this requestId.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "No request found for this requestId.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.get_purge_file_cache_status(self.cache_request_id) self.assertRaises(BadRequestException) @@ -969,7 +909,7 @@ def test_purge_file_cache_status_succeeds(self): responses.add( responses.GET, url, - body=json.dumps({"status": "Completed"}), + body="""{"status": "Completed"}""", ) resp = self.client.get_purge_file_cache_status(self.cache_request_id) mock_response_metadata = { @@ -1004,13 +944,9 @@ def test_get_file_metadata_fails_with_400(self): responses.GET, url, status=400, - body=json.dumps( - { - "message": "Your request contains invalid fileId parameter.", - "help": "For support kindly contact us at support@imagekit.io .", - "type": "INVALID_PARAM_ERROR", - } - ), + body="""{"message": "Your request contains invalid fileId parameter.", + "help": "For support kindly contact us at support@imagekit.io .", + "type": "INVALID_PARAM_ERROR"}""", ) self.client.get_file_metadata(self.file_id) self.assertRaises(BadRequestException) @@ -1031,20 +967,18 @@ def test_get_file_metadata_succeeds(self): responses.add( responses.GET, url, - body=json.dumps( - { - "height": 354, - "width": 236, - "size": 7390, - "format": "jpg", - "hasColorProfile": False, - "quality": 0, - "density": 250, - "hasTransparency": False, - "exif": {}, - "pHash": "2e0ed1f12eda9525", - } - ), + body="""{ + "height": 354, + "width": 236, + "size": 7390, + "format": "jpg", + "hasColorProfile": false, + "quality": 0, + "density": 250, + "hasTransparency": false, + "exif": {}, + "pHash": "2e0ed1f12eda9525" + }""", ) resp = self.client.get_file_metadata(self.file_id) mock_response_metadata = { @@ -1084,12 +1018,10 @@ def test_get_remote_file_url_metadata_fails_with_400(self): responses.GET, url, status=400, - body=json.dumps( - { - "message": "https://example.com/fakeid/fakeimage.jpg should be accessible using your ImageKit.io account.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{ + "message": "https://example.com/fakeid/fakeimage.jpg should be accessible using your ImageKit.io account.", + "help": "For support kindly contact us at support@imagekit.io ." + }""", match=[ matchers.query_string_matcher( "url=https://example.com/fakeid/fakeimage.jpg" @@ -1115,20 +1047,18 @@ def test_get_remote_file_url_metadata_succeeds(self): responses.add( responses.GET, url, - body=json.dumps( - { - "height": 354, - "width": 236, - "size": 7390, - "format": "jpg", - "hasColorProfile": False, - "quality": 0, - "density": 250, - "hasTransparency": False, - "exif": {}, - "pHash": "2e0ed1f12eda9525", - } - ), + body="""{ + "height": 354, + "width": 236, + "size": 7390, + "format": "jpg", + "hasColorProfile": false, + "quality": 0, + "density": 250, + "hasTransparency": false, + "exif": {}, + "pHash": "2e0ed1f12eda9525" + }""", match=[ matchers.query_string_matcher( "url=https://example.com/fakeid/fakeimage.jpg" @@ -1185,12 +1115,8 @@ def test_update_file_details_fails_on_unauthenticated_request(self): responses.PATCH, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.update_file_details( file_id=self.file_id, options=self.valid_options @@ -1212,36 +1138,37 @@ def test_update_file_details_succeeds_with_id(self): responses.add( responses.PATCH, url, - body=json.dumps( - { + body="""{ "type": "file", "name": "default-image.jpg", "createdAt": "2022-07-21T10:31:22.529Z", "updatedAt": "2022-07-21T10:37:11.848Z", "fileId": "fake_123", "tags": ["tag1", "tag2"], - "AITags": [ - { - "name": "Corridor", - "confidence": 99.39, - "source": "aws-auto-tagging", - }, - { - "name": "Floor", - "confidence": 97.59, - "source": "aws-auto-tagging", - }, - ], - "versionInfo": {"id": "versionId", "name": "Version 2"}, + "AITags": [{ + "name": "Corridor", + "confidence": 99.39, + "source": "aws-auto-tagging" + }, { + "name": "Floor", + "confidence": 97.59, + "source": "aws-auto-tagging" + }], + "versionInfo": { + "id": "versionId", + "name": "Version 2" + }, "embeddedMetadata": { "XResolution": 1, "YResolution": 1, "DateCreated": "2022-07-21T10:35:34.497Z", - "DateTimeCreated": "2022-07-21T10:35:34.500Z", + "DateTimeCreated": "2022-07-21T10:35:34.500Z" }, "customCoordinates": "10,10,100,100", - "customMetadata": {"test": 11}, - "isPrivateFile": False, + "customMetadata": { + "test": 11 + }, + "isPrivateFile": false, "url": "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/default-image.jpg", "fileType": "image", @@ -1249,31 +1176,38 @@ def test_update_file_details_succeeds_with_id(self): "height": 1000, "width": 1000, "size": 184425, - "hasAlpha": False, + "hasAlpha": false, "mime": "image/jpeg", "extensionStatus": { "remove-bg": "pending", - "google-auto-tagging": "success", - }, - } - ), + "google-auto-tagging": "success" + } + }""", headers=headers, ) - request_body = { + request_body = make_string_to_single_line( + """{ "removeAITags": ["ai-tag1", "ai-tag2"], "webhookUrl": "url", - "extensions": [ - { - "name": "remove-bg", - "options": {"add_shadow": True, "bg_color": "red"}, - }, - {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}, - ], + "extensions": [{ + "name": "remove-bg", + "options": { + "add_shadow": true, + "bg_color": "red" + } + }, { + "name": "google-auto-tagging", + "minConfidence": 80, + "maxTags": 10 + }], "tags": ["tag1", "tag2"], "customCoordinates": "10,10,100,100", - "customMetadata": {"test": 11}, - } + "customMetadata": { + "test": 11 + } + }""" + ) resp = self.client.update_file_details( file_id=self.file_id, options=UpdateFileRequestOptions( @@ -1289,59 +1223,61 @@ def test_update_file_details_succeeds_with_id(self): tags=["tag1", "tag2"], custom_coordinates="10,10,100,100", custom_metadata={"test": 11}, - ), + ) ) mock_response_metadata = { - "raw": { - "type": "file", - "name": "default-image.jpg", - "createdAt": "2022-07-21T10:31:22.529Z", - "updatedAt": "2022-07-21T10:37:11.848Z", - "fileId": "fake_123", - "tags": ["tag1", "tag2"], - "AITags": [ - { - "name": "Corridor", - "confidence": 99.39, - "source": "aws-auto-tagging", - }, - { - "name": "Floor", - "confidence": 97.59, - "source": "aws-auto-tagging", - }, - ], - "versionInfo": {"id": "versionId", "name": "Version 2"}, - "embeddedMetadata": { - "XResolution": 1, - "YResolution": 1, - "DateCreated": "2022-07-21T10:35:34.497Z", - "DateTimeCreated": "2022-07-21T10:35:34.500Z", + 'headers': { + 'Content-Type': 'text/plain, application/json', + 'Authorization': 'Basic ZmFrZTEyMjo=' + }, + 'http_status_code': 200, + 'raw': { + 'AITags': [{ + 'confidence': 99.39, + 'name': 'Corridor', + 'source': 'aws-auto-tagging' + }, { + 'confidence': 97.59, + 'name': 'Floor', + 'source': 'aws-auto-tagging' + }], + 'createdAt': '2022-07-21T10:31:22.529Z', + 'customCoordinates': '10,10,100,100', + 'customMetadata': { + 'test': 11 }, - "customCoordinates": "10,10,100,100", - "customMetadata": {"test": 11}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your_imagekit_id/default-image.jpg", - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/default-image.jpg", - "fileType": "image", - "filePath": "/default-image.jpg", - "height": 1000, - "width": 1000, - "size": 184425, - "hasAlpha": False, - "mime": "image/jpeg", - "extensionStatus": { - "remove-bg": "pending", - "google-auto-tagging": "success", + 'embeddedMetadata': { + 'DateCreated': '2022-07-21T10:35:34.497Z', + 'DateTimeCreated': '2022-07-21T10:35:34.500Z', + 'XResolution': 1, + 'YResolution': 1 }, - }, - "httpStatusCode": 200, - "headers": { - "Content-Type": "text/plain, application/json", - "Authorization": "Basic ZmFrZTEyMjo=", - }, + 'extensionStatus': { + 'google-auto-tagging': 'success', + 'remove-bg': 'pending' + }, + 'fileId': 'fake_123', + 'filePath': '/default-image.jpg', + 'fileType': 'image', + 'hasAlpha': False, + 'height': 1000, + 'isPrivateFile': False, + 'mime': 'image/jpeg', + 'name': 'default-image.jpg', + 'size': 184425, + 'tags': ['tag1', 'tag2'], + 'thumbnail': 'https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/default-image.jpg', + 'type': 'file', + 'updatedAt': '2022-07-21T10:37:11.848Z', + 'url': 'https://ik.imagekit.io/your_imagekit_id/default-image.jpg', + 'versionInfo': { + 'id': 'versionId', + 'name': 'Version 2' + }, + 'width': 1000 + } } - self.assertEqual(json.dumps(request_body), responses.calls[0].request.body) + self.assertEqual(request_body, responses.calls[0].request.body) self.assertEqual( camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__, @@ -1362,28 +1298,9 @@ def test_update_file_details_fails_with_404_exception(self) -> None: responses.PATCH, url, status=404, - body=json.dumps( - { - "message": "The requested file does not exist.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "The requested file does not exist.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) - - # request_body = { - # "removeAITags": ["ai-tag1", "ai-tag2"], - # "webhookUrl": "url", - # "extensions": [ - # { - # "name": "remove-bg", - # "options": {"add_shadow": True, "bg_color": "red"}, - # }, - # {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}, - # ], - # "tags": ["tag1", "tag2"], - # "customCoordinates": "10,10,100,100", - # "customMetadata": {"test": 11}, - # } self.client.update_file_details( file_id=self.file_id, options=UpdateFileRequestOptions( @@ -1434,12 +1351,8 @@ def test_get_file_versions_fails_on_unauthenticated_request(self): responses.GET, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.get_file_versions(self.file_id) self.assertRaises(ForbiddenException) @@ -1460,211 +1373,203 @@ def test_get_file_versions_succeeds_with_id(self): responses.add( responses.GET, url, - body=json.dumps( - [ - { - "type": "file", - "name": "new_car.jpg", - "createdAt": "2022-06-15T11:34:36.294Z", - "updatedAt": "2022-07-04T10:15:50.067Z", - "fileId": "fake_123", - "tags": ["Tag_1", "Tag_2", "Tag_3"], - "AITags": [ - { - "name": "Clothing", - "confidence": 98.77, - "source": "google-auto-tagging", - }, - { - "name": "Smile", - "confidence": 95.31, - "source": "google-auto-tagging", - }, - { - "name": "Shoe", - "confidence": 95.2, - "source": "google-auto-tagging", - }, - ], - "versionInfo": {"id": "versionId", "name": "Version 4"}, - "embeddedMetadata": { - "DateCreated": "2022-07-04T10:15:50.066Z", - "DateTimeCreated": "2022-07-04T10:15:50.066Z", - }, - "customCoordinates": None, - "customMetadata": {"test100": 10, "test10": 11}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your_imagekit_id/new_car.jpg", - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg", - "fileType": "image", - "filePath": "/new_car.jpg", - "height": 354, - "width": 236, - "size": 7390, - "hasAlpha": False, - "mime": "image/jpeg", - }, - { - "type": "file-version", - "name": "new_car.jpg", - "createdAt": "2022-07-04T10:15:49.698Z", - "updatedAt": "2022-07-04T10:15:49.734Z", - "fileId": "fileId", - "tags": ["Tag_1", "Tag_2", "Tag_3"], - "AITags": [ - { - "name": "Clothing", - "confidence": 98.77, - "source": "google-auto-tagging", - }, - { - "name": "Smile", - "confidence": 95.31, - "source": "google-auto-tagging", - }, - { - "name": "Shoe", - "confidence": 95.2, - "source": "google-auto-tagging", - }, - { - "name": "Street light", - "confidence": 91.05, - "source": "google-auto-tagging", - }, - ], - "versionInfo": { - "id": "62c2bdd5872375c6b8f40fd4", - "name": "Version 1", - }, - "embeddedMetadata": { - "XResolution": 250, - "YResolution": 250, - "DateCreated": "2022-06-15T11:34:36.702Z", - "DateTimeCreated": "2022-06-15T11:34:36.702Z", - }, - "customCoordinates": "10,10,40,40", - "customMetadata": {"test100": 10, "test10": 11}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your_imagekit_id/new_car.jpg?ik-obj-version" - "=dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz", - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version" - "=dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz", - "fileType": "image", - "filePath": "/new_car.jpg", - "height": 354, - "width": 236, - "size": 23023, - "hasAlpha": False, - "mime": "image/jpeg", - }, - ] - ), + body="""[{ + "type": "file", + "name": "new_car.jpg", + "createdAt": "2022-06-15T11:34:36.294Z", + "updatedAt": "2022-07-04T10:15:50.067Z", + "fileId": "fake_123", + "tags": ["Tag_1", "Tag_2", "Tag_3"], + "AITags": [{ + "name": "Clothing", + "confidence": 98.77, + "source": "google-auto-tagging" + }, { + "name": "Smile", + "confidence": 95.31, + "source": "google-auto-tagging" + }, { + "name": "Shoe", + "confidence": 95.2, + "source": "google-auto-tagging" + }], + "versionInfo": { + "id": "versionId", + "name": "Version 4" + }, + "embeddedMetadata": { + "DateCreated": "2022-07-04T10:15:50.066Z", + "DateTimeCreated": "2022-07-04T10:15:50.066Z" + }, + "customCoordinates": "", + "customMetadata": { + "test100": 10, + "test10": 11 + }, + "isPrivateFile": false, + "url": "https://ik.imagekit.io/your_imagekit_id/new_car.jpg", + "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg", + "fileType": "image", + "filePath": "/new_car.jpg", + "height": 354, + "width": 236, + "size": 7390, + "hasAlpha": false, + "mime": "image/jpeg" + }, { + "type": "file-version", + "name": "new_car.jpg", + "createdAt": "2022-07-04T10:15:49.698Z", + "updatedAt": "2022-07-04T10:15:49.734Z", + "fileId": "fileId", + "tags": ["Tag_1", "Tag_2", "Tag_3"], + "AITags": [{ + "name": "Clothing", + "confidence": 98.77, + "source": "google-auto-tagging" + }, { + "name": "Smile", + "confidence": 95.31, + "source": "google-auto-tagging" + }, { + "name": "Shoe", + "confidence": 95.2, + "source": "google-auto-tagging" + }, { + "name": "Street light", + "confidence": 91.05, + "source": "google-auto-tagging" + }], + "versionInfo": { + "id": "62c2bdd5872375c6b8f40fd4", + "name": "Version 1" + }, + "embeddedMetadata": { + "XResolution": 250, + "YResolution": 250, + "DateCreated": "2022-06-15T11:34:36.702Z", + "DateTimeCreated": "2022-06-15T11:34:36.702Z" + }, + "customCoordinates": "10,10,40,40", + "customMetadata": { + "test100": 10, + "test10": 11 + }, + "isPrivateFile": false, + "url": "https://ik.imagekit.io/your_imagekit_id/new_car.jpg?ik-obj-version =dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz", + "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version =dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz", + "fileType": "image", + "filePath": "/new_car.jpg", + "height": 354, + "width": 236, + "size": 23023, + "hasAlpha": false, + "mime": "image/jpeg" + }]""", headers=headers, ) resp = self.client.get_file_versions(self.file_id) mock_response_metadata = { - "raw": [ - { - "type": "file", - "name": "new_car.jpg", - "createdAt": "2022-06-15T11:34:36.294Z", - "updatedAt": "2022-07-04T10:15:50.067Z", - "fileId": "fake_123", - "tags": ["Tag_1", "Tag_2", "Tag_3"], - "AITags": [ - { - "name": "Clothing", - "confidence": 98.77, - "source": "google-auto-tagging", - }, - { - "name": "Smile", - "confidence": 95.31, - "source": "google-auto-tagging", - }, - { - "name": "Shoe", - "confidence": 95.2, - "source": "google-auto-tagging", - }, - ], - "versionInfo": {"id": "versionId", "name": "Version 4"}, - "embeddedMetadata": { - "DateCreated": "2022-07-04T10:15:50.066Z", - "DateTimeCreated": "2022-07-04T10:15:50.066Z", - }, - "customCoordinates": None, - "customMetadata": {"test100": 10, "test10": 11}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your_imagekit_id/new_car.jpg", - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg", - "fileType": "image", - "filePath": "/new_car.jpg", - "height": 354, - "width": 236, - "size": 7390, - "hasAlpha": False, - "mime": "image/jpeg", + 'headers': { + 'Content-Type': 'text/plain, application/json', + 'Authorization': 'Basic ZmFrZTEyMjo=' + }, + 'http_status_code': 200, + 'raw': [{ + 'AITags': [{ + 'confidence': 98.77, + 'name': 'Clothing', + 'source': 'google-auto-tagging' + }, { + 'confidence': 95.31, + 'name': 'Smile', + 'source': 'google-auto-tagging' + }, { + 'confidence': 95.2, + 'name': 'Shoe', + 'source': 'google-auto-tagging' + }], + 'createdAt': '2022-06-15T11:34:36.294Z', + 'customCoordinates': '', + 'customMetadata': { + 'test10': 11, + 'test100': 10 }, - { - "type": "file-version", - "name": "new_car.jpg", - "createdAt": "2022-07-04T10:15:49.698Z", - "updatedAt": "2022-07-04T10:15:49.734Z", - "fileId": "fileId", - "tags": ["Tag_1", "Tag_2", "Tag_3"], - "AITags": [ - { - "name": "Clothing", - "confidence": 98.77, - "source": "google-auto-tagging", - }, - { - "name": "Smile", - "confidence": 95.31, - "source": "google-auto-tagging", - }, - { - "name": "Shoe", - "confidence": 95.2, - "source": "google-auto-tagging", - }, - { - "name": "Street light", - "confidence": 91.05, - "source": "google-auto-tagging", - }, - ], - "versionInfo": { - "id": "62c2bdd5872375c6b8f40fd4", - "name": "Version 1", - }, - "embeddedMetadata": { - "XResolution": 250, - "YResolution": 250, - "DateCreated": "2022-06-15T11:34:36.702Z", - "DateTimeCreated": "2022-06-15T11:34:36.702Z", - }, - "customCoordinates": "10,10,40,40", - "customMetadata": {"test100": 10, "test10": 11}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your_imagekit_id/new_car.jpg?ik-obj-version=dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz", - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version=dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz", - "fileType": "image", - "filePath": "/new_car.jpg", - "height": 354, - "width": 236, - "size": 23023, - "hasAlpha": False, - "mime": "image/jpeg", + 'embeddedMetadata': { + 'DateCreated': '2022-07-04T10:15:50.066Z', + 'DateTimeCreated': '2022-07-04T10:15:50.066Z' }, - ], - "httpStatusCode": 200, - "headers": { - "Content-Type": "text/plain, application/json", - "Authorization": "Basic ZmFrZTEyMjo=", - }, + 'fileId': 'fake_123', + 'filePath': '/new_car.jpg', + 'fileType': 'image', + 'hasAlpha': False, + 'height': 354, + 'isPrivateFile': False, + 'mime': 'image/jpeg', + 'name': 'new_car.jpg', + 'size': 7390, + 'tags': ['Tag_1', 'Tag_2', 'Tag_3'], + 'thumbnail': 'https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg', + 'type': 'file', + 'updatedAt': '2022-07-04T10:15:50.067Z', + 'url': 'https://ik.imagekit.io/your_imagekit_id/new_car.jpg', + 'versionInfo': { + 'id': 'versionId', + 'name': 'Version 4' + }, + 'width': 236 + }, { + 'AITags': [{ + 'confidence': 98.77, + 'name': 'Clothing', + 'source': 'google-auto-tagging' + }, { + 'confidence': 95.31, + 'name': 'Smile', + 'source': 'google-auto-tagging' + }, { + 'confidence': 95.2, + 'name': 'Shoe', + 'source': 'google-auto-tagging' + }, { + 'confidence': 91.05, + 'name': 'Street light', + 'source': 'google-auto-tagging' + }], + 'createdAt': '2022-07-04T10:15:49.698Z', + 'customCoordinates': '10,10,40,40', + 'customMetadata': { + 'test10': 11, + 'test100': 10 + }, + 'embeddedMetadata': { + 'DateCreated': '2022-06-15T11:34:36.702Z', + 'DateTimeCreated': '2022-06-15T11:34:36.702Z', + 'XResolution': 250, + 'YResolution': 250 + }, + 'fileId': 'fileId', + 'filePath': '/new_car.jpg', + 'fileType': 'image', + 'hasAlpha': False, + 'height': 354, + 'isPrivateFile': False, + 'mime': 'image/jpeg', + 'name': 'new_car.jpg', + 'size': 23023, + 'tags': ['Tag_1', 'Tag_2', 'Tag_3'], + 'thumbnail': 'https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version ' + '=dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz', + 'type': 'file-version', + 'updatedAt': '2022-07-04T10:15:49.734Z', + 'url': 'https://ik.imagekit.io/your_imagekit_id/new_car.jpg?ik-obj-version ' + '=dlkUlhiJ7I8OTejhKG38GZJBrsvDBcnz', + 'versionInfo': { + 'id': '62c2bdd5872375c6b8f40fd4', + 'name': 'Version 1' + }, + 'width': 236 + }] } self.assertEqual( @@ -1688,12 +1593,8 @@ def test_get_file_versions_fails_with_404_exception(self) -> None: responses.GET, url, status=404, - body=json.dumps( - { - "message": "The requested asset does not exist.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "The requested asset does not exist.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.get_file_versions(self.file_id) self.assertRaises(NotFoundException) @@ -1715,12 +1616,8 @@ def test_get_file_version_details_fails_on_unauthenticated_request(self): responses.GET, url, status=403, - body=json.dumps( - { - "message": "Your account cannot be authenticated.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.get_file_version_details(self.file_id, self.version_id) self.assertRaises(ForbiddenException) @@ -1743,73 +1640,81 @@ def test_get_file_version_details_succeeds_with_id(self): responses.add( responses.GET, url, - body=json.dumps( - { - "type": "file-version", - "name": "new_car.jpg", - "createdAt": "2022-06-27T09:24:25.251Z", - "updatedAt": "2022-06-27T12:11:11.247Z", - "fileId": "fake_123", - "tags": ["tagg", "tagg1"], - "AITags": None, - "versionInfo": {"id": "fake_version_123", "name": "Version 1"}, - "embeddedMetadata": { - "XResolution": 250, - "YResolution": 250, - "DateCreated": "2022-06-15T11:34:36.702Z", - "DateTimeCreated": "2022-06-15T11:34:36.702Z", - }, - "customCoordinates": "10,10,20,20", - "customMetadata": {"test100": 10}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your-imagekit-id/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH", - "thumbnail": "https://ik.imagekit.io/your-imagekit-id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH", - "fileType": "image", - "filePath": "/new_car.jpg", - "height": 354, - "width": 236, - "size": 23023, - "hasAlpha": False, - "mime": "image/jpeg", - } - ), + body="""{ + "type": "file-version", + "name": "new_car.jpg", + "createdAt": "2022-06-27T09:24:25.251Z", + "updatedAt": "2022-06-27T12:11:11.247Z", + "fileId": "fake_123", + "tags": ["tagg", "tagg1"], + "AITags": "", + "versionInfo": { + "id": "fake_version_123", + "name": "Version 1" + }, + "embeddedMetadata": { + "XResolution": 250, + "YResolution": 250, + "DateCreated": "2022-06-15T11:34:36.702Z", + "DateTimeCreated": "2022-06-15T11:34:36.702Z" + }, + "customCoordinates": "10,10,20,20", + "customMetadata": { + "test100": 10 + }, + "isPrivateFile": false, + "url": "https://ik.imagekit.io/your-imagekit-id/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH", + "thumbnail": "https://ik.imagekit.io/your-imagekit-id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH", + "fileType": "image", + "filePath": "/new_car.jpg", + "height": 354, + "width": 236, + "size": 23023, + "hasAlpha": false, + "mime": "image/jpeg" + }""", headers=headers, ) resp = self.client.get_file_version_details(self.file_id, self.version_id) mock_response_metadata = { - "raw": { - "type": "file-version", - "name": "new_car.jpg", - "createdAt": "2022-06-27T09:24:25.251Z", - "updatedAt": "2022-06-27T12:11:11.247Z", - "fileId": "fake_123", - "tags": ["tagg", "tagg1"], - "AITags": None, - "versionInfo": {"id": "fake_version_123", "name": "Version 1"}, - "embeddedMetadata": { - "XResolution": 250, - "YResolution": 250, - "DateCreated": "2022-06-15T11:34:36.702Z", - "DateTimeCreated": "2022-06-15T11:34:36.702Z", - }, - "customCoordinates": "10,10,20,20", - "customMetadata": {"test100": 10}, - "isPrivateFile": False, - "url": "https://ik.imagekit.io/your-imagekit-id/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH", - "thumbnail": "https://ik.imagekit.io/your-imagekit-id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH", - "fileType": "image", - "filePath": "/new_car.jpg", - "height": 354, - "width": 236, - "size": 23023, - "hasAlpha": False, - "mime": "image/jpeg", - }, - "httpStatusCode": 200, - "headers": { - "Content-Type": "text/plain, application/json", - "Authorization": "Basic ZmFrZTEyMjo=", + 'headers': { + 'Content-Type': 'text/plain, application/json', + 'Authorization': 'Basic ZmFrZTEyMjo=' }, + 'http_status_code': 200, + 'raw': { + 'AITags': '', + 'createdAt': '2022-06-27T09:24:25.251Z', + 'customCoordinates': '10,10,20,20', + 'customMetadata': { + 'test100': 10 + }, + 'embeddedMetadata': { + 'DateCreated': '2022-06-15T11:34:36.702Z', + 'DateTimeCreated': '2022-06-15T11:34:36.702Z', + 'XResolution': 250, + 'YResolution': 250 + }, + 'fileId': 'fake_123', + 'filePath': '/new_car.jpg', + 'fileType': 'image', + 'hasAlpha': False, + 'height': 354, + 'isPrivateFile': False, + 'mime': 'image/jpeg', + 'name': 'new_car.jpg', + 'size': 23023, + 'tags': ['tagg', 'tagg1'], + 'thumbnail': 'https://ik.imagekit.io/your-imagekit-id/tr:n-ik_ml_thumbnail/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH', + 'type': 'file-version', + 'updatedAt': '2022-06-27T12:11:11.247Z', + 'url': 'https://ik.imagekit.io/your-imagekit-id/new_car.jpg?ik-obj-version=hzBNRjaJhZYg.JNu75L2nMDfhjJP4tJH', + 'versionInfo': { + 'id': 'fake_version_123', + 'name': 'Version 1' + }, + 'width': 236 + } } self.assertEqual( @@ -1836,12 +1741,8 @@ def test_get_file_version_details_fails_with_404_exception(self) -> None: responses.GET, url, status=404, - body=json.dumps( - { - "message": "The requested asset does not exist.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "The requested asset does not exist.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.get_file_version_details(self.file_id, self.version_id) self.assertRaises(NotFoundException) @@ -1862,12 +1763,8 @@ def test_get_file_version_details_fails_with_400_exception(self) -> None: responses.GET, url, status=400, - body=json.dumps( - { - "message": "Your request contains invalid fileId parameter.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "Your request contains invalid fileId parameter.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.get_file_version_details(self.file_id, self.version_id) self.assertRaises(BadRequestException) @@ -1895,12 +1792,8 @@ def test_delete_file_version_fails_with_404_exception(self) -> None: responses.DELETE, url, status=404, - body=json.dumps( - { - "message": "The requested file version does not exist.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "The requested file version does not exist.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.delete_file_version(self.file_id, self.version_id) self.assertRaises(NotFoundException) @@ -1918,9 +1811,7 @@ def test_delete_file_version_succeeds(self) -> None: ) headers = {"Content-Type": "application/json"} headers.update(create_headers_for_test()) - responses.add( - responses.DELETE, url, status=204, headers=headers, body=json.dumps({}) - ) + responses.add(responses.DELETE, url, status=204, headers=headers, body="{}") resp = self.client.delete_file_version(self.file_id, self.version_id) mock_response_metadata = { @@ -1961,13 +1852,11 @@ def test_copy_file_fails_with_404(self) -> None: url, status=404, headers=headers, - body=json.dumps( - { - "message": "No file found with filePath /source_file.jpg", - "help": "For support kindly contact us at support@imagekit.io .", - "reason": "SOURCE_FILE_MISSING", - } - ), + body="""{ + "message": "No file found with filePath /source_file.jpg", + "help": "For support kindly contact us at support@imagekit.io .", + "reason": "SOURCE_FILE_MISSING" + }""", ) try: self.client.copy_file( @@ -1990,16 +1879,14 @@ def test_copy_file_succeeds(self) -> None: url = "{}/v1/files/copy".format(URL.API_BASE_URL) headers = {"Content-Type": "application/json"} headers.update(create_headers_for_test()) - responses.add( - responses.POST, url, status=204, headers=headers, body=json.dumps({}) - ) + responses.add(responses.POST, url, status=204, headers=headers, body="{}") + resp = self.client.copy_file( options=CopyFileRequestOptions( source_file_path=self.source_file_path, destination_path=self.destination_path, include_file_versions=True, - ) - ) + )) mock_response_metadata = { "headers": { @@ -2011,12 +1898,12 @@ def test_copy_file_succeeds(self) -> None: "raw": None, } - request_body = json.dumps( - { - "sourceFilePath": "/source_file.jpg", - "destinationPath": "/destination_path", - "includeFileVersions": True, - } + request_body = make_string_to_single_line( + """{ + "sourceFilePath": "/source_file.jpg", + "destinationPath": "/destination_path", + "includeFileVersions": true + }""" ) self.assertEqual(request_body, responses.calls[0].request.body) @@ -2047,13 +1934,11 @@ def test_move_file_fails_with_404(self) -> None: url, status=404, headers=headers, - body=json.dumps( - { - "message": "No file found with filePath /source_file.jpg", - "help": "For support kindly contact us at support@imagekit.io .", - "reason": "SOURCE_FILE_MISSING", - } - ), + body="""{ + "message": "No file found with filePath /source_file.jpg", + "help": "For support kindly contact us at support@imagekit.io .", + "reason": "SOURCE_FILE_MISSING" + }""", ) try: self.client.move_file( @@ -2075,16 +1960,13 @@ def test_move_file_succeeds(self) -> None: url = "{}/v1/files/move".format(URL.API_BASE_URL) headers = {"Content-Type": "application/json"} headers.update(create_headers_for_test()) - responses.add( - responses.POST, url, status=204, headers=headers, body=json.dumps({}) - ) + responses.add(responses.POST, url, status=204, headers=headers, body="{}") + resp = self.client.move_file( options=MoveFileRequestOptions( source_file_path=self.source_file_path, destination_path=self.destination_path, - ) - ) - + )) mock_response_metadata = { "headers": { "Content-Type": "text/plain, application/json", @@ -2095,11 +1977,11 @@ def test_move_file_succeeds(self) -> None: "raw": None, } - request_body = json.dumps( - { - "sourceFilePath": "/source_file.jpg", - "destinationPath": "/destination_path", - } + request_body = make_string_to_single_line( + """{ + "sourceFilePath": "/source_file.jpg", + "destinationPath": "/destination_path" + }""" ) self.assertEqual(request_body, responses.calls[0].request.body) @@ -2131,19 +2013,16 @@ def test_rename_file_fails_with_409(self) -> None: url, status=409, headers=headers, - body=json.dumps( - { - "message": "File with name testing-binary.jpg already exists at the same location.", - "help": "For support kindly contact us at support@imagekit.io .", - "reason": "FILE_ALREADY_EXISTS", - } - ), + body="""{ + "message": "File with name testing-binary.jpg already exists at the same location.", + "help": "For support kindly contact us at support@imagekit.io .", + "reason": "FILE_ALREADY_EXISTS" + }""", ) self.client.rename_file( options=RenameFileRequestOptions( file_path=self.file_path, new_file_name=self.new_file_name - ) - ) + )) self.assertRaises(ConflictException) except ConflictException as e: self.assertEqual( @@ -2165,15 +2044,14 @@ def test_rename_file_succeeds_with_purge_cache(self) -> None: responses.PUT, url, headers=headers, - body=json.dumps({"purgeRequestId": "62de3e986f68334a5a3339fb"}), + body='{"purgeRequestId": "62de3e986f68334a5a3339fb"}', ) resp = self.client.rename_file( options=RenameFileRequestOptions( file_path=self.file_path, new_file_name=self.new_file_name, purge_cache=True, - ) - ) + )) mock_response_metadata = { "headers": { @@ -2185,12 +2063,12 @@ def test_rename_file_succeeds_with_purge_cache(self) -> None: "raw": {"purgeRequestId": "62de3e986f68334a5a3339fb"}, } - request_body = json.dumps( - { - "filePath": "/file_path.jpg", - "newFileName": "new_file.jpg", - "purgeCache": True, - } + request_body = make_string_to_single_line( + """{ + "filePath": "/file_path.jpg", + "newFileName": "new_file.jpg", + "purgeCache": true + }""" ) self.assertEqual(request_body, responses.calls[0].request.body) @@ -2211,13 +2089,11 @@ def test_rename_file_succeeds(self) -> None: url = "{}/v1/files/rename".format(URL.API_BASE_URL) headers = {"Content-Type": "application/json"} headers.update(create_headers_for_test()) - responses.add(responses.PUT, url, headers=headers, body=json.dumps({})) + responses.add(responses.PUT, url, headers=headers, body="{}") resp = self.client.rename_file( options=RenameFileRequestOptions( file_path=self.file_path, new_file_name=self.new_file_name - ) - ) - + )) mock_response_metadata = { "headers": { "Content-Type": "text/plain, application/json", @@ -2228,8 +2104,11 @@ def test_rename_file_succeeds(self) -> None: "raw": {}, } - request_body = json.dumps( - {"filePath": "/file_path.jpg", "newFileName": "new_file.jpg"} + request_body = make_string_to_single_line( + """{ + "filePath": "/file_path.jpg", + "newFileName": "new_file.jpg" + }""" ) self.assertEqual(request_body, responses.calls[0].request.body) @@ -2260,12 +2139,8 @@ def test_restore_file_version_fails_with_404_exception(self) -> None: responses.PUT, url, status=404, - body=json.dumps( - { - "message": "The requested file version does not exist.", - "help": "For support kindly contact us at support@imagekit.io .", - } - ), + body="""{"message": "The requested file version does not exist.", + "help": "For support kindly contact us at support@imagekit.io ."}""", ) self.client.restore_file_version(self.file_id, self.version_id) self.assertRaises(NotFoundException) @@ -2287,74 +2162,80 @@ def test_restore_file_version_succeeds(self) -> None: responses.PUT, url, headers=headers, - body=json.dumps( - { - "fileId": "fileId", - "type": "file", - "name": "file1.jpg", - "filePath": "/images/file.jpg", - "tags": ["t-shirt", "round-neck", "sale2019"], - "AITags": [ - { - "name": "Shirt", - "confidence": 90.12, - "source": "google-auto-tagging", - }, - ], - "versionInfo": {"id": "versionId", "name": "Version 2"}, - "isPrivateFile": False, - "customCoordinates": None, - "url": "https://ik.imagekit.io/your_imagekit_id/images/products/file1.jpg", - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-media_library_thumbnail/images/products/file1.jpg", - "fileType": "image", - "mime": "image/jpeg", - "width": 100, - "height": 100, - "size": 100, - "hasAlpha": False, - "customMetadata": {"brand": "Nike", "color": "red"}, - "createdAt": "2019-08-24T06:14:41.313Z", - "updatedAt": "2019-09-24T06:14:41.313Z", - } - ), - ) - resp = self.client.restore_file_version(self.file_id, self.version_id) - - mock_response_metadata = { - "headers": { - "Content-Type": "text/plain, application/json", - "Accept-Encoding": "gzip, deflate", - "Authorization": "Basic ZmFrZTEyMjo=", - }, - "httpStatusCode": 200, - "raw": { + body="""{ + "fileId": "fileId", + "type": "file", + "name": "file1.jpg", + "filePath": "/images/file.jpg", + "tags": ["t-shirt", "round-neck", "sale2019"], "AITags": [ { "confidence": 90.12, - "name": "Shirt", - "source": "google-auto-tagging", - } - ], - "createdAt": "2019-08-24T06:14:41.313Z", - "customCoordinates": None, - "customMetadata": {"brand": "Nike", "color": "red"}, - "fileId": "fileId", - "filePath": "/images/file.jpg", + "source": "google-auto-tagging" + }], + "versionInfo": { + "id": "versionId", + "name": "Version 2" + }, + "isPrivateFile": false, + "customCoordinates": "", + "url": "https://ik.imagekit.io/your_imagekit_id/images/products/file1.jpg", + "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-media_library_thumbnail/images/products/file1.jpg", "fileType": "image", - "hasAlpha": False, + "hasAlpha": false, "height": 100, - "isPrivateFile": False, + "isPrivateFile": false, "mime": "image/jpeg", "name": "file1.jpg", "size": 100, - "tags": ["t-shirt", "round-neck", "sale2019"], - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-media_library_thumbnail/images/products/file1.jpg", - "type": "file", - "updatedAt": "2019-09-24T06:14:41.313Z", - "url": "https://ik.imagekit.io/your_imagekit_id/images/products/file1.jpg", - "versionInfo": {"id": "versionId", "name": "Version " "2"}, - "width": 100, + "hasAlpha": false, + "customMetadata": { + "brand": "Nike", + "color": "red" + }, + "createdAt": "2019-08-24T06:14:41.313Z", + "updatedAt": "2019-09-24T06:14:41.313Z" + }""", + ) + resp = self.client.restore_file_version(self.file_id, self.version_id) + + mock_response_metadata = { + 'headers': { + 'Content-Type': 'text/plain, application/json', + 'Accept-Encoding': 'gzip, deflate', + 'Authorization': 'Basic ZmFrZTEyMjo=' }, + 'http_status_code': 200, + 'raw': { + 'AITags': [{ + 'confidence': 90.12, + 'source': 'google-auto-tagging' + }], + 'createdAt': '2019-08-24T06:14:41.313Z', + 'customCoordinates': '', + 'customMetadata': { + 'brand': 'Nike', + 'color': 'red' + }, + 'fileId': 'fileId', + 'filePath': '/images/file.jpg', + 'fileType': 'image', + 'hasAlpha': False, + 'height': 100, + 'isPrivateFile': False, + 'mime': 'image/jpeg', + 'name': 'file1.jpg', + 'size': 100, + 'tags': ['t-shirt', 'round-neck', 'sale2019'], + 'thumbnail': 'https://ik.imagekit.io/your_imagekit_id/tr:n-media_library_thumbnail/images/products/file1.jpg', + 'type': 'file', + 'updatedAt': '2019-09-24T06:14:41.313Z', + 'url': 'https://ik.imagekit.io/your_imagekit_id/images/products/file1.jpg', + 'versionInfo': { + 'id': 'versionId', + 'name': 'Version 2' + } + } } self.assertEqual( diff --git a/tests/test_folder_ops.py b/tests/test_folder_ops.py index b77a2f5..99cdfe4 100644 --- a/tests/test_folder_ops.py +++ b/tests/test_folder_ops.py @@ -1,5 +1,3 @@ -import json - import responses from imagekitio import ImageKit @@ -14,7 +12,7 @@ from imagekitio.models.DeleteFolderRequestOptions import DeleteFolderRequestOptions from imagekitio.models.MoveFolderRequestOptions import MoveFolderRequestOptions from imagekitio.utils.formatter import camel_dict_to_snake_dict -from tests.helpers import ClientTestCase, create_headers_for_test +from tests.helpers import ClientTestCase, create_headers_for_test, make_string_to_single_line imagekit_obj = ImageKit( private_key="private_fake:", public_key="public_fake123:", url_endpoint="fake.com", @@ -38,8 +36,8 @@ def test_create_folder_fails_on_unauthenticated_request(self): responses.POST, url, status=403, - body=json.dumps({'message': 'Your account cannot be authenticated.' - , 'help': 'For support kindly contact us at support@imagekit.io .'}), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.create_folder( options=CreateFolderRequestOptions(folder_name="folder_name", parent_folder_path="/test")) @@ -60,7 +58,7 @@ def test_create_folder_succeeds(self): responses.POST, url, status=201, - body=json.dumps({}), + body="{}", headers=headers ) resp = self.client.create_folder( @@ -92,8 +90,8 @@ def test_create_folder_fails_with_400(self): responses.POST, url, status=400, - body=json.dumps({"message": "folderName parameter cannot have a slash.", - "help": "For support kindly contact us at support@imagekit.io ."}), + body='''{"message": "folderName parameter cannot have a slash.", + "help": "For support kindly contact us at support@imagekit.io ."}''', ) self.client.create_folder( options=CreateFolderRequestOptions(folder_name="folder_name", parent_folder_path="/test")) @@ -114,11 +112,11 @@ def test_delete_folder_fails_with_400(self): responses.DELETE, url, status=404, - body=json.dumps({ + body='''{ "message": "No folder found with folderPath test", "help": "For support kindly contact us at support@imagekit.io .", "reason": "FOLDER_NOT_FOUND" - }), + }''', ) self.client.delete_folder(options=DeleteFolderRequestOptions(folder_path="/test")) self.assertRaises(NotFoundException) @@ -138,7 +136,7 @@ def test_delete_folder_succeeds(self): responses.DELETE, url, status=204, - body=json.dumps({}), + body="{}", ) resp = self.client.delete_folder(options=DeleteFolderRequestOptions(folder_path="/folderName")) mock_response_metadata = { @@ -170,10 +168,10 @@ def test_copy_folder_fails_with_400(self): responses.POST, url, status=400, - body=json.dumps({ + body='''{ "message": "sourceFolderPath and destinationPath cannot be same.", "help": "For support kindly contact us at support@imagekit.io ." - }), + }''', ) self.client.copy_folder(options=CopyFolderRequestOptions(source_folder_path="/test", destination_path="/test", @@ -195,11 +193,11 @@ def test_copy_folder_fails_with_404(self): responses.POST, url, status=404, - body=json.dumps({ + body='''{ "message": "No files & folder found at sourceFolderPath /test", "help": "For support kindly contact us at support@imagekit.io .", "reason": "NO_FILES_FOLDER" - }), + }''', ) self.client.copy_folder(options=CopyFolderRequestOptions(source_folder_path="/test", destination_path="/test1", @@ -220,7 +218,7 @@ def test_copy_folder_succeeds(self): responses.add( responses.POST, url, - body=json.dumps({"jobId": "62de84fb1b02a58936cc740c"}), + body='{"jobId": "62de84fb1b02a58936cc740c"}', ) resp = self.client.copy_folder( options=CopyFolderRequestOptions(source_folder_path="/test", @@ -235,11 +233,11 @@ def test_copy_folder_succeeds(self): 'jobId': '62de84fb1b02a58936cc740c' } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "sourceFolderPath": "/test", "destinationPath": "/test1", - "includeFileVersions": True - }) + "includeFileVersions": true + }''') self.assertEqual('62de84fb1b02a58936cc740c', resp.job_id) self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/bulkJobs/copyFolder", responses.calls[0].request.url) @@ -263,8 +261,8 @@ def test_move_folder_fails_on_unauthenticated_request(self): responses.POST, url, status=403, - body=json.dumps({'message': 'Your account cannot be authenticated.' - , 'help': 'For support kindly contact us at support@imagekit.io .'}), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.move_folder(options=MoveFolderRequestOptions(source_folder_path="/test", destination_path="/test1")) @@ -285,10 +283,10 @@ def test_move_folder_fails_with_400(self): responses.POST, url, status=400, - body=json.dumps({ + body='''{ "message": "sourceFolderPath and destinationPath cannot be same.", "help": "For support kindly contact us at support@imagekit.io ." - }), + }''', ) self.client.move_folder(options=MoveFolderRequestOptions(source_folder_path="/test", destination_path="/test")) @@ -309,11 +307,11 @@ def test_move_folder_fails_with_404(self): responses.POST, url, status=404, - body=json.dumps({ + body='''{ "message": "No files & folder found at sourceFolderPath /test", "help": "For support kindly contact us at support@imagekit.io .", "reason": "NO_FILES_FOLDER" - }), + }''', ) self.client.move_folder(options=MoveFolderRequestOptions(source_folder_path="/test", destination_path="/test1")) @@ -333,7 +331,7 @@ def test_move_folder_succeeds(self): responses.add( responses.POST, url, - body=json.dumps({"jobId": "62de84fb1b02a58936cc740c"}), + body='{"jobId": "62de84fb1b02a58936cc740c"}', ) resp = self.client.move_folder(options=MoveFolderRequestOptions(source_folder_path="/test", destination_path="/test1")) @@ -346,10 +344,10 @@ def test_move_folder_succeeds(self): 'jobId': '62de84fb1b02a58936cc740c' } } - request_body = json.dumps({ + request_body = make_string_to_single_line('''{ "sourceFolderPath": "/test", "destinationPath": "/test1" - }) + }''') self.assertEqual('62de84fb1b02a58936cc740c', resp.job_id) self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) self.assertEqual("http://test.com/v1/bulkJobs/moveFolder", responses.calls[0].request.url) @@ -375,8 +373,8 @@ def test_get_bulk_job_status_fails_with_500(self): responses.GET, url, status=500, - body=json.dumps({"message": "We have experienced an internal error while processing your request.", - "help": "For support kindly contact us at support@imagekit.io ."}), + body='''{"message": "We have experienced an internal error while processing your request.", + "help": "For support kindly contact us at support@imagekit.io ."}''', ) self.client.get_bulk_job_status(self.job_id) self.assertRaises(InternalServerException) @@ -395,11 +393,11 @@ def test_get_bulk_job_status_succeeds(self): responses.add( responses.GET, url, - body=json.dumps({ + body='''{ "jobId": "mock_job_id", "type": "COPY_FOLDER", "status": "Completed" - }), + }''', headers=headers ) resp = self.client.get_bulk_job_status(self.job_id) diff --git a/tests/test_tags_ops.py b/tests/test_tags_ops.py index a128da0..1dcb441 100644 --- a/tests/test_tags_ops.py +++ b/tests/test_tags_ops.py @@ -1,4 +1,3 @@ -import json import os import responses @@ -9,7 +8,7 @@ from imagekitio.exceptions.NotFoundException import NotFoundException from imagekitio.utils.formatter import camel_dict_to_snake_dict from tests.helpers import ( - ClientTestCase, get_auth_headers_for_test, + ClientTestCase, get_auth_headers_for_test, make_string_to_single_line, ) imagekit_obj = ImageKit( @@ -38,8 +37,8 @@ def test_add_tags_fails_on_unauthenticated_request(self): responses.POST, url, status=403, - body=json.dumps({'message': 'Your account cannot be authenticated.' - , 'help': 'For support kindly contact us at support@imagekit.io .'}), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.add_tags(file_ids=[self.file_id], tags=['add-tag-1', 'add-tag-2']) self.assertRaises(ForbiddenException) @@ -59,27 +58,25 @@ def test_add_tags_succeeds(self): responses.add( responses.POST, url, - body=json.dumps({ - "successfullyUpdatedFileIds": ["fake_123"] - }), + body='{"successfullyUpdatedFileIds": ["fake_123"]}', headers=headers ) resp = self.client.add_tags(file_ids=[self.file_id], tags=['add-tag-1', 'add-tag-2']) mock_response_metadata = { - 'headers': { - 'Content-Type': 'text/plain, application/json', - 'Authorization': 'Basic ZmFrZTEyMjo=' - }, - 'httpStatusCode': 200, - 'raw': { - 'successfullyUpdatedFileIds': ['fake_123'] - } - } - request_body = json.dumps({ + 'headers': { + 'Content-Type': 'text/plain, application/json', + 'Authorization': 'Basic ZmFrZTEyMjo=' + }, + 'httpStatusCode': 200, + 'raw': { + 'successfullyUpdatedFileIds': ['fake_123'] + } + } + request_body = make_string_to_single_line('''{ "fileIds": ["fake_123"], "tags": ["add-tag-1", "add-tag-2"] - }) + }''') self.assertEqual(request_body, responses.calls[0].request.body) self.assertEqual(['fake_123'], resp.successfully_updated_file_ids) self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) @@ -98,11 +95,11 @@ def test_add_tags_fails_with_404_exception(self) -> None: responses.POST, url, status=404, - body=json.dumps({ + body='''{ "message": "The requested file(s) does not exist.", "help": "For support kindly contact us at support@imagekit.io .", "missingFileIds": ["fake_123"] - }), + }''', headers=headers ) self.client.add_tags(file_ids=[self.file_id], tags=['add-tag-1', 'add-tag-2']) @@ -124,8 +121,8 @@ def test_remove_tags_fails_on_unauthenticated_request(self): responses.POST, url, status=403, - body=json.dumps({'message': 'Your account cannot be authenticated.' - , 'help': 'For support kindly contact us at support@imagekit.io .'}), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.remove_tags(file_ids=[self.file_id], tags=['remove-tag-1', 'remove-tag-2']) self.assertRaises(ForbiddenException) @@ -145,27 +142,25 @@ def test_remove_tags_succeeds(self): responses.add( responses.POST, url, - body=json.dumps({ - "successfullyUpdatedFileIds": ["fake_123"] - }), + body='{"successfullyUpdatedFileIds": ["fake_123"]}', headers=headers ) resp = self.client.remove_tags(file_ids=[self.file_id], tags=['remove-tag-1', 'remove-tag-2']) mock_response_metadata = { - 'headers': { - 'Content-Type': 'text/plain, application/json', - 'Authorization': 'Basic ZmFrZTEyMjo=' - }, - 'httpStatusCode': 200, - 'raw': { - 'successfullyUpdatedFileIds': ['fake_123'] - } - } - request_body = json.dumps({ + 'headers': { + 'Content-Type': 'text/plain, application/json', + 'Authorization': 'Basic ZmFrZTEyMjo=' + }, + 'httpStatusCode': 200, + 'raw': { + 'successfullyUpdatedFileIds': ['fake_123'] + } + } + request_body = make_string_to_single_line('''{ "fileIds": ["fake_123"], "tags": ["remove-tag-1", "remove-tag-2"] - }) + }''') self.assertEqual(request_body, responses.calls[0].request.body) self.assertEqual(['fake_123'], resp.successfully_updated_file_ids) self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) @@ -184,11 +179,11 @@ def test_remove_tags_fails_with_404_exception(self) -> None: responses.POST, url, status=404, - body=json.dumps({ + body='''{ "message": "The requested file(s) does not exist.", "help": "For support kindly contact us at support@imagekit.io .", "missingFileIds": ["fake_123"] - }), + }''', headers=headers ) self.client.remove_tags(file_ids=[self.file_id], tags=['remove-tag-1', 'remove-tag-2']) @@ -223,8 +218,8 @@ def test_remove_ai_tags_fails_on_unauthenticated_request(self): responses.POST, url, status=403, - body=json.dumps({'message': 'Your account cannot be authenticated.' - , 'help': 'For support kindly contact us at support@imagekit.io .'}), + body="""{'message': 'Your account cannot be authenticated.' + , 'help': 'For support kindly contact us at support@imagekit.io .'}""", ) self.client.remove_ai_tags(file_ids=[self.file_id], a_i_tags=['remove-ai-tag1', 'remove-ai-tag2']) self.assertRaises(ForbiddenException) @@ -244,27 +239,25 @@ def test_remove_ai_tags_succeeds(self): responses.add( responses.POST, url, - body=json.dumps({ - "successfullyUpdatedFileIds": ["fake_123"] - }), + body='{"successfullyUpdatedFileIds": ["fake_123"]}', headers=headers ) resp = self.client.remove_ai_tags(file_ids=[self.file_id], a_i_tags=['remove-ai-tag-1', 'remove-ai-tag-2']) mock_response_metadata = { - 'headers': { - 'Content-Type': 'text/plain, application/json', - 'Authorization': 'Basic ZmFrZTEyMjo=' - }, - 'httpStatusCode': 200, - 'raw': { - 'successfullyUpdatedFileIds': ['fake_123'] - } - } - request_body = json.dumps({ + 'headers': { + 'Content-Type': 'text/plain, application/json', + 'Authorization': 'Basic ZmFrZTEyMjo=' + }, + 'httpStatusCode': 200, + 'raw': { + 'successfullyUpdatedFileIds': ['fake_123'] + } + } + request_body = make_string_to_single_line('''{ "fileIds": ["fake_123"], - "AITags": ['remove-ai-tag-1', 'remove-ai-tag-2'] - }) + "AITags": ["remove-ai-tag-1", "remove-ai-tag-2"] + }''') self.assertEqual(request_body, responses.calls[0].request.body) self.assertEqual(['fake_123'], resp.successfully_updated_file_ids) self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) @@ -283,11 +276,11 @@ def test_remove_ai_tags_fails_with_404_exception(self) -> None: responses.POST, url, status=404, - body=json.dumps({ + body='''{ "message": "The requested file(s) does not exist.", "help": "For support kindly contact us at support@imagekit.io .", "missingFileIds": ["fake_123"] - }), + }''', headers=headers ) self.client.remove_ai_tags(file_ids=[self.file_id], a_i_tags=['remove-ai-tag-1', 'remove-ai-tag-2'])