diff --git a/imagekitio/file.py b/imagekitio/file.py index 4f7c62c..995e28f 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 @@ -327,7 +330,8 @@ def copy_file( url = "{}/v1/files/copy".format(URL.API_BASE_URL) headers = {"Content-Type": "application/json"} headers.update(self.request.create_headers()) - formatted_options = dumps(request_formatter(options.__dict__)) if options is not None else dict() + formatted_options = dumps(request_formatter(options.__dict__)) + print("here formatted options:--->", formatted_options) resp = self.request.request( method="Post", url=url, headers=headers, data=formatted_options ) @@ -337,8 +341,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 +366,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 +391,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 +418,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 +442,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 +464,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 +487,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 +511,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 +623,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 +639,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 +651,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 +684,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 +711,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/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/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..68d8812 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): @@ -36,8 +34,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 +54,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 +113,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 +128,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 +159,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 +180,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 +210,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 +219,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 +249,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 +257,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 +277,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 +321,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 +351,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 +360,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 +391,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 +419,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 +459,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 +487,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 +534,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 +562,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 +621,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 +649,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 +658,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 +687,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 +713,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 +742,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..d7fccea 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,47 +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 .", - } - ), - ) - self.client.upload_file( - file=self.image, - file_name=self.filename, - options=UploadFileRequestOptions( - use_unique_file_name=False, - tags=["abc", "def"], - folder="/testing-python-folder/", - is_private_file=False, - custom_coordinates="10,10,20,20", - response_fields=[ - "tags", - "custom_coordinates", - "is_private_file", - "embedded_metadata", - "custom_metadata", - ], - extensions=( - { - "name": "remove-bg", - "options": {"add_shadow": True, "bg_color": "pink"}, - }, - { - "name": "google-auto-tagging", - "minConfidence": 80, - "maxTags": 10, - }, - ), - webhook_url="https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e", - overwrite_file=True, - overwrite_a_i_tags=False, - overwrite_tags=False, - overwrite_custom_metadata=True, - custom_metadata={"testss": 12}, - ), + body='''{"message": "Your account cannot be authenticated." + , "help": "For support kindly contact us at support@imagekit.io ."}''', ) self.assertRaises(ForbiddenException) except ForbiddenException as e: @@ -115,99 +76,73 @@ 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", - }, - } - ), - headers=headers, + "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 ) with open(self.sample_image, mode="rb") as img: imgstr = base64.b64encode(img.read()) - resp = self.client.upload_file( - file=imgstr, - file_name="file_name.jpg", - options=UploadFileRequestOptions( - use_unique_file_name=False, - tags=["abc", "def"], - folder="/testing-python-folder/", - is_private_file=True, - response_fields=["is_private_file", "tags"], - extensions=( - { - "name": "remove-bg", - "options": {"add_shadow": True, "bg_color": "pink"}, - }, - {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}, - ), - webhook_url="url", - overwrite_file=True, - overwrite_a_i_tags=False, - overwrite_tags=False, - overwrite_custom_metadata=True, - custom_metadata={"test100": 11}, - ), - ) + resp = self.client.upload_file(file=imgstr, + file_name="file_name.jpg", + + options=UploadFileRequestOptions(use_unique_file_name=False, tags=["abc", "def"], + folder="/testing-python-folder/", + is_private_file=True, + response_fields=["is_private_file", "tags"], + extensions=( + {"name": "remove-bg", + "options": {"add_shadow": True, + "bg_color": "pink"}}, + {"name": "google-auto-tagging", + "minConfidence": 80, "maxTags": 10}), + webhook_url="url", + overwrite_file=True, overwrite_a_i_tags=False, + overwrite_tags=False, + overwrite_custom_metadata=True, + custom_metadata={"test100": 11})) 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", + 'raw': { + 'fileId': 'fake_file_id1234', + 'name': 'file_name.jpg', + 'size': 102117, + 'versionInfo': { + 'id': '62d670648cdb697522602b45', + 'name': 'Version 11' }, }, "httpStatusCode": 200, @@ -217,27 +152,22 @@ def test_binary_upload_succeeds(self): "Authorization": "Basic ZmFrZTEyMjo=", }, } - 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('''{'customMetadata': '{"test100": 11}', + 'extensions': '[{"name": "remove-bg", "options": {"add_shadow": true, ' + '"bg_color": "pink"}}, {"name": "google-auto-tagging", ' + '"minConfidence": 80, "maxTags": 10}]', + 'file': "<_io.BufferedReader name='sample.jpg'>", + 'fileName': 'file_name.jpg', + 'folder': '/testing-python-folder/', + 'isPrivateFile': 'true', + 'overwriteAITags': 'false', + 'overwriteCustomMetadata': 'true', + 'overwriteFile': 'true', + 'overwriteTags': 'false', + 'responseFields': 'isPrivateFile,tags', + 'tags': 'abc,def', + 'useUniqueFileName': 'false', + 'webhookUrl': 'url'}''') actual_body = responses.calls[0].request.body.__dict__.__getitem__("fields") actual_body["file"] = "<_io.BufferedReader name='sample.jpg'>" self.assertEqual(request_body, actual_body) @@ -324,11 +254,8 @@ def test_upload_fails_with_400_exception(self) -> None: ) self.assertRaises(BadRequestException) except BadRequestException as e: - self.assertEqual( - "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.", - e.message, - ) + self.assertEqual("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.", e.message) self.assertEqual(400, e.response_metadata.http_status_code) @@ -348,17 +275,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,41 +297,39 @@ 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( @@ -425,40 +346,45 @@ def test_list_files_succeeds_with_basic_request(self) -> None: "Accept-Encoding": "gzip, deflate", "Authorization": "Basic ZmFrZTEyMjo=", }, - "httpStatusCode": 200, - "raw": [ - { - "AITags": None, - "createdAt": "2022-06-15T08:19:00.843Z", - "customCoordinates": "10,10,20,20", - "customMetadata": {"test100": 10}, - "embeddedMetadata": { - "DateCreated": "2022-06-15T08:19:01.523Z", - "DateTimeCreated": "2022-06-15T08:19:01.524Z", - "XResolution": 250, - "YResolution": 250, - }, - "fileId": "62a995f4d875ec08dc587b72", - "filePath": "/sample-cat-image_gr64HPlJS.jpg", - "fileType": "image", - "hasAlpha": False, - "height": 354, - "isPrivateFile": False, - "mime": "image/jpeg", - "name": "sample-cat-image_gr64HPlJS.jpg", - "size": 23023, - "tags": ["{Tag_1", " Tag_2", " Tag_3}", "tag-to-add-2"], - "thumbnail": "https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/sample-cat-image_gr64HPlJS.jpg", - "type": "file", - "updatedAt": "2022-06-15T08:19:45.169Z", - "url": "https://ik.imagekit.io/your_imagekit_id/sample-cat-image_gr64HPlJS.jpg", - "versionInfo": { - "id": "62a995f4d875ec08dc587b72", - "name": "Version " "1", - }, - "width": 236, - } - ], + 'httpStatusCode': 200, + 'raw': [{ + 'AITags': '', + 'createdAt': '2022-06-15T08:19:00.843Z', + 'customCoordinates': '10,10,20,20', + 'customMetadata': { + 'test100': 10 + }, + 'embeddedMetadata': { + 'DateCreated': '2022-06-15T08:19:01.523Z', + 'DateTimeCreated': '2022-06-15T08:19:01.524Z', + 'XResolution': 250, + 'YResolution': 250 + }, + 'fileId': '62a995f4d875ec08dc587b72', + 'filePath': '/sample-cat-image_gr64HPlJS.jpg', + 'fileType': 'image', + 'hasAlpha': False, + 'height': 354, + 'isPrivateFile': False, + 'mime': 'image/jpeg', + 'name': 'sample-cat-image_gr64HPlJS.jpg', + 'size': 23023, + 'tags': ['{Tag_1', + ' Tag_2', + ' Tag_3}', + 'tag-to-add-2' + ], + 'thumbnail': 'https://ik.imagekit.io/your_imagekit_id/tr:n-ik_ml_thumbnail/sample-cat-image_gr64HPlJS.jpg', + 'type': 'file', + 'updatedAt': '2022-06-15T08:19:45.169Z', + 'url': 'https://ik.imagekit.io/your_imagekit_id/sample-cat-image_gr64HPlJS.jpg', + 'versionInfo': { + 'id': '62a995f4d875ec08dc587b72', + 'name': 'Version ' + '1' + }, + 'width': 236 + }] } 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", @@ -480,19 +406,12 @@ 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 .", - } - ), - 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" - ) - ], + 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")], ) self.client.list_files(self.options) self.assertRaises(BadRequestException) @@ -525,12 +444,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,72 +462,9 @@ 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", - }, - { - "name": "Smile", - "confidence": 95.31, - "source": "google-auto-tagging", - }, - ], - "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", - } - ), - 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=", - }, - "httpStatusCode": 200, - "raw": { - "AITags": [ - { - "confidence": 98.77, - "name": "Clothing", - "source": "google-auto-tagging", - }, - { - "confidence": 95.31, - "name": "Smile", - "source": "google-auto-tagging", - }, - ], + body='''{ + "type": "file", + "name": "new_car.jpg", "createdAt": "2022-06-15T11:34:36.294Z", "customCoordinates": "null", "customMetadata": {"test10": 11, "test100": 10}, @@ -620,7 +472,10 @@ def test_file_details_succeeds_with_id(self) -> None: "DateCreated": "2022-07-04T10:15:50.066Z", "DateTimeCreated": "2022-07-04T10:15:50.066Z", }, - "fileId": "fake_file_id1234", + "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", "fileType": "image", "hasAlpha": False, @@ -629,14 +484,61 @@ def test_file_details_succeeds_with_id(self) -> None: "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", + "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=' + }, + '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' + }, + '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' }, "width": 236, }, @@ -663,12 +565,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) @@ -699,21 +597,9 @@ 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) - except ForbiddenException as e: - self.assertEqual(e.message, "Your account cannot be authenticated.") - self.assertEqual(e.response_metadata.http_status_code, 403) - - @responses.activate - def test_bulk_file_delete_succeeds(self): """Test bulk_delete on authenticated request this function tests if bulk_file_delete working properly """ @@ -726,33 +612,19 @@ def test_bulk_file_delete_succeeds(self): responses.add( responses.POST, url, - body=json.dumps({"successfullyDeletedFileIds": ["fake_123", "fake_222"]}), - headers=headers, + body='{"successfullyDeletedFileIds": ["fake_123", "fake_222"]}', + headers=headers ) - resp = self.client.bulk_file_delete(self.bulk_delete_ids) - mock_response_metadata = { - "raw": {"successfullyDeletedFileIds": ["fake_123", "fake_222"]}, - "httpStatusCode": 200, - "headers": { "Content-Type": "text/plain, application/json", "Authorization": "Basic ZmFrZTEyMjo=", }, } - self.assertEqual( - json.dumps({"fileIds": ["fake_123", "fake_222"]}), - responses.calls[0].request.body, - ) - self.assertEqual( - camel_dict_to_snake_dict(mock_response_metadata), - resp.response_metadata.__dict__, - ) - self.assertEqual(["fake_123", "fake_222"], resp.successfully_deleted_file_ids) - self.assertEqual( - "http://test.com/v1/files/batch/deleteByFileIds", - responses.calls[0].request.url, - ) + self.assertEqual('{"fileIds": ["fake_123", "fake_222"]}', responses.calls[0].request.body) + self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) + self.assertEqual(['fake_123', 'fake_222'], resp.successfully_deleted_file_ids) + self.assertEqual("http://test.com/v1/files/batch/deleteByFileIds", responses.calls[0].request.url) @responses.activate def test_bulk_file_delete_fails_with_404_exception(self) -> None: @@ -767,14 +639,12 @@ 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"], - } - ), - headers=headers, + 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) self.assertRaises(NotFoundException) @@ -801,13 +671,11 @@ 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 .", - } - ), - headers=headers, + 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) self.assertRaises(BadRequestException) @@ -828,7 +696,11 @@ def test_file_delete_succeeds(self): headers.update(get_auth_headers_for_test()) responses.add( - responses.DELETE, url, body=json.dumps({}), status=204, headers=headers + responses.DELETE, + url, + body="{}", + status=204, + headers=headers ) resp = self.client.delete_file(self.file_id) @@ -865,12 +737,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 +758,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 +777,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 = { @@ -917,18 +785,11 @@ def test_purge_file_cache_succeeds(self): "httpStatusCode": 201, "headers": {"Content-Type": "text/plain"}, } - self.assertEqual( - camel_dict_to_snake_dict(mock_response_metadata), - resp.response_metadata.__dict__, - ) - self.assertEqual("requestId", resp.request_id) - self.assertEqual( - "http://test.com/v1/files/purge", responses.calls[0].request.url - ) - self.assertEqual( - json.dumps({"url": "https://example.com/fakeid/fakeimage.jpg"}), - responses.calls[0].request.body, - ) + self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) + self.assertEqual('requestId', resp.request_id) + self.assertEqual("http://test.com/v1/files/purge", responses.calls[0].request.url) + self.assertEqual('{"url": "https://example.com/fakeid/fakeimage.jpg"}', + responses.calls[0].request.body) class TestPurgeCacheStatus(ClientTestCase): @@ -946,12 +807,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 +826,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 +861,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 +884,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,17 +935,11 @@ 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 .", - } - ), - match=[ - matchers.query_string_matcher( - "url=https://example.com/fakeid/fakeimage.jpg" - ) - ], + 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")] ) self.client.get_remote_file_url_metadata(self.fake_image_url) self.assertRaises(BadRequestException) @@ -1115,25 +960,19 @@ 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", - } - ), - match=[ - matchers.query_string_matcher( - "url=https://example.com/fakeid/fakeimage.jpg" - ) - ], + 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")] ) resp = self.client.get_remote_file_url_metadata(self.fake_image_url) mock_response_metadata = { @@ -1185,12 +1024,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 @@ -1204,95 +1039,15 @@ def test_update_file_details_fails_on_unauthenticated_request(self): def test_update_file_details_succeeds_with_id(self): """ Tests if update file details succeeds with file id - """ - URL.API_BASE_URL = "http://test.com" - url = "{}/v1/files/{}/details/".format(URL.API_BASE_URL, self.file_id) - headers = {"Content-Type": "application/json"} - headers.update(get_auth_headers_for_test()) - responses.add( - responses.PATCH, - url, - body=json.dumps( - { - "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", - }, - "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", - }, - } - ), - headers=headers, - ) - - 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}, - } - resp = self.client.update_file_details( - file_id=self.file_id, - options=UpdateFileRequestOptions( - remove_a_i_tags=["ai-tag1", "ai-tag2"], - webhook_url="url", - extensions=[ - { - "name": "remove-bg", - "options": {"add_shadow": True, "bg_color": "red"}, - }, - {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}, - ], - tags=["tag1", "tag2"], - custom_coordinates="10,10,100,100", - custom_metadata={"test": 11}, - ), - ) - mock_response_metadata = { - "raw": { + """ + URL.API_BASE_URL = "http://test.com" + url = "{}/v1/files/{}/details/".format(URL.API_BASE_URL, self.file_id) + headers = {"Content-Type": "application/json"} + headers.update(get_auth_headers_for_test()) + responses.add( + responses.PATCH, + url, + body='''{ "type": "file", "name": "default-image.jpg", "createdAt": "2022-07-21T10:31:22.529Z", @@ -1319,8 +1074,10 @@ def test_update_file_details_succeeds_with_id(self): "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", @@ -1328,11 +1085,75 @@ 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 = 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 + }], + "tags": ["tag1", "tag2"], + "customCoordinates": "10,10,100,100", + "customMetadata": { + "test": 11 + } + }''') + resp = self.client.update_file_details(file_id=self.file_id, + options=UpdateFileRequestOptions(remove_a_i_tags=['ai-tag1', 'ai-tag2'], + webhook_url="url", + extensions=[ + { + "name": "remove-bg", + "options": { + "add_shadow": True, + "bg_color": "red" + } + }, + { + "name": "google-auto-tagging", + "minConfidence": 80, + "maxTags": 10 + }], + 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' }, }, "httpStatusCode": 200, @@ -1341,15 +1162,10 @@ def test_update_file_details_succeeds_with_id(self): "Authorization": "Basic ZmFrZTEyMjo=", }, } - self.assertEqual(json.dumps(request_body), responses.calls[0].request.body) - self.assertEqual( - camel_dict_to_snake_dict(mock_response_metadata), - resp.response_metadata.__dict__, - ) - self.assertEqual("fake_123", resp.file_id) - self.assertEqual( - "http://test.com/v1/files/fake_123/details/", responses.calls[0].request.url - ) + self.assertEqual(request_body, responses.calls[0].request.body) + self.assertEqual(camel_dict_to_snake_dict(mock_response_metadata), resp.response_metadata.__dict__) + self.assertEqual('fake_123', resp.file_id) + self.assertEqual("http://test.com/v1/files/fake_123/details/", responses.calls[0].request.url) @responses.activate def test_update_file_details_fails_with_404_exception(self) -> None: @@ -1362,12 +1178,8 @@ 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 = { @@ -1434,12 +1246,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,107 +1268,102 @@ 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", - }, - ] - ), - headers=headers, + 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 = { @@ -1688,12 +1491,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 +1514,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,49 +1538,18 @@ 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", - } - ), - headers=headers, - ) - resp = self.client.get_file_version_details(self.file_id, self.version_id) - mock_response_metadata = { - "raw": { + 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": None, - "versionInfo": {"id": "fake_version_123", "name": "Version 1"}, + "AITags": "", + "versionInfo": { + "id": "fake_version_123", + "name": "Version 1" + }, "embeddedMetadata": { "XResolution": 250, "YResolution": 250, @@ -1793,8 +1557,10 @@ def test_get_file_version_details_succeeds_with_id(self): "DateTimeCreated": "2022-06-15T11:34:36.702Z", }, "customCoordinates": "10,10,20,20", - "customMetadata": {"test100": 10}, - "isPrivateFile": False, + "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", @@ -1802,13 +1568,45 @@ def test_get_file_version_details_succeeds_with_id(self): "height": 354, "width": 236, "size": 23023, - "hasAlpha": False, - "mime": "image/jpeg", - }, - "httpStatusCode": 200, - "headers": { - "Content-Type": "text/plain, application/json", - "Authorization": "Basic ZmFrZTEyMjo=", + "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': '', + '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' }, } @@ -1836,12 +1634,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 +1656,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 +1685,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) @@ -1919,7 +1705,11 @@ 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.DELETE, + url, + status=204, + headers=headers, + body='{}' ) resp = self.client.delete_file_version(self.file_id, self.version_id) @@ -1961,13 +1751,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( @@ -1991,14 +1779,11 @@ def test_copy_file_succeeds(self) -> None: headers = {"Content-Type": "application/json"} headers.update(create_headers_for_test()) responses.add( - responses.POST, url, status=204, headers=headers, body=json.dumps({}) - ) - resp = self.client.copy_file( - options=CopyFileRequestOptions( - source_file_path=self.source_file_path, - destination_path=self.destination_path, - include_file_versions=True, - ) + responses.POST, + url, + status=204, + headers=headers, + body='{}' ) mock_response_metadata = { @@ -2011,13 +1796,11 @@ 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) self.assertEqual( @@ -2047,13 +1830,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( @@ -2076,13 +1857,11 @@ def test_move_file_succeeds(self) -> None: headers = {"Content-Type": "application/json"} headers.update(create_headers_for_test()) responses.add( - responses.POST, url, status=204, headers=headers, body=json.dumps({}) - ) - resp = self.client.move_file( - options=MoveFileRequestOptions( - source_file_path=self.source_file_path, - destination_path=self.destination_path, - ) + responses.POST, + url, + status=204, + headers=headers, + body='{}' ) mock_response_metadata = { @@ -2095,12 +1874,10 @@ 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) self.assertEqual( @@ -2131,18 +1908,11 @@ 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", - } - ), - ) - self.client.rename_file( - options=RenameFileRequestOptions( - file_path=self.file_path, new_file_name=self.new_file_name - ) + 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.assertRaises(ConflictException) except ConflictException as e: @@ -2165,14 +1935,7 @@ def test_rename_file_succeeds_with_purge_cache(self) -> None: responses.PUT, url, headers=headers, - body=json.dumps({"purgeRequestId": "62de3e986f68334a5a3339fb"}), - ) - resp = self.client.rename_file( - options=RenameFileRequestOptions( - file_path=self.file_path, - new_file_name=self.new_file_name, - purge_cache=True, - ) + body='{"purgeRequestId": "62de3e986f68334a5a3339fb"}' ) mock_response_metadata = { @@ -2185,13 +1948,11 @@ 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) self.assertEqual( @@ -2211,11 +1972,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({})) - resp = self.client.rename_file( - options=RenameFileRequestOptions( - file_path=self.file_path, new_file_name=self.new_file_name - ) + responses.add( + responses.PUT, + url, + headers=headers, + body="{}" ) mock_response_metadata = { @@ -2228,9 +1989,10 @@ 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) self.assertEqual( @@ -2260,12 +2022,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,59 +2045,25 @@ 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, "height": 100, @@ -2347,14 +2071,60 @@ def test_restore_file_version_succeeds(self) -> None: "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=' }, + 'httpStatusCode': 200, + 'raw': { + 'AITags': [{ + 'confidence': 90.12, + 'name': 'Shirt', + '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' + }, + 'width': 100 + } } 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'])