Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
Test that the error is thrown and can be correctly handled
"""
try:
response = HttpResponse(404, None, json.dumps({"error":{"code":"itemNotFound", "message":"The resource could not be found"}}))
assert False
except OneDriveError as e:
assert e.status_code == 404
assert e.code == ErrorCode.ItemNotFound
try:
response = HttpResponse(403, None, json.dumps({"error":{"code":"generalException", "message":"TestMessage", "innererror":{"code":"accessDenied", "message":"TestMessage", "innererror":{"code":"unauthenticated", "message":"TestMessage"}}}}))
assert False
except OneDriveError as e:
assert e.status_code == 403
assert e.code == ErrorCode.GeneralException
assert e.matches(ErrorCode.AccessDenied)
assert e.matches(ErrorCode.Unauthenticated)
assert not e.matches(ErrorCode.NotSupported)
def test_error(self, MockHttpProvider, MockAuthProvider):
"""
Test that the error is thrown and can be correctly handled
"""
try:
response = HttpResponse(404, None, json.dumps({"error":{"code":"itemNotFound", "message":"The resource could not be found"}}))
assert False
except OneDriveError as e:
assert e.status_code == 404
assert e.code == ErrorCode.ItemNotFound
try:
response = HttpResponse(403, None, json.dumps({"error":{"code":"generalException", "message":"TestMessage", "innererror":{"code":"accessDenied", "message":"TestMessage", "innererror":{"code":"unauthenticated", "message":"TestMessage"}}}}))
assert False
except OneDriveError as e:
assert e.status_code == 403
assert e.code == ErrorCode.GeneralException
assert e.matches(ErrorCode.AccessDenied)
assert e.matches(ErrorCode.Unauthenticated)
assert not e.matches(ErrorCode.NotSupported)
def exception_handler(self):
error_map = {
ErrorCode.AccessDenied: exceptions.AuthFailure,
ErrorCode.ActivityLimitReached: exceptions.ConnectionFailure,
ErrorCode.GeneralException: exceptions.ProviderOperationFailure,
ErrorCode.InvalidRange: exceptions.ProviderOperationFailure,
ErrorCode.InvalidRequest: exceptions.ProviderOperationFailure,
ErrorCode.ItemNotFound: exceptions.ProviderOperationFailure,
ErrorCode.Malformed: exceptions.ProviderOperationFailure,
ErrorCode.MalwareDetected: exceptions.ProviderOperationFailure,
ErrorCode.NameAlreadyExists: exceptions.ProviderOperationFailure,
ErrorCode.NotAllowed: exceptions.ProviderOperationFailure,
ErrorCode.NotSupported: exceptions.ProviderOperationFailure,
ErrorCode.QuotaLimitReached: exceptions.ConnectionFailure,
ErrorCode.ResourceModified: exceptions.ProviderOperationFailure,
ErrorCode.ResyncRequired: exceptions.ProviderOperationFailure,
ErrorCode.ServiceNotAvailable: exceptions.ConnectionFailure,
ErrorCode.Unauthenticated: exceptions.AuthFailure
}
try:
yield
except OneDriveError as e:
logger.error("OneDriveError in OneDriveProvider: %s", e)
raise error_map.get(e.message.split()[0], exceptions.ProviderOperationFailure)(self)
except Exception as e:
logger.error("General error in OneDriveProvider: %s", e)
raise exceptions.ProviderOperationFailure(self)
def item_request_call(repo, request_func, *args, **kwargs):
while True:
try:
return request_func(*args, **kwargs)
except onedrivesdk.error.OneDriveError as e:
logging.error('Encountered API Error: %s.', e)
if e.code == onedrivesdk.error.ErrorCode.ActivityLimitReached:
time.sleep(THROTTLE_PAUSE_SEC)
elif e.code == onedrivesdk.error.ErrorCode.Unauthenticated:
repo.authenticator.refresh_session(repo.account_id)
else:
raise e
except requests.ConnectionError as e:
logging.error('Encountered connection error: %s. Retry in %d sec.', e, THROTTLE_PAUSE_SEC)
time.sleep(THROTTLE_PAUSE_SEC)
returned_item = item_request_call(self.repo, item_request.upload_async,
local_path=self.local_abspath, upload_status=self.update_progress)
if not isinstance(returned_item, onedrivesdk.Item):
if hasattr(returned_item, '_prop_dict'):
returned_item = onedrivesdk.Item(returned_item._prop_dict)
else:
returned_item = item_request_call(self.repo, item_request.get)
self.update_timestamp_and_record(returned_item, item_stat)
self.task_pool.release_path(self.local_abspath)
logging.info('Finished uploading file "%s".', self.local_abspath)
return True
except (onedrivesdk.error.OneDriveError, OSError) as e:
logging.error('Error uploading file "%s": %s.', self.local_abspath, e)
# TODO: what if quota is exceeded?
if (isinstance(e, onedrivesdk.error.OneDriveError) and
e.code == onedrivesdk.error.ErrorCode.MalwareDetected):
logging.warning('File "%s" was detected as malware by OneDrive. '
'Do not upload during program session.', self.local_abspath)
self.task_pool.occupy_path(self.local_abspath, None)
return False
self.task_pool.release_path(self.local_abspath)
return False
# Remote path is not a directory. Try renaming it and if renaming fails, deleting it.
new_name = get_filename_with_incremented_count(item_name)
logging.info('Remote item "%s" in Drive %s is not a directory. Try renaming it to "%s".',
rel_path, repo.drive.id, new_name)
if not move_item.MoveItemTask(repo=repo, task_pool=self.task_pool,
parent_relpath=parent_relpath, item_name=item_name,
new_name=new_name, is_folder=False).handle():
if not delete_item.DeleteRemoteItemTask(repo=repo, task_pool=self.task_pool,
parent_relpath=parent_relpath,
item_name=item_name, is_folder=False).handle():
logging.warning('Failed to rename or delete remote item "%s" in Drive %s.',
rel_path, repo.drive.id)
return False
except onedrivesdk.error.OneDriveError as e:
if e.code != onedrivesdk.error.ErrorCode.ItemNotFound:
return False
if not merge_dir.CreateFolderTask(repo=repo, task_pool=self.task_pool,
item_name=item_name, parent_relpath=parent_relpath,
upload_if_success=False, abort_if_local_gone=True).handle():
logging.critical('Failed to create remote directory "%s" on Drive %s.', rel_path, repo.drive.id)
return False
return True
def exception_handler(self):
error_map = {
ErrorCode.AccessDenied: exceptions.AuthFailure,
ErrorCode.ActivityLimitReached: exceptions.ConnectionFailure,
ErrorCode.GeneralException: exceptions.ProviderOperationFailure,
ErrorCode.InvalidRange: exceptions.ProviderOperationFailure,
ErrorCode.InvalidRequest: exceptions.ProviderOperationFailure,
ErrorCode.ItemNotFound: exceptions.ProviderOperationFailure,
ErrorCode.Malformed: exceptions.ProviderOperationFailure,
ErrorCode.MalwareDetected: exceptions.ProviderOperationFailure,
ErrorCode.NameAlreadyExists: exceptions.ProviderOperationFailure,
ErrorCode.NotAllowed: exceptions.ProviderOperationFailure,
ErrorCode.NotSupported: exceptions.ProviderOperationFailure,
ErrorCode.QuotaLimitReached: exceptions.ConnectionFailure,
ErrorCode.ResourceModified: exceptions.ProviderOperationFailure,
ErrorCode.ResyncRequired: exceptions.ProviderOperationFailure,
ErrorCode.ServiceNotAvailable: exceptions.ConnectionFailure,
ErrorCode.Unauthenticated: exceptions.AuthFailure
}